From 27fa8e2e4fb86273a6880b75b69e08d1292d64c2 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 18 Feb 2025 17:24:39 +0200 Subject: [PATCH] Adds media library scan progress tracking --- .../architecture-decission-record-0002.md | 82 +++++++++++ .../ApplicationLayerServices.cs | 19 +-- .../Models/Scanning/MediaScanTrackerModel.cs | 12 -- .../GetLibraryScanProgressRequestMapping.cs | 25 ++++ .../Management/LibraryScanEntityMapping.cs | 2 +- .../MediaLibraryScanJobProgressMapping.cs | 27 ++++ .../MediaLibraryScanProgressMapping.cs | 28 ++++ .../ScanLibraries/ScanLibrariesCommand.cs | 2 +- .../ScanLibrariesCommandHandler.cs | 8 +- .../ScanLibrary/ScanLibraryCommand.cs | 2 +- .../ScanLibrary/ScanLibraryCommandHandler.cs | 6 +- .../LibraryScanFailedDomainEventHandler.cs | 2 +- .../LibraryScanFinishedDomainEventHandler.cs | 83 +++++++++++ ...canJobProgressChangedDomainEventHandler.cs | 38 +++++ ...ryScanProgressChangedDomainEventHandler.cs | 14 ++ .../GetLibrary/GetLibraryQueryHandler.cs | 3 +- .../GetLibraryScanProgressQuery.cs | 18 +++ .../GetLibraryScanProgressQueryHandler.cs | 82 +++++++++++ .../GetLibraryScanProgressQueryValidator.cs | 26 ++++ .../MediaLibrariesScanCancellationTracker.cs | 101 -------------- .../Scanning/Jobs/Common/HashComparerJob.cs | 48 ------- .../Common/RepositoryMetadataDiscoveryJob.cs | 42 ------ .../Books/GoodReadsMetadataScrapJob.cs | 43 ------ .../GetLibraryScanProgressRequest.cs | 17 +++ .../MediaLibraryScanJobProgressResponse.cs | 20 +++ .../MediaLibraryScanProgressResponse.cs | 24 ++++ ...esponse.cs => MediaLibraryScanResponse.cs} | 2 +- .../UpdateAuditableEntitiesInterceptor.cs | 2 +- .../DomainLayerServices.cs | 5 +- .../Common/Errors/Errors.LibraryScanning.cs | 7 +- ...t.cs => LibraryScanFinishedDomainEvent.cs} | 14 +- ...ibraryScanJobProgressChangedDomainEvent.cs | 26 ++++ .../LibraryScanProgressChangedDomainEvent.cs | 9 +- .../LibraryScanAggregate/LibraryScan.cs | 14 ++ .../IMediaLibrariesScanCancellationTracker.cs | 33 ++--- .../Jobs/IRepositoryMetadataSaveJob.cs | 9 ++ .../Services/Jobs/MediaLibraryScanJob.cs | 1 - .../Services/MediaLibraryScanningService.cs | 96 ++++++++++--- .../IMediaLibrariesScanProgressTracker.cs | 44 ++++++ .../MediaLibrariesScanProgressTracker.cs | 106 ++++++++++++++ .../IMediaLibraryScannerFactory.cs | 2 +- .../{Common => }/IMediaTypeScanner.cs | 2 +- .../MediaLibraryScannerFactory.cs | 2 +- .../MediaLibraryScanCompositeId.cs | 54 ++++++++ ...ress.cs => MediaLibraryScanJobProgress.cs} | 18 +-- .../ValueObjects/MediaLibraryScanProgress.cs | 98 +++++++++++++ .../Scanners/BookLibraryTypeScanner.cs | 10 ++ .../Scanners/IBookLibraryTypeScanner.cs | 3 +- src/Lumina.Domain/Lumina.Domain.csproj | 4 - .../InfrastructureLayerServices.cs | 19 +++ .../MediaLibrariesScanCancellationTracker.cs | 86 ++++++++++++ .../Jobs/Common/FileSystemDiscoveryJob.cs | 128 +++++++++-------- .../Scanning/Jobs/Common/HashComparerJob.cs | 115 +++++++++++++++ .../Common/RepositoryMetadataDiscoveryJob.cs | 118 ++++++++++++++++ .../Jobs/Common/RepositoryMetadataSaveJob.cs | 116 ++++++++++++++++ .../Jobs/Payloads/FileSystemTreeNode.cs | 2 +- .../Books/GoodReadsMetadataScrapJob.cs | 116 ++++++++++++++++ .../Scanning/Queue/MediaLibrariesScanQueue.cs | 7 +- .../Queue/MediaLibraryScanJobProcessorJob.cs | 5 +- .../EventualConsistencyMiddleware.cs | 10 +- .../GetLibraryScanProgressEndpoint.cs | 54 ++++++++ .../GetLibraryScanProgressEndpointSummary.cs | 131 ++++++++++++++++++ .../ScanLibraries/ScanLibrariesEndpoint.cs | 2 +- .../ScanLibrariesEndpointSummary.cs | 2 +- .../ScanLibrary/ScanLibraryEndpoint.cs | 2 +- .../ScanLibrary/ScanLibraryEndpointSummary.cs | 2 +- .../ExceptionHandlingMiddleware.de-DE.resx | 12 ++ .../ExceptionHandlingMiddleware.en-US.resx | 12 ++ .../ExceptionHandlingMiddleware.es-ES.resx | 12 ++ .../ExceptionHandlingMiddleware.fr-FR.resx | 12 ++ .../ExceptionHandlingMiddleware.it-IT.resx | 12 ++ .../ExceptionHandlingMiddleware.ja-JP.resx | 12 ++ .../ExceptionHandlingMiddleware.resx | 12 ++ .../ExceptionHandlingMiddleware.ro-RO.resx | 12 ++ .../ExceptionHandlingMiddleware.ru-RU.resx | 12 ++ .../ExceptionHandlingMiddleware.zh-CN.resx | 12 ++ .../Views/Library/Management/Index.de-DE.resx | 12 ++ .../Views/Library/Management/Index.en-US.resx | 12 ++ .../Views/Library/Management/Index.es-ES.resx | 12 ++ .../Views/Library/Management/Index.fr-FR.resx | 12 ++ .../Views/Library/Management/Index.it-IT.resx | 12 ++ .../Views/Library/Management/Index.ja-JP.resx | 12 ++ .../Views/Library/Management/Index.resx | 12 ++ .../Views/Library/Management/Index.ro-RO.resx | 12 ++ .../Views/Library/Management/Index.ru-RU.resx | 12 ++ .../Views/Library/Management/Index.zh-CN.resx | 12 ++ src/Lumina.sln | 9 +- 87 files changed, 2078 insertions(+), 421 deletions(-) create mode 100644 docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0002.md delete mode 100644 src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryScanProgressRequest.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs rename src/Lumina.Contracts/Responses/MediaLibrary/Management/{ScanLibraryResponse.cs => MediaLibraryScanResponse.cs} (94%) rename src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/{LibraryScanCompletedDomainEvent.cs => LibraryScanFinishedDomainEvent.cs} (52%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs rename src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/{Common => }/IMediaLibraryScannerFactory.cs (93%) rename src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/{Common => }/IMediaTypeScanner.cs (95%) rename src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/{Common => }/MediaLibraryScannerFactory.cs (98%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs rename src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/{ScanJobProgress.cs => MediaLibraryScanJobProgress.cs} (80%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services => Lumina.Infrastructure/Core/MediaLibrary/Management}/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs (57%) create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services => Lumina.Infrastructure/Core/MediaLibrary/Management}/Scanning/Jobs/Payloads/FileSystemTreeNode.cs (91%) create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services => Lumina.Infrastructure/Core/MediaLibrary/Management}/Scanning/Queue/MediaLibrariesScanQueue.cs (86%) rename src/{Lumina.Application/Core/MediaLibrary/Management/Services => Lumina.Infrastructure/Core/MediaLibrary/Management}/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs (91%) create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0002.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0002.md new file mode 100644 index 00000000..d877f881 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0002.md @@ -0,0 +1,82 @@ +# Architecture Decision Record (ADR): 0002 - Transaction commit before event publishing in Eventual Consistency Middleware + +## Status +**Accepted** (2025-02-18) + +## Context +The system requires reliable coordination between database transactions and domain event processing in scenarios involving: + +1. **Background service isolation**: Long-running operations triggered by domain events execute in singleton-hosted services with separate dependency injection scopes. +2. **Transaction visibility requirements**: Subsequent operations in child scopes must see committed database state. +3. **Eventual consistency needs**: Event handlers may spawn follow-up operations requiring atomic transaction boundaries. + +The previous implementation published domain events *before* transaction commit, causing: + +| Problem | Impact | +|---------------------------|---------------------------------------------------------------------------| +| Phantom reads | Background services saw pre-commit state via separate DbContext instances | +| Stale data actions | Event handlers executed against uncommitted changes | +| Scope lifetime mismatch | Singleton services couldn't access request-scoped transaction context | + +## Decision +Enforce strict commit-before-publish sequence in `EventualConsistencyMiddleware`: + +```csharp +context.Response.OnCompleted(async () => +{ + if (IsSuccessfulResponse(context)) + { + await transaction.CommitAsync(); // commit FIRST + await PublishEvents(publisher, domainEventQueue); // THEN publish + } + await transaction.DisposeAsync(); +}); +``` + + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|-------------------|-------------------------------------------------------------------| +| Data visibility | Guarantees event handlers see committed state | +| Atomicity | Prevents partial updates from being visible | +| Error recovery | Failed event publishing doesn't rollback committed transactions | +| Scope alignment | Matches DbContext lifetime with transaction boundaries | + +### Risks and Tradeoffs + +| Risk | Mitigation Strategy | +|-------------------------------|-----------------------------------------------------------------------| +| Event loss after commit | Implement dead-letter queue with compensation handlers (to be done) | +| Non-atomic event publishing | Use outbox pattern for critical events (to be done) | +| Transaction timeout | Configure SQL Server `SET LOCK_TIMEOUT` appropriately | + +## Alternatives Considered + +### 1. Transactional Outbox Pattern +```csharp +// store events in outbox table within transaction +dbContext.OutboxMessages.AddRange(events); +await dbContext.SaveChangesAsync(); + +// separate worker publishes from outbox +``` + +**Rejected** for non-critical events due to: +- Added infrastructure complexity (outbox table + worker) +- Increased latency for non-critical notifications +- Overkill for non-idempotent operations + +### 2. Two-Phase Commit (2PC) +```csharp +using (TransactionScope scope = new(TransactionScopeAsyncFlowOption.Enabled)) +{ + // distributed transaction coordination +} +``` +**Rejected** due to: +- Unsupported in polyglot persistence environment +- Performance overhead from MSDTC coordination +- Conflict with cloud-native architecture principles diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index c7eb4276..ec060e21 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -2,14 +2,6 @@ using FluentValidation; using Lumina.Application.Common.Behaviors; using Lumina.Application.Common.DomainEvents; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; -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; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Mediator; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; @@ -43,16 +35,7 @@ public static class ApplicationLayerServices services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); services.AddScoped(); - - services.AddSingleton(); - services.AddSingleton(); - services.AddHostedService(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - + return services; } } diff --git a/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs b/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs deleted file mode 100644 index 029bb64c..00000000 --- a/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -#endregion - -namespace Lumina.Application.Common.Infrastructure.Models.Scanning; - -/// -/// Model for tracking media library scans. -/// -/// The unique identifier of the media library scan to be tracked. -/// The unique identifier of the username who initiated the media library scan. -public record MediaScanTrackerModel(Guid ScanId, Guid UserId); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMapping.cs new file mode 100644 index 00000000..e255491d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; +using Lumina.Contracts.Requests.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryScanProgressRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryScanProgressQuery ToQuery(this GetLibraryScanProgressRequest request) + { + return new GetLibraryScanProgressQuery( + request.LibraryId, + request.ScanId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs index 85bee581..d6a0a78f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs @@ -23,7 +23,7 @@ public static class LibraryScanEntityMapping /// /// The repository entity to be converted. /// - /// An containing either a collection of converted , or an error message. + /// An containing either a converted , or an error message. /// public static ErrorOr ToDomainEntity(this LibraryScanEntity repositoryEntity) { diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMapping.cs new file mode 100644 index 00000000..bc4adcb9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class MediaLibraryScanJobProgressMapping +{ + /// + /// Converts to . + /// + /// The domain value object to be converted. + /// The converted response. + public static MediaLibraryScanJobProgressResponse ToResponse(this MediaLibraryScanJobProgress domainValueObject) + { + return new MediaLibraryScanJobProgressResponse( + domainValueObject.CompletedItems, + domainValueObject.TotalItems, + domainValueObject.CurrentOperation, + domainValueObject.ProgressPercentage + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs new file mode 100644 index 00000000..f90f94d5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class MediaLibraryScanProgressMapping +{ + /// + /// Converts to . + /// + /// The domain value object to be converted. + /// The converted response. + public static MediaLibraryScanProgressResponse ToResponse(this MediaLibraryScanProgress domainValueObject) + { + return new MediaLibraryScanProgressResponse( + domainValueObject.TotalJobs, + domainValueObject.CompletedJobs, + domainValueObject.CurrentJobProgress.Value?.ToResponse(), + domainValueObject.Status, + domainValueObject.OverallProgressPercentage + ); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs index f06b1af9..f97762c4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs @@ -10,4 +10,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Command for initiating the scan of all media libraries. /// -public record ScanLibrariesCommand() : IRequest>>; +public record ScanLibrariesCommand() : IRequest>>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index 6f584c4e..aad83b67 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Handler for the command for initiating the scan of all media libraries. /// -public class ScanLibrariesCommandHandler : IRequestHandler>> +public class ScanLibrariesCommandHandler : IRequestHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -57,7 +57,7 @@ public class ScanLibrariesCommandHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken) + public async ValueTask>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken) { ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); @@ -74,7 +74,7 @@ public class ScanLibrariesCommandHandler : IRequestHandler libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value); - List responses = []; + List responses = []; List domainEvents = []; // for each library, start the scan @@ -118,7 +118,7 @@ public class ScanLibrariesCommandHandler : IRequestHandlerThe unique identifier of the library to scan. public record ScanLibraryCommand( Guid Id -) : IRequest>; +) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 58b4b9cd..472cd2ea 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -28,7 +28,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; /// /// Handler for the command for initiating the scan of a media library. /// -public class ScanLibraryCommandHandler : IRequestHandler> +public class ScanLibraryCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; @@ -60,7 +60,7 @@ public class ScanLibraryCommandHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async ValueTask> Handle(ScanLibraryCommand request, CancellationToken cancellationToken) + public async ValueTask> Handle(ScanLibraryCommand request, CancellationToken cancellationToken) { ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); @@ -125,6 +125,6 @@ public class ScanLibraryCommandHandler : IRequestHandler failScanResult = libraryScanDomainResult.Value.FailScan(); - // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs might trigger this domain event, + // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, // trying to set as failed a scan that has already been marked as failed by a concurrent job if (!failScanResult.IsError) { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs new file mode 100644 index 00000000..5fbd5279 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; +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 Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library scan is finished. +/// +public class LibraryScanFinishedDomainEventHandler : INotificationHandler +{ + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for tracking the progress of media library scans. + /// Injected tracker used for canceling media library scans. + /// Injected unit of work for interacting with the data access layer repositories. + public LibraryScanFinishedDomainEventHandler( + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, + IUnitOfWork unitOfWork) + { + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the event raised when a media library scan is finished. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) + { + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the library scan from the repository + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsError) + throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); + if (getLibraryScansResult.Value is null) + throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); + + // convert the repository scan to a domain object + ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsError) + throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); + + // mark the media library scan as finished + ErrorOr finishScanResult = libraryScanDomainResult.Value.FinishScan(); + if (finishScanResult.IsError) + throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors); + + // update the library scan in the repository + ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsError) + throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // mark the scan progress as completed, and remove its cancellation tracking + _mediaLibrariesScanProgressTracker.UpdateScanProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId)); + _mediaLibrariesScanCancellationTracker.RemoveScan(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId)); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs new file mode 100644 index 00000000..f2c47693 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandler.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library's scan progress changes. +/// +public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHandler +{ + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected tracker used for media library scans progress. + public LibraryScanJobProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) + { + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + } + + /// + /// Handles the event raised when a media library's scan progress changes. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) + { + _mediaLibrariesScanProgressTracker.UpdateScanJobProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId), domainEvent.Progress); + await Task.CompletedTask; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs index 7846699e..af3c74d4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Mediator; using System.Threading; using System.Threading.Tasks; @@ -12,6 +14,17 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler { + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected tracker used for media library scans progress. + public LibraryScanProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) + { + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + } + /// /// Handles the event raised when a media library's scan progress changes. /// @@ -19,6 +32,7 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler /// Cancellation token that can be used to stop the execution. public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) { + _mediaLibrariesScanProgressTracker.UpdateScanProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId)); await Task.CompletedTask; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index 0e726d85..1a360c62 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -62,8 +62,7 @@ public class GetLibraryQueryHandler : IRequestHandler +/// Query for getting the progress of a media library scan. +/// +/// The Id of the media library whose scan progress is requested. +/// The Id of the media library scan whose progress is requested. +public record GetLibraryScanProgressQuery( + Guid LibraryId, + Guid ScanId +) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs new file mode 100644 index 00000000..71cec463 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.Authorization; +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; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; + +/// +/// Handler for the query to get the progress of a library scan. +/// +public class GetLibraryScanProgressQueryHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for tracking the progress of media library scans. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetLibraryScanProgressQueryHandler( + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IUnitOfWork unitOfWork) + { + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the progress of a library scan. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error message. + /// + public async ValueTask> Handle(GetLibraryScanProgressQuery request, CancellationToken cancellationToken) + { + // get the library with the specified id from the repository + ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError) + return getLibraryResult.Errors; + else if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to view its scan progress + if (getLibraryResult.Value.UserId != _currentUserService.UserId || + !await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + ErrorOr getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( + MediaLibraryScanCompositeId.Create(ScanId.Create(request.ScanId), UserId.Create(_currentUserService.UserId!.Value))); + if (getProgressResult.IsError) + return getProgressResult.Errors; + + return getProgressResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs new file mode 100644 index 00000000..c68edca1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryScanProgressQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryScanProgressQueryValidator() + { + RuleFor(x => x.ScanId) + .NotEmpty().WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description); + RuleFor(x => x.LibraryId) + .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs deleted file mode 100644 index 3a07f698..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs +++ /dev/null @@ -1,101 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Models.Scanning; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; -using System; -using System.Collections.Concurrent; -using System.Threading; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation; - -/// -/// Tracker used for canceling in-memory media library scans. -/// -internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable -{ - private readonly ConcurrentDictionary _runningScans = new(); - private bool _disposed; - - /// - /// Registers a new scan operation for tracking. - /// - /// The unique identifier of the scan operation to track. - /// The unique identifier of the user who initiated the scan to track. - public void RegisterScan(Guid scanId, Guid userId) - { - _runningScans.TryAdd(new MediaScanTrackerModel(scanId, userId), new CancellationTokenSource()); - } - - /// - /// Gets the cancellation token for a scan identified by and . - /// - /// The unique identifier of the scan to get the cancellation token for<./param> - /// The unique identifier of the user who initiated the scan for which to get the cancellation token. - /// A cancellation token for the specified scan. - public CancellationToken GetTokenForScan(Guid scanId, Guid userId) - { - return _runningScans.TryGetValue(new MediaScanTrackerModel(scanId, userId), out CancellationTokenSource? scan) - ? scan.Token - : CancellationToken.None; - } - - /// - /// Cancels a scan identified by and . - /// - /// The unique identifier of the scan operation to cancel. - /// The unique identifier of the user requesting the cancellation. - public void CancelScan(Guid scanId, Guid userId) - { - foreach (MediaScanTrackerModel key in _runningScans.Keys) - { - if (key.ScanId == scanId && key.UserId == userId) - { - if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan)) - { - scan.Cancel(); - // remove and dispose after cancellation - if (_runningScans.TryRemove(key, out CancellationTokenSource? removedScan)) - removedScan?.Dispose(); - } - } - } - } - - /// - /// Cancels all active scan operations for a user identified by . - /// - /// The unique identifier of the user whose scans should be canceled. - public void CancelUserScans(Guid userId) - { - foreach (MediaScanTrackerModel key in _runningScans.Keys) - { - if (key.UserId == userId) - { - if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan)) - { - scan.Cancel(); - // remove and dispose after cancellation - if (_runningScans.TryRemove(key, out CancellationTokenSource? removedScan)) - removedScan?.Dispose(); - } - } - } - } - - /// - /// Disposes the tracker and cancels all media library scans. - /// - public void Dispose() - { - if (!_disposed) - { - foreach (CancellationTokenSource scan in _runningScans.Values) - { - scan.Cancel(); - scan.Dispose(); - } - _runningScans.Clear(); - _disposed = true; - } - } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs deleted file mode 100644 index 124b05b0..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; - -/// -/// Media library scan job for comparing hashes. -/// -internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob -{ - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job - // only execute this job's payload when it has no parents, or when all the parents finished their execution - if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) - { - Status = LibraryScanJobStatus.Running; - Console.WriteLine("started file hashing"); - List ints = [1, 2, 3]; - while (!cancellationToken.IsCancellationRequested) - { - await Task.Delay(1111, cancellationToken).ConfigureAwait(false); - Console.WriteLine("ticking"); - cancellationToken.ThrowIfCancellationRequested(); - } - Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended file hashing"); - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs deleted file mode 100644 index 50161cd6..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ /dev/null @@ -1,42 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; - -/// -/// Media library scan job for retrieving persistence data from any eventual previous scans. -/// -internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob -{ - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job - // only execute this job's payload when it has no parents, or when all the parents finished their execution - if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) - { - Status = LibraryScanJobStatus.Running; - Console.WriteLine("started repo discovering"); - List ints = [1, 2, 3]; - Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended repo discovering"); - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs deleted file mode 100644 index 9329ca06..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ /dev/null @@ -1,43 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books; - -/// -/// Media library scan job for retrieving written content metadata from GoodReads. -/// -internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob -{ - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job - // only execute this job's payload when it has no parents, or when all the parents finished their execution - if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) - { - Status = LibraryScanJobStatus.Running; - Console.WriteLine("started goodreads metadata"); - List ints = [1, 2, 3]; - Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended goodreads metadata"); - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } -} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryScanProgressRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryScanProgressRequest.cs new file mode 100644 index 00000000..1929ab4b --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryScanProgressRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents a request to report the progress of a media library scan. +/// +/// The Id of the media library whose scan progress is requested. Required. +/// The Id of the media library scan whose progress is requested. Required. +[DebuggerDisplay("LibraryId: {LibraryId}, ScanId: {ScanId}")] +public record GetLibraryScanProgressRequest( + Guid LibraryId, + Guid ScanId +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponse.cs new file mode 100644 index 00000000..3351d93a --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponse.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a media library scan job progress response. +/// +/// The number of processed scan job items. +/// The total number of scan job items. +/// The current processing operation in the scan job. +/// The ratio between the number of processed items and the total number of items to process, as percentage. +[DebuggerDisplay("CompletedItems: {CompletedItems} TotalItems: {TotalItems}")] +public record MediaLibraryScanJobProgressResponse( + int CompletedItems, + int TotalItems, + string CurrentOperation, + decimal ProgressPercentage +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs new file mode 100644 index 00000000..5f1771cd --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a media library scan progress response. +/// +/// The total number of jobs to be processed by the scan. +/// The number of jobs that have been processed. +/// The progress of the currently processing job. +/// The status of the scan. +/// The ratio between the number of processed jobs and the total number of jobs to process, as percentage. +[DebuggerDisplay("TotalJobs: {TotalJobs} CompletedJobs: {CompletedJobs}")] +public record MediaLibraryScanProgressResponse( + int TotalJobs, + int CompletedJobs, + MediaLibraryScanJobProgressResponse? CurrentJobProgress, + LibraryScanJobStatus Status, + decimal OverallProgressPercentage +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanResponse.cs similarity index 94% rename from src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs rename to src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanResponse.cs index 179bf7ae..26a54f3e 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanResponse.cs @@ -11,7 +11,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// The unique identifier of the media library scan. /// The unique identifier of the scanned media library. [DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")] -public record ScanLibraryResponse( +public record MediaLibraryScanResponse( Guid ScanId, Guid LibraryId ); diff --git a/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs b/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs index 66f8f464..8c405acc 100644 --- a/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs +++ b/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs @@ -106,6 +106,6 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor // set modification properties entry.Entity.UpdatedOnUtc = utcNow; - entry.Entity.UpdatedBy = userId; + entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id } } diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index 526bdf09..e8d2dfaa 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -5,7 +5,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; @@ -49,7 +50,9 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); return services; } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs index 10d2522a..70e5bacb 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs @@ -10,8 +10,10 @@ namespace Lumina.Domain.Common.Errors; public static partial class Errors { public static class LibraryScanning - { + { + public static Error LibraryScanIdCannotBeEmpty => Error.Validation(description: nameof(LibraryScanIdCannotBeEmpty)); public static Error CanOnlyStartPendingScans => Error.Forbidden(description: nameof(CanOnlyStartPendingScans)); + public static Error CanOnlyCompleteRunningScans => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScans)); public static Error CanOnlyCancelRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelRunningScans)); public static Error CanOnlyFailRunningScans => Error.Forbidden(description: nameof(CanOnlyFailRunningScans)); public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty)); @@ -19,8 +21,11 @@ public static partial class Errors public static Error LibraryAlreadyBeingScanned => Error.Forbidden(description: nameof(LibraryAlreadyBeingScanned)); public static Error LibraryScanNotFound => Error.NotFound(description: nameof(LibraryScanNotFound)); public static Error TotalScanJobItemsCountMustBePositive => Error.Validation(description: nameof(TotalScanJobItemsCountMustBePositive)); + public static Error TotalScanJobsCountMustBePositive => Error.Validation(description: nameof(TotalScanJobsCountMustBePositive)); public static Error CompletedScanJobItemsCountMustBePositive => Error.Validation(description: nameof(CompletedScanJobItemsCountMustBePositive)); + public static Error CompletedScanJobsCountMustBePositive => Error.Validation(description: nameof(CompletedScanJobsCountMustBePositive)); public static Error CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount => Error.Validation(description: nameof(CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount)); + public static Error CompletedScanJobsCountCantExceedTotalScanJobsCount => Error.Validation(description: nameof(CompletedScanJobsCountCantExceedTotalScanJobsCount)); public static Error ScanJobCurrentOperationCannotBeEmpty => Error.Validation(description: nameof(ScanJobCurrentOperationCannotBeEmpty)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs similarity index 52% rename from src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs index 574a2f74..78fc407b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; using System.Diagnostics; #endregion @@ -8,14 +10,16 @@ using System.Diagnostics; namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; /// -/// Domain event raised when a libary scan is completed. +/// Domain event raised when a libary scan is finished. /// /// The unique identifier of the domain event. -/// The unique identifier of the library whose scan was completed. +/// The object representing the unique identifier of the media library scan. +/// The object representing the unique identifier of the user that started the library scan whose progress changes. /// The date and time when the domain event occurred. -[DebuggerDisplay("Id: {Id}")] -public record LibraryScanCompletedDomainEvent( +[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] +public record LibraryScanFinishedDomainEvent( Guid Id, - LibraryId LibraryId, + ScanId ScanId, + UserId UserId, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs new file mode 100644 index 00000000..711cfb7b --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary's scan job progress changes. +/// +/// The unique identifier of the domain event. +/// The object representing the unique identifier of the media library scan. +/// The object representing the unique identifier of the user that started the library scan whose progress changes. +/// The object representing the new media library scan job progress. +/// The date and time when the domain event occurred. +[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] +public record LibraryScanJobProgressChangedDomainEvent( + Guid Id, + ScanId ScanId, + UserId UserId, + MediaLibraryScanJobProgress Progress, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs index 5ce1f801..579a33c7 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs @@ -2,6 +2,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; using System.Diagnostics; #endregion @@ -12,13 +13,13 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Domain event raised when a libary's scan progress changes. /// /// The unique identifier of the domain event. -/// The unique identifier of the failed media library scan. -/// The unique identifier of the library whose scan progress changes. +/// The object representing the unique identifier of the media library scan. +/// The object representing the unique identifier of the user that started the library scan whose progress changes. /// The date and time when the domain event occurred. -[DebuggerDisplay("Id: {Id}")] +[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] public record LibraryScanProgressChangedDomainEvent( Guid Id, ScanId ScanId, - LibraryId LibraryId, + UserId UserId, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs index 3d747370..9d816c78 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs @@ -119,6 +119,20 @@ public class LibraryScan : AggregateRoot return Result.Success; } + /// + /// Finishes the media library scan. + /// + /// An representing either a successful operation, or an error. + public ErrorOr FinishScan() + { + if (Status == LibraryScanJobStatus.Running) + Status = LibraryScanJobStatus.Completed; + else + return Errors.LibraryScanning.CanOnlyCompleteRunningScans; + + return Result.Success; + } + /// /// Cancels the media library scan. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs index 7484ad69..07687d27 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using System; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System.Threading; #endregion @@ -11,30 +11,27 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib public interface IMediaLibrariesScanCancellationTracker { /// - /// Gets the cancellation token for a scan identified by and . + /// Gets the cancellation token for a scan identified by . /// - /// The unique identifier of the scan to get the cancellation token for. - /// The unique identifier of the user who initiated the scan for which to get the cancellation token. + /// Model for tracking media library scans. /// A cancellation token for the specified scan. - CancellationToken GetTokenForScan(Guid scanId, Guid userId); + CancellationToken GetTokenForScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); /// /// Registers a new scan operation for tracking. /// - /// The unique identifier of the scan operation to track. - /// The unique identifier of the user who initiated the scan to track. - void RegisterScan(Guid scanId, Guid userId); + /// Model for tracking media library scans. + void RegisterScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + + /// + /// Removes a scan operation from tracking. + /// + /// Model for tracking media library scans. + void RemoveScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); /// - /// Cancels a scan identified by and . + /// Cancels a scan identified by . /// - /// The unique identifier of the scan operation to cancel. - /// The unique identifier of the user requesting the cancellation. - void CancelScan(Guid scanId, Guid userId); - - /// - /// Cancels all active scan operations for a user identified by . - /// - /// The unique identifier of the user whose scans should be canceled. - void CancelUserScans(Guid userId); + /// Model for tracking media library scans. + void CancelScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs new file mode 100644 index 00000000..f9f8228e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs @@ -0,0 +1,9 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph. +/// +public interface IRepositoryMetadataSaveJob : IMediaLibraryScanJob +{ + +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs index 29dd78f3..1ade7600 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs @@ -17,7 +17,6 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib public abstract class MediaLibraryScanJob : IMediaLibraryScanJob { protected int parentsPayloadsExecuted; - protected ScanJobProgress? _jobProgress; /// /// Gets or sets the Id of the media library scan that this job is part of. diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 17e32bc2..857e17bb 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -1,11 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Enums.MediaLibrary; +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.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +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.Linq; @@ -20,23 +24,32 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// internal class MediaLibraryScanningService : IMediaLibraryScanningService { - private readonly IMediaLibrariesScanQueue _mediaScanQueue; - private readonly IMediaLibraryScannerFactory _libraryScannerFactory; + private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue; + private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + private readonly IPublisher _publisher; /// /// Initializes a new instance of the class. /// - /// Injected queue used for processing media libraries scan jobs. - /// Injected factory for creating media library scanners. + /// Injected queue used for processing media libraries scan jobs. + /// Injected factory for creating media library scanners. + /// Injected tracker used for canceling media library scans. + /// Injected tracker used for media library scans progress. + /// The domain event publisher used to publish events. public MediaLibraryScanningService( - IMediaLibrariesScanQueue mediaScanQueue, - IMediaLibraryScannerFactory libraryScannerFactory, - IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker) + IMediaLibrariesScanQueue mediaLibrariesScanQueue, + IMediaLibraryScannerFactory mediaLibraryScannerFactory, + IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IPublisher publisher) { - _mediaScanQueue = mediaScanQueue; - _libraryScannerFactory = libraryScannerFactory; + _mediaLibrariesScanQueue = mediaLibrariesScanQueue; + _mediaLibraryScannerFactory = mediaLibraryScannerFactory; _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _publisher = publisher; } /// @@ -53,25 +66,34 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService ErrorOr startScanResult = scan.StartScan(); if (startScanResult.IsError) return startScanResult.Errors; + + foreach (IDomainEvent domainEvent in scan.GetDomainEvents()) + await _publisher!.Publish(domainEvent, cancellationToken).ConfigureAwait(false); + // register the scan in the tracker for cancellation tokens - _mediaLibrariesScanCancellationTracker.RegisterScan(scan.Id.Value, scan.UserId!.Value); + _mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); try { // link the user's cancellation token with the scan's token CancellationTokenSource linkedSource = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(scan.Id.Value, scan.UserId!.Value)); + .CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId))); // get a media library scanner for the provided media library type - IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(libraryType); + IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType); // get the list of scan jobs for the retrieved scanner List jobs = scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMedatadaFromWeb).ToList(); + + // count total jobs in the chain by traversing the job graph + int totalJobs = CountTotalJobs(jobs); + _mediaLibrariesScanProgressTracker.InitializeScanProgress(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId), totalJobs); + // enqueue the jobs on the channel from where they will be processed foreach (IMediaLibraryScanJob job in jobs) { - job.ScanId = scan.Id; - job.UserId = scan.UserId; - await _mediaScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false); + // set the Id of the scan and of the user initiating the scan to all jobs in the scan job graph + SetScanPropertiesForJobChain(job, scan.Id, scan.UserId); + await _mediaLibrariesScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false); } } catch (NotImplementedException) { } @@ -86,7 +108,47 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService public ErrorOr CancelScan(LibraryScan scan) { // trigger the process that cancels the jobs of the scan - _mediaLibrariesScanCancellationTracker.CancelScan(scan.Id.Value, scan.UserId!.Value); + _mediaLibrariesScanCancellationTracker.CancelScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); return Result.Success; } + + /// + /// Sets the scan properties for a job and all its child jobs in a recursive manner. + /// + /// The media library scan job whose properties are to be set. + /// The object representing the unique identifier for the scan. + /// The object representing the unique identifier for the user that initiated the scan. + public static void SetScanPropertiesForJobChain(IMediaLibraryScanJob job, ScanId scanId, UserId userId) + { + job.ScanId = scanId; + job.UserId = userId; + // recursively set properties for all children + foreach (IMediaLibraryScanJob childJob in job.Children) + SetScanPropertiesForJobChain(childJob, scanId, userId); + } + + /// + /// Counts the total number of unique media library scan jobs in a list of root jobs. + /// + /// A list of root media library scan jobs to traverse. + /// The total count of unique media library scan jobs. + private static int CountTotalJobs(List rootJobs) + { + HashSet uniqueJobs = []; + foreach (IMediaLibraryScanJob job in rootJobs) + TraverseJobGraph(job, uniqueJobs); + return uniqueJobs.Count; + } + + /// + /// Traverses the job graph recursively and adds each job to a set of unique jobs. + /// + /// The current media library scan job being traversed. + /// A hash set that stores unique media library scan jobs. + private static void TraverseJobGraph(IMediaLibraryScanJob job, HashSet uniqueJobs) + { + uniqueJobs.Add(job); + foreach (IMediaLibraryScanJob child in job.Children) + TraverseJobGraph(child, uniqueJobs); + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs new file mode 100644 index 00000000..9a49b45b --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; + +/// +/// Interface for the tracker used for media library scans progress. +/// +public interface IMediaLibrariesScanProgressTracker +{ + /// + /// Initializes the the progress tracking of a media library scan. + /// + /// Model for tracking media library scans. + /// The total number of jobs that this media library scan contains. + /// An representing either a successful operation, or an error. + ErrorOr InitializeScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs); + + /// + /// Updates the progress tracking of the media library scan by incrementing the number of completed scan jobs. + /// + /// Model for tracking media library scans. + /// An representing either a successful operation, or an error. + ErrorOr UpdateScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + + /// + /// Updates the progress tracking of the media library scan by incrementing the number of completed items of a scan job. + /// + /// Model for tracking media library scans. + /// The object representing the progress of the media library scan job. + /// An representing either a successful operation, or an error. + ErrorOr UpdateScanJobProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress); + + /// + /// Gets the progress of a media library scan. + /// + /// Model for tracking media library scans. + /// + /// An containing either a , or an error message. + /// + ErrorOr GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs new file mode 100644 index 00000000..06f98a82 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System.Collections.Concurrent; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; + +/// +/// Tracker used for media library scans progress. +/// +internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTracker +{ + private readonly ConcurrentDictionary _scanProgresses = new(); + + /// + /// Initializes the the progress tracking of a media library scan. + /// + /// Model for tracking media library scans. + /// The total number of jobs that this media library scan contains. + /// An representing either a successful operation, or an error. + public ErrorOr InitializeScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs) + { + ErrorOr createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Initializing"); + if (createLibraryScanJobProgressResult.IsError) + return createLibraryScanJobProgressResult.Errors; + + ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + completedJobs: 0, + totalJobs: totalJobs, + LibraryScanJobStatus.Pending, + Optional.Some(createLibraryScanJobProgressResult.Value) + ); + if (createScanProgressResult.IsError) + return createScanProgressResult.Errors; + + _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; + + return Result.Created; + } + + /// + /// Updates the progress tracking of the media library scan by incrementing the number of completed scan jobs. + /// + /// Model for tracking media library scans. + /// An representing either a successful operation, or an error. + public ErrorOr UpdateScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) + { + ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + progress.CompletedJobs + 1, + progress.TotalJobs, + progress.CompletedJobs + 1 == progress.TotalJobs ? LibraryScanJobStatus.Completed : LibraryScanJobStatus.Running, + progress.CurrentJobProgress + ); + if (createScanProgressResult.IsError) + return createScanProgressResult.Errors; + + _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; + } + return Result.Updated; + } + + /// + /// Updates the progress tracking of the media library scan by incrementing the number of completed items of a scan job. + /// + /// Model for tracking media library scans. + /// The object representing the progress of the media library scan job. + /// An representing either a successful operation, or an error. + public ErrorOr UpdateScanJobProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress) + { + if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? scanProgress)) + { + ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + scanProgress.CompletedJobs, + scanProgress.TotalJobs, + scanProgress.Status, + Optional.Some(progress) + ); + if (createScanProgressResult.IsError) + return createScanProgressResult.Errors; + + _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; + return Result.Updated; + } + return Errors.LibraryScanning.LibraryScanNotFound; + } + + /// + /// Gets the progress of a media library scan. + /// + /// Model for tracking media library scans. + /// + /// An containing either a , or an error message. + /// + public ErrorOr GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) + return progress; + return Errors.LibraryScanning.LibraryScanNotFound; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs similarity index 93% rename from src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs index 5468b54f..f09d0e0d 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs @@ -2,7 +2,7 @@ using Lumina.Domain.Common.Enums.MediaLibrary; #endregion -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; /// /// Interface defining a factory for creating media library scanners. diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs similarity index 95% rename from src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs index 5a1a988d..adf8ae82 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs @@ -5,7 +5,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; /// /// Interface defining a media library scanner for a specific media library type. diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs similarity index 98% rename from src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs index abc9797d..e65d2138 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using System; #endregion -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; /// /// Defines a factory for creating media library scanners. diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs new file mode 100644 index 00000000..f47fef11 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object for the composite unique identifier of a media library scan. +/// +[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] +public sealed class MediaLibraryScanCompositeId : ValueObject +{ + /// + /// Gets the object representing the unique identifier of the media library scan to be tracked. + /// + public ScanId ScanId { get; } + + /// + /// Gets the object representing the unique identifier of the username who initiated the media library scan. + /// + public UserId UserId { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the media library scan to be tracked. + /// The object representing the unique identifier of the username who initiated the media library scan. + private MediaLibraryScanCompositeId(ScanId scanId, UserId userId) + { + ScanId = scanId; + UserId = userId; + } + + /// + /// Creates a new instance of the class. + /// + /// The object representing the unique identifier of the media library scan to be tracked. + /// The object representing the unique identifier of the username who initiated the media library scan. + /// The created instance. + public static MediaLibraryScanCompositeId Create(ScanId scanId, UserId userId) + { + return new MediaLibraryScanCompositeId(scanId, userId); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return ScanId; + yield return UserId; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs similarity index 80% rename from src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs index bcf57cf7..922aa8b4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgress.cs @@ -12,7 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Value Object representing a progress snapshot of a media library scan job. /// [DebuggerDisplay("CompletedItems: {CompletedItems}; TotalItems: {TotalItems}; CurrentOperation: {CurrentOperation}")] -public sealed class ScanJobProgress : ValueObject +public sealed class MediaLibraryScanJobProgress : ValueObject { /// /// Gets the number of completed items of the media library scan job. @@ -32,15 +32,15 @@ public sealed class ScanJobProgress : ValueObject /// /// Gets the ratio between the total number and the completed number of items, as a percentage. /// - public decimal ProgressPercentage => CompletedItems * 100.0m / TotalItems; + public decimal ProgressPercentage => TotalItems > 0 ? CompletedItems * 100.0m / TotalItems : 0; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The number of completed items of the media library scan job. /// The total number of items of the media library scan job. /// The current operation being performed by the media library scan job. - private ScanJobProgress(int completedItems, int totalItems, string currentOperation) + private MediaLibraryScanJobProgress(int completedItems, int totalItems, string currentOperation) { CompletedItems = completedItems; TotalItems = totalItems; @@ -48,17 +48,17 @@ public sealed class ScanJobProgress : ValueObject } /// - /// Creates a new instance of the class. + /// Creates a new instance of the class. /// /// The number of completed items of the media library scan job. /// The total number of items of the media library scan job. /// The current operation being performed by the media library scan job. /// - /// An containing either a successfuly created , or an error message. + /// An containing either a successfuly created , or an error message. /// - public static ErrorOr Create(int completedItems, int totalItems, string currentOperation) + public static ErrorOr Create(int completedItems, int totalItems, string currentOperation) { - if (totalItems <= 0) + if (totalItems < 0) return Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive; if (completedItems < 0) return Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive; @@ -66,7 +66,7 @@ public sealed class ScanJobProgress : ValueObject return Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount; if (string.IsNullOrWhiteSpace(currentOperation)) return Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty; - return new ScanJobProgress(completedItems, totalItems, currentOperation); + return new MediaLibraryScanJobProgress(completedItems, totalItems, currentOperation); } /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs new file mode 100644 index 00000000..9001192c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object representing a progress snapshot of a media library scan. +/// +[DebuggerDisplay("CompletedJobs: {CompletedJobs}; TotalJobs: {TotalJobs}; CurrentJobProgress: {CurrentJobProgress}")] +public sealed class MediaLibraryScanProgress : ValueObject +{ + /// + /// Gets the number of completed jobs of the media library scan job. + /// + public int CompletedJobs { get; } + + /// + /// Gets the total number of jobs of the media library scan job. + /// + public int TotalJobs { get; } + + /// + /// Gets the optional current job progress of the media library scan. + /// + public Optional CurrentJobProgress { get; } = Optional.None(); + + /// + /// Gets the status of the media library scan. + /// + public LibraryScanJobStatus Status { get; } = LibraryScanJobStatus.Pending; + + /// + /// Gets the ratio between the total number and the completed number of jobs, as a percentage. + /// + public decimal OverallProgressPercentage => TotalJobs > 0 ? CompletedJobs * 100.0m / TotalJobs : 0; + + /// + /// Initializes a new instance of the class. + /// + /// The number of completed jobs of the media library scan job. + /// The total number of jobs of the media library scan job. + /// The status of the media library scan. + /// The optional current job progress of the media library scan. + private MediaLibraryScanProgress(int completedJobs, int totalJobs, LibraryScanJobStatus status, Optional currentJobProgress) + { + CompletedJobs = completedJobs; + TotalJobs = totalJobs; + CurrentJobProgress = currentJobProgress; + Status = status; + } + + /// + /// Creates a new instance of the class. + /// + /// The number of completed jobs of the media library scan job. + /// The total number of jobs of the media library scan job. + /// The status of the media library scan. + /// The optional current job progress of the media library scan. + /// + /// An containing either a successfuly created , or an error message. + /// + public static ErrorOr Create(int completedJobs, int totalJobs, LibraryScanJobStatus status, Optional currentJobProgress) + { + if (totalJobs <= 0) + return Errors.LibraryScanning.TotalScanJobsCountMustBePositive; + if (completedJobs < 0) + return Errors.LibraryScanning.CompletedScanJobsCountMustBePositive; + if (completedJobs > totalJobs) + return Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount; + + return new MediaLibraryScanProgress(completedJobs, totalJobs, status, currentJobProgress); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return CompletedJobs; + yield return TotalJobs; + yield return Status; + yield return CurrentJobProgress; + } + + /// + /// Customized ToString() method. + /// + /// Custom string value showing relevant data for current class. + public override string ToString() + { + return $"CompletedJobs: {CompletedJobs}; TotalJobs: {TotalJobs}; CurrentJobProgress: {CurrentJobProgress}"; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index 6efd6742..249d6711 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -35,6 +35,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(libraryId); IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId); + IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob(libraryId); // establish the hierarchical relationships between jobs fileSystemDiscoveryJob.AddChild(hashComparerJob); @@ -46,7 +47,16 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner if (downloadMedatadaFromWeb) { hashComparerJob.AddChild(goodReadsMetadataScrapJob); + goodReadsMetadataScrapJob.AddChild(repositoryMetadataSaveJob); + goodReadsMetadataScrapJob.AddParent(hashComparerJob); + repositoryMetadataSaveJob.AddParent(goodReadsMetadataScrapJob); + } + else // TODO: perform some action with local files? + { + hashComparerJob.AddChild(repositoryMetadataSaveJob); + + repositoryMetadataSaveJob.AddParent(hashComparerJob); } // return the top level jobs that will be triggered when the scan will be started diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs index aac900f9..c3e1c421 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; + #endregion namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index feef8631..8ad251e1 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -22,8 +22,4 @@ - - - - diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index a7508bd3..0415f2a3 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -5,10 +5,18 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; +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; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Infrastructure.Core.Authentication; using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using Lumina.Infrastructure.Core.Authorization.Policies.Over18; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Time; using Microsoft.Extensions.DependencyInjection; @@ -46,6 +54,17 @@ public static class InfrastructureLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + + // media library scanning + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); return services; } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs new file mode 100644 index 00000000..74b156ab --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Collections.Concurrent; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; + +/// +/// Tracker used for canceling in-memory media library scans. +/// +internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable +{ + private readonly ConcurrentDictionary _runningScans = new(); + private bool _disposed; + + /// + /// Registers a new scan operation for tracking. + /// + /// Model for tracking media library scans. + public void RegisterScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + _runningScans.TryAdd(mediaLibraryScanCompositeId, new CancellationTokenSource()); + } + + /// + /// Removes a scan operation from tracking. + /// + /// Model for tracking media library scans. + public void RemoveScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan)) + { + scan.Cancel(); + // remove and dispose after cancellation + if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan)) + removedScan?.Dispose(); + } + } + + /// + /// Gets the cancellation token for a scan identified by . + /// + /// Model for tracking media library scans. + /// A cancellation token for the specified scan. + public CancellationToken GetTokenForScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + return _runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan) + ? scan.Token + : CancellationToken.None; + } + + /// + /// Cancels a scan identified by . + /// + /// Model for tracking media library scans. + public void CancelScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan)) + { + scan.Cancel(); + // remove and dispose after cancellation + if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan)) + removedScan?.Dispose(); + } + } + + /// + /// Disposes the tracker and cancels all media library scans. + /// + public void Dispose() + { + if (!_disposed) + { + foreach (CancellationTokenSource scan in _runningScans.Values) + { + scan.Cancel(); + scan.Dispose(); + } + _runningScans.Clear(); + _disposed = true; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs similarity index 57% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs index ac6665a1..8a439b93 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs @@ -3,9 +3,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads; using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Primitives; @@ -16,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library 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.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; @@ -24,7 +23,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; /// /// Media library scan job for discovering file system items. @@ -59,74 +58,81 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job // only execute this job's payload when it has no parents, or when all the parents finished their execution if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) - { - Status = LibraryScanJobStatus.Running; - - Console.WriteLine("started file discovering"); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } + Status = LibraryScanJobStatus.Running; + await Task.Delay(25000); + Console.WriteLine("started file discovering"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job - ErrorOr scanJobProgressResult = ScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - _jobProgress = scanJobProgressResult.Value; - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - Console.WriteLine($"Reporting job progress in file discovery. Total: {_jobProgress.TotalItems}; Completed: {_jobProgress.CompletedItems}; Current: {_jobProgress.CurrentOperation}"); - // recursively get the file system tree for each of the media library content locations - List contentLocationTrees = []; - foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) - { - cancellationToken.ThrowIfCancellationRequested(); - ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken); - if (treeResult.IsError) + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) { - // handle errors, maybe: - // Status = LibraryScanJobStatus.Failed; + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; } - else - contentLocationTrees.Add(treeResult.Value); - // increment the number of processed elements progress - scanJobProgressResult = ScanJobProgress.Create( - scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); if (scanJobProgressResult.IsError) { await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - } - Console.WriteLine("ended file discovering"); - Status = LibraryScanJobStatus.Completed; - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); - } + + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + // recursively get the file system tree for each of the media library content locations + List contentLocationTrees = []; + foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) + { + await Task.Delay(5000); + cancellationToken.ThrowIfCancellationRequested(); + ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken); + if (treeResult.IsError) + { + // handle errors, maybe: + // Status = LibraryScanJobStatus.Failed; + } + else + contentLocationTrees.Add(treeResult.Value); + + // increment the number of processed elements progress + scanJobProgressResult = MediaLibraryScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } + // this job finished, increment the number of processed jobs progress + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Console.WriteLine("ended file discovering"); + Status = LibraryScanJobStatus.Completed; + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs new file mode 100644 index 00000000..f0ed6e7c --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +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; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for comparing hashes. +/// +internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public HashComparerJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) + { + Status = LibraryScanJobStatus.Running; + Console.WriteLine("started file hashing"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + List ints = [1, 2, 3]; + foreach (int nr in ints) + { + await Task.Delay(5400); + // increment the number of processed elements progress + scanJobProgressResult = MediaLibraryScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } + // this job finished, increment the number of processed jobs progress + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended file hashing"); + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs new file mode 100644 index 00000000..41fff526 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +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; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for retrieving persistence data from any eventual previous scans. +/// +internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + Console.WriteLine("started repo discovering"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + List ints = [1, 2, 3]; + foreach (int nr in ints) + { + await Task.Delay(5400); + // increment the number of processed elements progress + scanJobProgressResult = MediaLibraryScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } + // this job finished, increment the number of processed jobs progress + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended repo discovering"); + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs new file mode 100644 index 00000000..1bc394f0 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +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; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph. +/// +internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + Console.WriteLine("started repo saving"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + List ints = [1, 2, 3]; + foreach (int nr in ints) + { + await Task.Delay(5400); + // increment the number of processed elements progress + scanJobProgressResult = MediaLibraryScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } + // 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(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Console.WriteLine("ended repo saving"); + // this should always be the last job in the directed acyclic job graph, so no linked child to call further + }, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs similarity index 91% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs index 28b30b52..b0e91c6c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads; +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads; /// /// Generic file system node. diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs new file mode 100644 index 00000000..4de40862 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +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.Services.Jobs; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Media library scan job for retrieving written content metadata from GoodReads. +/// +internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) + { + Status = LibraryScanJobStatus.Running; + Console.WriteLine("started goodreads metadata"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsDownload"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + List ints = [1, 2, 3]; + foreach (int nr in ints) + { + await Task.Delay(5400); + // increment the number of processed elements progress + scanJobProgressResult = MediaLibraryScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } + // this job finished, increment the number of processed jobs progress + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended goodreads metadata"); + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs similarity index 86% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs index 3d7400dc..8f154524 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs @@ -11,12 +11,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queu /// internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue { - private readonly Channel _channel = Channel.CreateUnbounded(new UnboundedChannelOptions - { - SingleWriter = false, - SingleReader = false, - AllowSynchronousContinuations = true - }); + private readonly Channel _channel = Channel.CreateUnbounded(); /// /// Gets the writer for the queue, allowing producers to enqueue instances. diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs similarity index 91% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs index 8253701a..1075307f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Utilities; 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; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Microsoft.Extensions.Hosting; using System; using System.Threading; @@ -23,7 +24,7 @@ internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService /// Initializes a new instance of the class. /// /// Injected queue used for processing media libraries scan jobs. - /// Injected service for scanning media libraries. + /// Injected tracker used for canceling media library scans. public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker) { _mediaScanQueue = mediaScanQueue; @@ -43,7 +44,7 @@ internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService await foreach (IMediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) { // get the cancellation token that was associated with this library scan - CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(mediaScanJob.ScanId.Value, mediaScanJob.UserId.Value); + CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(mediaScanJob.ScanId, mediaScanJob.UserId)); // create linked token to handle both scan cancellation and service shutdown CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, scanToken); mediaScanJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).FireAndForgetSafeAsync(() => linkedSource.Dispose()); diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 2409e12e..5b9db6d0 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -50,12 +50,16 @@ public class EventualConsistencyMiddleware // only proceed if the response status code indicates success if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300) { + // commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are + // singletons that require their own DI scope to be created, any changes made on the DbContext in this HTTP scope would not be seen on the + // DbContext created in the background service scope, because the transaction is not yet commited here; therefor, the transaction needs to be + // commited first, before any domain events are fired + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0002.md for details: + await transaction.CommitAsync().ConfigureAwait(false); + // check if domain events exist in the channel queue and publish them while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent)) await publisher.Publish(nextEvent); - - // commit the transaction - await transaction.CommitAsync().ConfigureAwait(false); } } catch (EventualConsistencyException ex) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs new file mode 100644 index 00000000..d0cf1c49 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress; + +/// +/// API endpoint for the /libraries/{libraryId}/scans/{scanId}/progress route. +/// +public class GetLibraryScanProgressEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetLibraryScanProgressEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.LIBRARY_SCAN_PROGRESS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the progress of a media library scan. + /// + /// The request containing the Id of the media library and of the scan whose progress is requested. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryScanProgressRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs new file mode 100644 index 00000000..ba1f29f3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryScanProgressEndpointSummary() + { + Summary = "Retrieves the progress of a media library scan."; + Description = "Retrieves the progress of a media library scan, if the user making the request is an Admin, or the owner of the library."; + + ExampleRequest = new GetLibraryScanProgressRequest( + LibraryId: Guid.NewGuid(), + ScanId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose scan progress is requested. Required."); + RequestParam(r => r.ScanId, "The Id of the media library scan whose progress is requested. Required."); + + ResponseParam(r => r.TotalJobs, "The total number of jobs to be processed by the scan."); + ResponseParam(r => r.CompletedJobs, "The number of jobs that have been processed."); + ResponseParam(r => r.CurrentJobProgress, "The progress of the currently processing job."); + ResponseParam(r => r.Status, "The status of the scan."); + ResponseParam(r => r.OverallProgressPercentage, "The ratio between the number of processed jobs and the total number of jobs to process, as percentage."); + + Response(200, "The progress of the media library scan is returned.", example: new MediaLibraryScanProgressResponse( + TotalJobs: 10, + CompletedJobs: 4, + CurrentJobProgress: new MediaLibraryScanJobProgressResponse( + TotalItems: 1536, + CompletedItems: 768, + CurrentOperation: "Comparing file hashes", + ProgressPercentage: 50 + ), + Status: LibraryScanJobStatus.Running, + OverallProgressPercentage: 40 + )); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library has no scan started.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryScanNotFound", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/scans/{scanId}/progress", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "LibraryScanIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index c0e8b12a..de2019af 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -47,7 +47,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - ErrorOr> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs index 7bd56f18..b8ed39e5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs @@ -22,7 +22,7 @@ public class ScanLibrariesEndpointSummary : Summary /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs index f482c598..ec9af2ea 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -23,7 +23,7 @@ public class ScanLibraryEndpointSummary : Summary Aktuelle Scan-Operation darf nicht leer sein! + + Die Scan-ID der Bibliothek darf nicht leer sein! + + + Gesamtanzahl der Scan-Aufträge muss positiv sein! + + + Anzahl der abgeschlossenen Scan-Aufträge muss positiv sein! + + + Anzahl der abgeschlossenen Scan-Aufträge darf die Gesamtanzahl der Scan-Aufträge nicht überschreiten! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 68426de4..663b6837 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -573,4 +573,16 @@ Scan job current operation cannot be empty! + + Library scan Id cannot be empty! + + + Total scan jobs count must be positive! + + + Completed scan jobs count must be positive! + + + Completed scan jobs count can't exceed total scan jobs count! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index 737b7a71..bf9c4f11 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -573,4 +573,16 @@ ¡La operación actual del escaneo no puede estar vacía! + + ¡El ID de escaneo de la biblioteca no puede estar vacío! + + + ¡El número total de trabajos de escaneo debe ser positivo! + + + ¡El número de trabajos de escaneo completados debe ser positivo! + + + ¡El número de trabajos de escaneo completados no puede exceder el número total de trabajos de escaneo! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index e2d3104c..3770031b 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -573,4 +573,16 @@ L'opération actuelle du scan ne peut pas être vide ! + + L'ID de scan de la bibliothèque ne peut pas être vide! + + + Le nombre total de tâches de scan doit être positif ! + + + Le nombre de tâches de scan terminées doit être positif ! + + + Le nombre de tâches de scan terminées ne peut pas dépasser le nombre total de tâches de scan ! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index d1e01da4..549b7380 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -573,4 +573,16 @@ L'operazione corrente della scansione non può essere vuota! + + L'ID della scansione della libreria non può essere vuoto! + + + Il numero totale dei lavori di scansione deve essere positivo! + + + Il numero dei lavori di scansione completati deve essere positivo! + + + Il numero dei lavori di scansione completati non può superare il numero totale dei lavori di scansione! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index d7eb743a..7e46ce3f 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -573,4 +573,16 @@ スキャンの現在の操作を空にすることはできません! + + ライブラリスキャンIDを空にすることはできません! + + + スキャンジョブの合計数は正の値でなければなりません! + + + 完了したスキャンジョブ数は正の値でなければなりません! + + + 完了したスキャンジョブ数は合計スキャンジョブ数を超えることはできません! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 3b83eddb..1d656920 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -573,4 +573,16 @@ Scan job current operation cannot be empty! + + Library scan Id cannot be empty! + + + Total scan jobs count must be positive! + + + Completed scan jobs count must be positive! + + + Completed scan jobs count can't exceed total scan jobs count! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index f6664d8c..071ffba3 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -573,4 +573,16 @@ Operația curentă de scanare nu poate fi goală! + + ID-ul de scanare al bibliotecii nu poate fi gol! + + + Numărul total de job-uri de scanare trebuie să fie pozitiv! + + + Numărul de job-uri de scanare completate trebuie să fie pozitiv! + + + Numărul de job-uri de scanare completate nu poate depăși numărul total de job-uri de scanare! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 2d0db0e1..c0c66dc1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -573,4 +573,16 @@ Текущая операция сканирования не может быть пустой! + + Идентификатор сканирования библиотеки не может быть пустым! + + + Общее количество заданий сканирования должно быть положительным! + + + Количество завершенных заданий сканирования должно быть положительным! + + + Количество завершенных заданий сканирования не может превышать общее количество заданий сканирования! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 6e6f4ece..65199c3c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -573,4 +573,16 @@ 扫描任务当前操作不能为空! + + 库扫描ID不能为空! + + + 扫描任务总数必须为正数! + + + 已完成扫描任务数量必须为正数! + + + 已完成扫描任务数量不能超过扫描任务总数! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index 9a5a7185..6cbb886f 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -144,6 +144,9 @@ Comic-Serie + + Datei-Hashes werden verglichen... + Konzert @@ -174,6 +177,9 @@ Filmreihe + + Metadaten werden von GoodReads heruntergeladen... + Grafischer Roman @@ -234,6 +240,12 @@ Entfernen + + Vergangene Scan-Daten werden abgerufen... + + + Scandaten werden gespeichert... + Scannen diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index ee1afbb8..57f1569c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -144,6 +144,9 @@ Comic Series + + Comparing file hashes... + Concert @@ -174,6 +177,9 @@ Film Series + + Downloading metadata from GoodReads... + Graphic Novel @@ -234,6 +240,12 @@ Remove + + Retrieving past scan data... + + + Saving scan data... + Scan diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 0f73abe9..83d46d20 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -144,6 +144,9 @@ Serie de Cómics + + Se están comparando hashes de archivos... + Concierto @@ -174,6 +177,9 @@ Saga Cinematográfica + + Descargando metadatos de GoodReads... + Novela Gráfica @@ -234,6 +240,12 @@ Eliminar + + Recuperando datos de escaneos anteriores... + + + Guardando datos del escaneo... + Escanear diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 9f44d8cd..8ac0c837 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -144,6 +144,9 @@ Série de Bandes Dessinées + + Comparer les hachages de fichiers... + Concert @@ -174,6 +177,9 @@ Saga Cinématographique + + Téléchargement des métadonnées depuis GoodReads... + Roman Graphique @@ -234,6 +240,12 @@ Supprimer + + Récupération des données de scan précédentes... + + + Sauvegarde des données de scan en cours... + Scanner diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index 9d8c7b3f..a2981966 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -144,6 +144,9 @@ Serie di Fumetti + + Si stanno confrontando gli hash dei file... + Concerto @@ -174,6 +177,9 @@ Saga Cinematografica + + Scaricamento dei metadati da GoodReads... + Romanzo Grafico @@ -234,6 +240,12 @@ Rimuovere + + Recupero dei dati di scansione precedenti... + + + Salvataggio dei dati di scansione... + Scansiona diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index 20d143e5..ccdce597 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -144,6 +144,9 @@ 漫画シリーズ + + ファイルのハッシュを比較中... + コンサート @@ -174,6 +177,9 @@ 映画シリーズ + + GoodReadsからメタデータをダウンロード中... + グラフィックノベル @@ -234,6 +240,12 @@ 削除 + + 過去のスキャンデータを取得中... + + + スキャンデータを保存中... + スキャン diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index ee1afbb8..57f1569c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -144,6 +144,9 @@ Comic Series + + Comparing file hashes... + Concert @@ -174,6 +177,9 @@ Film Series + + Downloading metadata from GoodReads... + Graphic Novel @@ -234,6 +240,12 @@ Remove + + Retrieving past scan data... + + + Saving scan data... + Scan diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index 0a7a927f..a97bc684 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -144,6 +144,9 @@ Serie de Benzi Desenate + + Se compară hash-urile fișierelor... + Concert @@ -174,6 +177,9 @@ Serie de Filme + + Se descarcă metadate de pe GoodReads... + Roman Grafic @@ -234,6 +240,12 @@ Șterge + + Se preiau datele de scanare anterioare... + + + Se salvează datele de scanare... + Scanează diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index d82f2186..5a0ce521 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -144,6 +144,9 @@ Серия Комиксов + + Сравнение хешей файлов... + Концерт @@ -174,6 +177,9 @@ Киносерия + + Загрузка метаданных из GoodReads... + Графический Роман @@ -234,6 +240,12 @@ Удалить + + Получение данных прошлых сканирований... + + + Сохранение данных сканирования... + Сканировать diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 8661d496..0bde7364 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -144,6 +144,9 @@ 漫画系列 + + 正在比较文件哈希值... + 音乐会 @@ -174,6 +177,9 @@ 电影系列 + + 正在从GoodReads下载元数据... + 图像小说 @@ -234,6 +240,12 @@ 删除 + + 正在检索过去的扫描数据... + + + 正在保存扫描数据... + 扫描 diff --git a/src/Lumina.sln b/src/Lumina.sln index 36ebae26..7273bc7b 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -173,9 +173,15 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architecture", "{D93CA337-37D5-4A42-86B5-0A2410594A7A}" ProjectSection(SolutionItems) = preProject ..\docs\technical\architecture\1 system-context-diagram.puml = ..\docs\technical\architecture\1 system-context-diagram.puml + ..\docs\technical\architecture\1 system-context-diagram.svg = ..\docs\technical\architecture\1 system-context-diagram.svg ..\docs\technical\architecture\2 container-diagram.puml = ..\docs\technical\architecture\2 container-diagram.puml + ..\docs\technical\architecture\2 container-diagram.svg = ..\docs\technical\architecture\2 container-diagram.svg ..\docs\technical\architecture\3.1 component-web-client-diagram.puml = ..\docs\technical\architecture\3.1 component-web-client-diagram.puml - ..\docs\technical\architecture\3.2 component-server-diagram.puml = ..\docs\technical\architecture\3.2 component-server-diagram.puml + ..\docs\technical\architecture\3.1 component-web-client-diagram.svg = ..\docs\technical\architecture\3.1 component-web-client-diagram.svg + ..\docs\technical\architecture\3.2 component-api-server-diagram.puml = ..\docs\technical\architecture\3.2 component-api-server-diagram.puml + ..\docs\technical\architecture\3.2 component-api-server-diagram.svg = ..\docs\technical\architecture\3.2 component-api-server-diagram.svg + ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.puml = ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.puml + ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg = ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{70B56088-6D3A-481E-9459-79AC6B16FEC1}" @@ -183,6 +189,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", "architecture-decision-log", "{788FADE4-342D-4919-8E5C-10CA8EDBE954}" ProjectSection(SolutionItems) = preProject ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0002.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0002.md EndProjectSection EndProject Global