From 0f1f47e86ca1c1240f8de98b7968bbf0ba0c72f7 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 30 Oct 2026 23:55:51 +0200 Subject: [PATCH 1/3] Adds a pull request template that GitHub applies automatically Copies the pull request template from docs/technical/templates into the .github directory, which is one of the locations GitHub reads when it pre-fills the pull request description in the web interface. --- .github/PULL_REQUEST_TEMPLATE.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..c053809c --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,17 @@ +## Description +[Provide a brief description of the changes in this PR] + +## Related Issue +[Link to the related issue, if applicable] + +## Type of Change +- [ ] Bug fix +- [ ] Hot fix +- [ ] New feature +- [ ] Documentation update +- [ ] Other (please specify) + +## Checklist +- [ ] My code follows the project's coding style +- [ ] I have tested my changes +- [ ] I have updated the documentation accordingly From b0c24a1722d12a42544e875fcb182518af33939b Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 31 Oct 2026 12:39:25 +0200 Subject: [PATCH 2/3] Standardizes the architecture decision records Uses ADR-0001 as the template for the sections of every ADR, moves the remaining in-document amendments to amendment sections at the end in chronological order, renames the consequence subsections to the template names, and fixes the heading formatting. --- .../architecture-decision-record-0003.md | 27 +++++++++---------- .../architecture-decision-record-0008.md | 8 +++--- .../architecture-decision-record-0010.md | 20 ++++++++------ .../architecture-decision-record-0011.md | 4 +-- .../architecture-decision-record-0012.md | 4 +-- .../architecture-decision-record-0013.md | 4 +-- .../architecture-decision-record-0014.md | 4 +-- .../architecture-decision-record-0015.md | 4 +-- .../architecture-decision-record-0016.md | 4 +-- .../architecture-decision-record-0017.md | 4 +-- .../architecture-decision-record-0018.md | 4 +-- .../architecture-decision-record-0019.md | 1 - 12 files changed, 37 insertions(+), 51 deletions(-) diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md index 1bfd69b4..b9adc308 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md @@ -1,9 +1,9 @@ # Architecture Decision Record (ADR): 0003 - Pragmatic `System.IO` Usage for File System Discovery in Library Scan Job -## Status +## Status **Accepted** (2025-03-01) -## Context +## Context The media library scanning subsystem requires: 1. **Performance at scale**: enumeration of files needs to run fast, because file discovery is the first job in the chain of media library scan jobs. If this is slow, the entire scan will be slow, no matter how optimized subsequent jobs are. 2. **Domain model limitations**: @@ -13,7 +13,7 @@ The media library scanning subsystem requires: - Users potentially having tens of millions of files and hundreds of terrabytes of data, in some cases. - Limited value from domain semantics during raw discovery. -## Decision +## Decision Use `System.IO` directly in `FileSystemDiscoveryJob` with: ```csharp @@ -25,33 +25,28 @@ private static List GetFiles(...) } ``` - -## Amendments - -- **2026-10-09**: The single generic `FileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`). The `System.IO` guidance of this ADR applies to the books discovery job, which still traverses the file system directly. The music discovery job uses the domain file system provider services (`IFileProviderService`, `IDirectoryProviderService`) instead. - ## Consequences -### Performance vs Purity Tradeoff +### Positive Outcomes | Metric | Before (Domain) | After (System.IO) | Delta | |----------------------|-----------------|-------------------|----------| | 100k File Enumeration| 65s | 4s | -94% | -### Risks and Mitigations +### Risks and Tradeoffs | Risk | Mitigation Strategy | |-------------------------------|------------------------------------------------------------| | Hidden Platform Dependencies | Regular integration tests on Linux/Windows | | Loss of Domain Abstraction | Strictly limit usage to library scan discovery phase only | -## Alternatives Considered +## Alternatives Considered -### 1. Optimized Domain Aggregate +### 1. Optimized Domain Aggregate Domain entities like `File` or `Directory` could be modified to bypass invariants checks in their initialization, leading to a noticeable latency drop. **Rejected**: Invariants checks are one of the most important domain aspects, and the performance gain was still insufficient for the target scale. -### 2. Hybrid Approach +### 2. Hybrid Approach ```csharp if (fileCount > 10_000) @@ -84,7 +79,7 @@ static extern IntPtr OpenDir(string name); | Memory Leaks | Manual handle management required finalizers and safe handles | | Testing Complexity | Physical VM requirements for platform validation | -### 5. Native C Library with Managed Interop +### 4. Native C Library with Managed Interop ```c // file_discovery.c @@ -114,3 +109,7 @@ void lin_enumerate(const char* path, void (callback)(const char)) | Cross-Compilation Complexity | Required CI pipeline support for Windows/macOS/Linux binaries | | ABI Breakage | High risk of crashes during .NET runtime updates | | Debugging Difficulty | Specialized tools (WinDbg/gdb) needed for crash analysis | + +## Amendment: Per-Type File System Discovery Jobs (2026-10-09) + +The single generic `FileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`). The `System.IO` guidance of this ADR applies to the books discovery job, which still traverses the file system directly. The music discovery job uses the domain file system provider services (`IFileProviderService`, `IDirectoryProviderService`) instead. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md index 37c87324..6e0244e1 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md @@ -17,10 +17,6 @@ Define the `IScanJobRegistry` interface, which maps a hook name to the plugin jo The payload passing between jobs keeps the generic `ExecuteAsync` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables ([ADR-0004](architecture-decision-record-0004.md), [ADR-0005](architecture-decision-record-0005.md)). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated. -## Amendments - -- **2026-10-09**: Superseded by [ADR-0015](architecture-decision-record-0015.md). The `ScanJobHooks` hook points and the `IScanJobRegistry` / `ScanJobRegistry` were removed, and plugins now contribute capability providers (`IMetadataProvider`, `IArtworkProvider`, `IBookReader`) instead of scan jobs. This ADR is marked superseded rather than amended because its decision is replaced in full by [ADR-0015](architecture-decision-record-0015.md); [ADR-0001](architecture-decision-record-0001.md), [ADR-0003](architecture-decision-record-0003.md) and [ADR-0010](architecture-decision-record-0010.md) stay accepted because only part of their decisions changed. - ## Consequences > The rows struck through reflect the superseded hook point and scan job registry model. They no longer hold, see [ADR-0015](architecture-decision-record-0015.md). @@ -51,3 +47,7 @@ Allow plugins to attach anywhere in the graph without restriction. Rework the jobs into a generic pipeline engine where edges carry strongly typed channels. **Rejected**: The database-centric jobs exchange state through the database, so a full in-memory typed dataflow engine would add complexity without benefit. The generic payload contract is retained for the plugin jobs that need it. + +## Amendment: Superseded by Plugin Capability Providers (2026-10-09) + +Superseded by [ADR-0015](architecture-decision-record-0015.md). The `ScanJobHooks` hook points and the `IScanJobRegistry` / `ScanJobRegistry` were removed, and plugins now contribute capability providers (`IMetadataProvider`, `IArtworkProvider`, `IBookReader`) instead of scan jobs. This ADR is marked superseded rather than amended because its decision is replaced in full by [ADR-0015](architecture-decision-record-0015.md); [ADR-0001](architecture-decision-record-0001.md), [ADR-0003](architecture-decision-record-0003.md) and [ADR-0010](architecture-decision-record-0010.md) stay accepted because only part of their decisions changed. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md index 09680ffa..4c274bf6 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md @@ -18,14 +18,6 @@ The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best- The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise. -## Amendments - -- **2026-10-09**: The enrichment phase is now three sequential jobs, and the last job of the graph is the artwork enrichment job. - - `MediaLibraryScanProviderConfigurationInvalidationJob` invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, and the metadata derived from the paths when the path template changed. - - `MediaLibraryScanMetadataEnrichmentJob` enriches the metadata and links the media contributors. - - `MediaLibraryScanArtworkEnrichmentJob` resolves the artwork and is always the last job, publishing `LibraryScanFinishedDomainEvent` (see `MediaLibraryScanArtworkEnrichmentJob`). -- **2026-10-09**: The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`; it triggers the provider configuration invalidation job. The metadata enrichment semantics described below apply to both the metadata and the artwork enrichment jobs, and across every media library type with enrichers, including music (`MusicMediaLibraryScanMetadataEnricher`, `MusicMediaLibraryScanArtworkEnricher`), not only books. - ## Consequences ### Positive Outcomes @@ -53,3 +45,15 @@ Keep [ADR-0009](architecture-decision-record-0009.md) semantics for the enrichme Enrich the books asynchronously after the scan, decoupled from the scan progress and cancellation. **Rejected**: This contradicts the decision that the metadata enrichment phase is part of the scan lifetime, covered by the scan progress reporting and cancellation machinery, so that the scan progress reaches completion only when the metadata is downloaded. + +## Amendment: Sequential Enrichment Jobs and Artwork Enrichment Last (2026-10-09) + +The enrichment phase is now three sequential jobs, and the last job of the graph is the artwork enrichment job. + +- `MediaLibraryScanProviderConfigurationInvalidationJob` invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, and the metadata derived from the paths when the path template changed. +- `MediaLibraryScanMetadataEnrichmentJob` enriches the metadata and links the media contributors. +- `MediaLibraryScanArtworkEnrichmentJob` resolves the artwork and is always the last job, publishing `LibraryScanFinishedDomainEvent` (see `MediaLibraryScanArtworkEnrichmentJob`). + +## Amendment: Enrichment Semantics Across Media Library Types (2026-10-09) + +The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`; it triggers the provider configuration invalidation job. The metadata enrichment semantics described above apply to both the metadata and the artwork enrichment jobs, and across every media library type with enrichers, including music (`MusicMediaLibraryScanMetadataEnricher`, `MusicMediaLibraryScanArtworkEnricher`), not only books. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md index 4e57fd2f..375bb703 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0011 - Replace MediatR with Custom CQRS Abstractions ## Status - **Accepted** (2026-08-13) ## Context @@ -121,8 +120,7 @@ internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint | DI Alignment | Leverages the existing .NET DI container idioms already present in the solution | | Performance | No runtime reflection, other than the startup registration of application use case handlers | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | Loss of pipeline behavior support | Application validation will be performed manually, as an orchestration step | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md index 27bf386e..933c28cd 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0012 - Replace FluentValidation with Custom Validation Abstractions ## Status - **Accepted** (2026-08-13) ## Context @@ -171,8 +170,7 @@ internal sealed class CreateSensorCommandValidator : AbstractValidator`, `IQueryHandler<>` | Consistency | Domain event handlers join the same explicit registration scan as the CQRS handlers | | Single event contract | `IDomainEvent` remains the sole contract until a real cross-bounded-context consumer exists | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | Handler resolution failures surface at runtime | Existing integration test suite exercises the DI container on startup | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md index 32fd843b..56b3e3d0 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0014 - Closed Generic Persistence Toolkit for Aggregate Graph Persistence ## Status - **Accepted** (2026-09-26) ## Context @@ -54,8 +53,7 @@ Treat `Lumina.DataAccess\Common\Persistence` as a closed set of generic, entity- | Testability | The primitives are covered directly by unit tests, independently of any repository | | Ownership | No new external dependency and no declarative engine; the toolkit depends only on the internal `ISharedReferenceEntity` marker, and the logic stays explicit and inspectable | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | The generic resolver depends on an entity keyed by `Name` and translated by EF Core | `SharedReferenceResolver` is generic over `ISharedReferenceEntity` and is exercised by both unit and integration tests, which prove the EF translation | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md index 6756845e..c4a946f0 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0015 - Plugin Capability Providers for Media Library Enrichment ## Status - **Accepted** (2026-10-09) Supersedes [ADR-0008](architecture-decision-record-0008.md). @@ -56,8 +55,7 @@ The host defines the capability contracts, and a plugin implements the ones it s | Per-library control | Providers are enabled and ranked per media library, independent of plugin installation | | Simplicity | No hook registry, no graph splicing across the plugin boundary, and no runtime payload type switching | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | A plugin registers a capability a library type does not support | Providers declare `SupportedLibraryTypes`, and the host only offers and invokes providers that support the library being processed | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md index f438f466..93ee1830 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0016 - Playback Delivery Decision and Player Capability Negotiation ## Status - **Accepted** (2026-10-14) ## Context @@ -70,8 +69,7 @@ The segments are exposed through a dedicated segment route, `.../stream/deliveri | Seekability | Time addressed segments make a normalized delivery seekable without a byte to time index | | Testability | The decision is a pure function of the stored container and codec and the advertised capabilities | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md index 1a1e6f43..0a0f8476 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0017 - One Generic Favorites Aggregate Keyed by Media Kind and Item Id ## Status - **Accepted** (2026-10-21) ## Context @@ -61,8 +60,7 @@ The decision includes these rules: | No existence oracle | An inaccessible item and a missing item are indistinguishable when adding, and inaccessible display data is never listed | | No schema change for new kinds | The kind is stored by name, so a planned kind only needs its restriction lifted and its two resolutions written | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | Without a foreign key, rows can point at items that no longer exist | This is intended: the listing returns such rows as unavailable and removal never needs the item. Nothing relies on the item being present | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md index b30cfb39..980a40e2 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0018 - Media Neutral Consumption History, Resume Points, and Derived Statistics ## Status - **Accepted** (2026-10-26) ## Context @@ -88,8 +87,7 @@ The statistics count a session when the rule of its media kind says so. Duration | Per-library policy | Progress tracking and completion thresholds are chosen per library instead of being hardcoded for a media kind | | Privacy by default | A regular user cannot read or delete another user's data, and a wrong user id is reported as not authorized rather than revealing existence | -### Risks and Mitigations - +### Risks and Tradeoffs | Risk | Mitigation Strategy | |---|---| | Without a foreign key, a record can point at an item that no longer exists | This is intended: the history keeps its counts and duration, and the list returns the item as unavailable with blank display data so the user can delete it | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0019.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0019.md index 3385708e..e8d7e710 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0019.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0019.md @@ -1,7 +1,6 @@ # Architecture Decision Record (ADR): 0019 - SSD Aware Read Parallelism During Media Library Scans ## Status - **Accepted** (2026-10-30) ## Context From 8ff5149b6eadbcedaefd9bd227a33b7a07aae82b Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 31 Oct 2026 14:42:33 +0200 Subject: [PATCH 3/3] Serializes media library scans through a scan queue Replaces the job queue with a scan queue that executes one media library scan at a time, in the order in which the scans were queued, so several libraries requested at once no longer run one complete job chain each on the thread pool shared with the web server. Keeps queued scans Pending and cancellable, reports them as queued, and cancels the executing scan and the queued ones when the user cancels all scans. A media library type without a scanner now fails its own scan instead of leaving it stuck Pending, without stopping the scans queued behind it. Makes the file system discovery job the only top level job of a scan graph, so awaiting it completes the whole scan, and leaves one logical processor free for the rest of the process while discovery and hashing read files in parallel. Removes the per job Task.Run wrappers, links the scan cancellation with the host shutdown token in the scan processor, updates the ADR amendments, API documentation, manual, web client and tests, and normalizes the comments of the touched files. --- docs/manual/managing-libraries/index.md | 8 +- .../api/library/management/Api.Libraries.md | 17 + .../architecture-decision-record-0001.md | 15 +- .../architecture-decision-record-0009.md | 8 + .../MediaLibrary/ILibraryScanRepository.cs | 4 +- .../CancelLibrariesScanCommandHandler.cs | 12 +- .../LibraryScanCancelledDomainEventHandler.cs | 17 +- .../LibraryScanQueuedDomainEventHandler.cs | 65 ++-- .../IMediaLibraryScanProgressNotifier.cs | 7 + .../GetRunningLibraryScansQueryHandler.cs | 38 +-- .../Libraries/LibraryRepository.cs | 3 + .../Libraries/LibraryScanRepository.cs | 7 +- .../Common/Errors/Errors.LibraryScanning.cs | 5 +- .../Jobs/IMusicFileSystemDiscoveryJob.cs | 2 +- .../Scanners/MusicLibraryTypeScanner.cs | 11 +- .../Events/LibraryScanQueuedDomainEvent.cs | 3 + .../LibraryScanAggregate/LibraryScan.cs | 16 +- .../Services/IMediaLibraryScanningService.cs | 10 +- .../Jobs/IMediaLibraryScanDiscoveryJob.cs | 11 + .../Services/MediaLibraryScanningService.cs | 82 ++--- .../IMediaLibrariesScanProgressTracker.cs | 8 + .../MediaLibrariesScanProgressTracker.cs | 30 ++ .../Queue/IMediaLibrariesScanQueue.cs | 13 +- .../Scanners/IMediaLibraryScannerFactory.cs | 7 +- .../Services/Scanners/IMediaTypeScanner.cs | 7 +- .../Scanners/MediaLibraryScannerFactory.cs | 52 +-- .../ValueObjects/MediaLibraryScanProgress.cs | 3 +- .../Jobs/IBooksFileSystemDiscoveryJob.cs | 2 +- .../Scanners/BookLibraryTypeScanner.cs | 17 +- .../InfrastructureLayerServices.cs | 2 +- .../Music/MusicFileSystemDiscoveryJob.cs | 184 +++++----- .../Audio/Music/MusicMetadataExtractionJob.cs | 156 +++++---- .../MediaLibraryScanArtworkEnrichmentJob.cs | 58 ++-- .../Jobs/Common/MediaLibraryScanDiffJob.cs | 58 ++-- .../Jobs/Common/MediaLibraryScanHashJob.cs | 150 ++++----- .../MediaLibraryScanMetadataEnrichmentJob.cs | 58 ++-- ...canProviderConfigurationInvalidationJob.cs | 198 ++++++----- .../Common/MediaLibraryScanResultsSaveJob.cs | 164 +++++---- .../Books/BooksFileSystemDiscoveryJob.cs | 178 +++++----- ...bouncedMediaLibraryScanProgressNotifier.cs | 25 +- .../Scanning/Queue/MediaLibrariesScanQueue.cs | 13 +- .../Queue/MediaLibraryScanJobProcessorJob.cs | 53 --- .../Queue/MediaLibraryScanProcessorJob.cs | 181 ++++++++++ .../Core/Security/FileHashService.cs | 9 +- .../ScanLibrariesEndpointSummary.cs | 2 +- .../ScanLibrary/ScanLibraryEndpointSummary.cs | 2 +- .../CancelLibrariesScanEndpoint.cs | 2 +- .../CancelLibrariesScanEndpointSummary.cs | 2 +- .../CancelLibraryScanEndpoint.cs | 2 +- .../CancelLibraryScanEndpointSummary.cs | 2 +- .../GetRunningLibraryScansEndpointSummary.cs | 2 +- .../Views/Library/Management/Index.ar-SA.resx | 6 + .../Views/Library/Management/Index.de-DE.resx | 6 + .../Views/Library/Management/Index.en-US.resx | 6 + .../Views/Library/Management/Index.es-ES.resx | 6 + .../Views/Library/Management/Index.fr-FR.resx | 6 + .../Views/Library/Management/Index.it-IT.resx | 6 + .../Views/Library/Management/Index.ja-JP.resx | 6 + .../Views/Library/Management/Index.resx | 6 + .../Views/Library/Management/Index.ro-RO.resx | 6 + .../Views/Library/Management/Index.uk-UA.resx | 6 + .../Views/Library/Management/Index.zh-CN.resx | 6 + .../Views/Library/Management/Index.cshtml | 127 ++++--- .../LibraryScanQueuedDomainEventFixture.cs | 6 + .../Jobs/FakeMediaLibraryScanDiscoveryJob.cs | 134 ++++++++ .../MediaLibraryScanDiscoveryJobFixture.cs | 57 ++++ .../CancelLibrariesScanCommandHandlerTests.cs | 51 ++- .../CancelLibraryScanCommandHandlerTests.cs | 28 +- ...aryScanCancelledDomainEventHandlerTests.cs | 53 ++- ...ibraryScanQueuedDomainEventHandlerTests.cs | 105 +++--- ...GetRunningLibraryScansQueryHandlerTests.cs | 68 +++- .../Libraries/LibraryScanRepositoryTests.cs | 15 +- .../Common/Errors/ErrorsTests.cs | 7 +- .../Scanners/MusicLibraryTypeScannerTests.cs | 83 ++++- .../LibraryScanQueuedDomainEventTests.cs | 7 +- .../LibraryScanAggregate/LibraryScanTests.cs | 55 +-- .../MediaLibraryScanningServiceTests.cs | 199 +++++++---- .../MediaLibrariesScanProgressTrackerTests.cs | 49 ++- .../MediaLibraryScannerFactoryTests.cs | 160 +++++---- .../MediaLibraryScanProgressTests.cs | 50 ++- .../Scanners/BookLibraryTypeScannerTests.cs | 80 ++++- ...edMediaLibraryScanProgressNotifierTests.cs | 56 ++++ .../Queue/MediaLibrariesScanQueueTests.cs | 53 ++- .../MediaLibraryScanJobProcessorJobTests.cs | 146 -------- .../MediaLibraryScanProcessorJobTests.cs | 317 ++++++++++++++++++ 85 files changed, 2559 insertions(+), 1394 deletions(-) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiscoveryJob.cs delete mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs create mode 100644 tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/FakeMediaLibraryScanDiscoveryJob.cs create mode 100644 tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanDiscoveryJobFixture.cs delete mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs diff --git a/docs/manual/managing-libraries/index.md b/docs/manual/managing-libraries/index.md index 253df261..916494e7 100644 --- a/docs/manual/managing-libraries/index.md +++ b/docs/manual/managing-libraries/index.md @@ -116,17 +116,17 @@ The template is read on every scan, so changing it changes how your folders are ## Scanning a library -Creating a library only records where the media lives. To actually read it, you scan it. You can scan a single library, or all of them at once, from the Libraries page. +Creating a library only records where the media lives. To actually read it, you scan it. You can scan a single library, or ask Lumina to scan all of them, from the Libraries page. Only one scan runs at a time: a scan that is requested while another one is running waits in the scan queue, and starts on its own when the scan ahead of it finishes. Lumina is designed to be efficient and performant. The first scan of a library reads and indexes everything it finds, so it is the slowest one. Every scan after that compares what is on disk against the previous scan and only processes what is new or changed, so it is normally much faster. How long any scan takes also depends on what is enabled for the library: metadata and artwork providers that fetch data from the web add network time on top of reading the files, and they do it only for the items that need it. -How the scan reads the files depends on the hardware that stores them. A library whose content is on a solid state drive can discover and hash several files at the same time, so turn on **Content is on SSD** for it. A library on a mechanical hard drive should keep that setting off, because parallel reads make the drive seek back and forth and can make the scan slower. Metadata extraction and artwork resolution still read the files one at a time; this setting only changes file discovery and content hashing. +How the scan reads the files depends on the hardware that stores them. A library whose content is on a solid state drive can discover and hash several files at the same time, so turn on **Content is on SSD** for it. A library on a mechanical hard drive should keep that setting off, because parallel reads make the drive seek back and forth and can make the scan slower. Metadata extraction and artwork resolution still read the files one at a time; this setting only changes file discovery and content hashing. Even when the parallel reads are on, Lumina leaves one processor free, so the rest of the application keeps responding while it scans. Scans run on the server in the background, so once one starts you can close the browser and come back later. -While a scan is running, its progress is shown live: how far along it is overall, how many items it has processed, and the operation it is currently on. A scan is queued before it starts, then runs, and ends up finished, cancelled or failed. You can cancel a running scan at any time, for one library or for all of them. +While a scan is waiting in the queue it is shown as queued, and while it is running its progress is shown live: how far along it is overall, how many items it has processed, and the operation it is currently on. A scan is queued before it starts, then runs, and ends up finished, cancelled or failed. You can cancel a scan while it is queued or running, for one library or for all of them; the library shows that its cancellation is in progress until the server confirms it. -A disabled or locked library is refused a scan. Scans can also be driven by the scheduler, so libraries refresh themselves on a timetable without you lifting a finger. +A disabled or locked library is refused a scan, and a library whose type has no scanner yet ends its scan as failed instead of staying queued forever. Scans can also be driven by the scheduler, so libraries refresh themselves on a timetable without you lifting a finger. ## Editing a library diff --git a/docs/technical/api/library/management/Api.Libraries.md b/docs/technical/api/library/management/Api.Libraries.md index 26e3807c..29803fc9 100644 --- a/docs/technical/api/library/management/Api.Libraries.md +++ b/docs/technical/api/library/management/Api.Libraries.md @@ -368,10 +368,27 @@ GET api/v1/libraries/scans/running }, "status": "Running", "overallProgressPercentage": 40.0 + }, + { + "scanId": "0b5f8d21-9c3e-4a7b-8f6d-1e2a3b4c5d6e", + "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", + "libraryId": "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", + "totalJobs": 0, + "completedJobs": 0, + "currentJobProgress": { + "completedItems": 0, + "totalItems": 0, + "currentOperation": "Queued", + "progressPercentage": 0.0 + }, + "status": "Pending", + "overallProgressPercentage": 0.0 } ] ``` +Queued scans are reported here too, with no jobs prepared yet, because media library scans are executed one at a time and a scan that was queued can wait for the scans ahead of it to finish before it starts. + ### Get Library Scan Progress #### Get Library Scan Progress Request diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md index 6f4fa111..3007533e 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md @@ -36,9 +36,6 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD } } ``` -## Amendments - -- **2026-10-09**: The generic `FileSystemDiscoveryJob` / `IFileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`), and the job execution contract is now `ExecuteAsync(Guid id, TInput input, CancellationToken token)` on `IMediaLibraryScanJob`. The `IServiceScopeFactory` decision itself is unchanged. ## Consequences @@ -105,3 +102,15 @@ services.AddDbContextFactory(options => ``` **Rejected**: Would require a dependency on EF Core in the Application layer, and even when using an abstraction, would completely defeat the purpose of using the Repository + Unit of Work patterns used everywhere else in the Application layer. + +## Amendment: Per-Type File System Discovery Jobs (2026-10-09) + +The generic `FileSystemDiscoveryJob` / `IFileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`), and the job execution contract is now `ExecuteAsync(Guid id, TInput input, CancellationToken token)` on `IMediaLibraryScanJob`. The `IServiceScopeFactory` decision itself is unchanged. + +## Amendment: Serialized Media Library Scans (2026-10-31) + +The execution model described above changed in a way that directly affects how scoped services are obtained. Until this amendment, the unit placed on the in-memory queue was the root job of a scan job graph, and the processor launched each root job in a fire-and-forget manner. Scanning several media libraries at once, which is the normal outcome of a "scan all libraries" action or of a scheduled run, therefore started one complete job chain per library at the same time. Each chain fans out to `Environment.ProcessorCount` parallel file reads for file system discovery and content hashing, and every job performed its work on the same shared thread pool that the web server uses to handle requests, so above a certain number of libraries the thread pool was starved and the API could stop answering requests for as long as the scans were running. The queue therefore carries the media library scans themselves now, and `MediaLibraryScanProcessorJob` awaits a scan completely before it dequeues the next one. + +Waiting for a complete scan means the processor owns the execution for its whole duration, which can be hours. That is why the scope lifetime at this level matters, and why the processor does not keep a scope open around a scan: a unit of work and its `DbContext` resolved there would stay alive, and hold a database connection, for the entire scan. The processor uses one short lived scope to read the scan and a second short lived scope to prepare its job graph through `IMediaLibraryScanningService`, disposes both before the job graph starts, and executes the graph outside any scope. The jobs themselves keep creating their own scopes exactly as decided above, so the `IServiceScopeFactory` decision and the sample above are unchanged. + +The scan's job graph still has exactly one top level job, and the scanner contract now makes that structural: `IMediaTypeScanner.CreateScanJobsForLibrary` returns `IMediaLibraryScanDiscoveryJob`, implemented by the file system discovery jobs, instead of a collection of jobs. Because every job awaits its children, awaiting that discovery job is what tells the processor that the scan, and with it the execution it took over from the queue, is over. Without that invariant, the processor could move on to the next scan while work of the previous one was still running and its scopes were already disposed. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md index ff4d566c..7bf5ce1c 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md @@ -40,3 +40,11 @@ Change the processor to await the root job completion and observe its exceptions Keep the current behavior of swallowing unexpected exceptions. **Rejected**: It leaves scans stuck in the `Running` state and leaks resources, which the whole point of this decision is to fix. + +## Amendment: Awaiting the Scan in the Serialized Scan Processor (2026-10-31) + +The rejection of alternative 1 rested on an assumption that no longer holds: that the queue consumer must never block. That assumption produced the defect that forced this amendment. Launching every root job in a fire-and-forget manner meant that scanning several libraries at once ran one complete job chain per library simultaneously, each of them fanning out to as many parallel file reads as the machine has processors, all on the thread pool shared with the web server, so the API could become unresponsive for the duration of the scans. Media library scans are now deliberately serialized, one at a time. The next queued scan must not start before the current one has stopped, which is only guaranteed if the processor waits for it. + +Alternative 1 is therefore the decision, and the fire-and-forget launch is removed. The failure semantics decided here are unchanged: every job still catches its own failures and publishes the `LibraryScanFailedDomainEvent`, `OperationCanceledException` still marks the job as `Canceled`, and the handlers still release the scan processing resources. + +Because the processor must keep draining the queue after a failed scan, a scan that fails must never affect the scans queued behind it. This matters the most for the action that starts several scans at once: a single library that cannot be scanned, for example because its type has no scanner yet, must not stop the libraries queued behind it. A failure that happens while a scan is being prepared now publishes the same failure event for that scan only, instead of being swallowed, and the processor moves on to the next queued scan. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs index 179da525..90d65fed 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -28,11 +28,11 @@ public interface ILibraryScanRepository : IRepository, Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); /// - /// Gets the media library scans have a status, from the storage medium. + /// Gets the media library scans that have a or a status, from the storage medium. /// /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. - Task>> GetRunningScansAsync(CancellationToken cancellationToken); + Task>> GetActiveScansAsync(CancellationToken cancellationToken); /// /// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index a141ae47..1d5ddc70 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -64,18 +64,18 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); - if (getRunningLibraryScansResult.IsFailure) - return getRunningLibraryScansResult.Errors; + // Get the scans of the current user that are either executing or still waiting in the scan queue, from the repository. + Result> getActiveLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false); + if (getActiveLibraryScansResult.IsFailure) + return getActiveLibraryScansResult.Errors; // Filter the library scans to process. List authorizedLibraryScans = []; // Admins can see all library scans. if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) - authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value); + authorizedLibraryScans.AddRange(getActiveLibraryScansResult.Value); else // For regular users, only take the library scans that belong to them. - authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)); + authorizedLibraryScans.AddRange(getActiveLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)); // Convert persistence library scans to domain entities. IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index d5dfda0d..276ec57f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -4,6 +4,7 @@ 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.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; @@ -11,7 +12,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; -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 System.Threading; @@ -27,7 +27,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler @@ -35,17 +35,17 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler /// Injected service for scanning media libraries. /// Injected tracker used for canceling media library scans. - /// Injected tracker used for media library scans progress. + /// Injected service for notifying media libraries scan progress changes to third parties. /// Injected unit of work for interacting with the data access layer repositories. public LibraryScanCancelledDomainEventHandler( IMediaLibraryScanningService mediaLibraryScanningService, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, - IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IMediaLibraryScanProgressNotifier mediaLibraryScanProgressNotifier, IUnitOfWork unitOfWork) { _mediaLibraryScanningService = mediaLibraryScanningService; _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; - _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _mediaLibraryScanProgressNotifier = mediaLibraryScanProgressNotifier; _unitOfWork = unitOfWork; } @@ -73,10 +73,13 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler { - private readonly IMediaLibraryScanningService _mediaLibraryScanningService; - private readonly IDomainEventsQueue _domainEventsQueue; - private readonly IUnitOfWork _unitOfWork; + private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; /// /// Initializes a new instance of the class. /// - /// Injected service for scanning media libraries. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for the queue of domain events. - /// Injected unit of work for interacting with the data access layer repositories. - public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork) + /// Injected queue used for processing the media library scans that are waiting to execute. + /// Injected tracker used for canceling media library scans. + /// Injected tracker used for media library scans progress. + public LibraryScanQueuedDomainEventHandler( + IMediaLibrariesScanQueue mediaLibrariesScanQueue, + IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) { - _mediaLibraryScanningService = mediaLibraryScanningService; - _domainEventsQueue = domainEventsQueue; - _unitOfWork = unitOfWork; + _mediaLibrariesScanQueue = mediaLibrariesScanQueue; + _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; } /// @@ -46,26 +43,18 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) { - // Get the library scan that was queued, from the repository. - Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryScanResult.IsFailure) - throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); - if (getLibraryScanResult.Value is null) - throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); + MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId); - // Convert the repository entity to a domain entity. - Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); - if (libraryScanDomainResult.IsFailure) - throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); + // Register the scan for cancellation before it is queued, so that a cancellation that arrives while the scan is still + // waiting for its turn is honored when the scan processor finally picks it up. + _mediaLibrariesScanCancellationTracker.RegisterScan(compositeId); - // Start the media library scan. - Result startScanResult = await _mediaLibraryScanningService.StartScanAsync( - libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false); - if (startScanResult.IsFailure) - throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); + // Report the scan as queued, so clients can show it while it waits for the scans ahead of it to finish. + // This is only a display concern, so it must never prevent the scan from being queued. + _ = _mediaLibrariesScanProgressTracker.InitializeQueuedScanProgress(domainEvent.LibraryId, compositeId); - // Queue any domain events. - foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents()) - _domainEventsQueue.Enqueue(queuedDomainEvent); + // Only the scan itself is queued, not its jobs. The scan processor prepares and executes the jobs of one scan at a time, + // so the scans run consecutively, in the order in which they were queued. + await _mediaLibrariesScanQueue.Writer.WriteAsync(compositeId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs index 38692fe5..e518f569 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs @@ -31,4 +31,11 @@ public interface IMediaLibraryScanProgressNotifier /// The object representing the unique identifier for the media library scan that failed. /// Cancellation token that can be used to stop the execution. Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken); + + /// + /// Notifies the SignalR clients about the cancellation of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that was cancelled. + /// Cancellation token that can be used to stop the execution. + Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs index b87a20da..ce5f3de5 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -65,33 +65,33 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); - if (getRunningScansResult.IsFailure) - return getRunningScansResult.Errors; + // Get the library scans that are executing or still waiting in the scan queue, from the repository. + Result> getActiveScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false); + if (getActiveScansResult.IsFailure) + return getActiveScansResult.Errors; // Filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own. - LibraryScanEntity[] userRunningRepositoryLibraryScans = []; + LibraryScanEntity[] userActiveRepositoryLibraryScans = []; if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) - userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value]; + userActiveRepositoryLibraryScans = [.. getActiveScansResult.Value]; else - userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)]; + userActiveRepositoryLibraryScans = [.. getActiveScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)]; // For each of the filtered library scans, get their progress. List libraryScanProgresses = []; - IEnumerable> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities(); - foreach (Result userRunningDomainLibraryScan in userRunningDomainLibraryScans) + IEnumerable> userActiveDomainLibraryScans = userActiveRepositoryLibraryScans.ToDomainEntities(); + foreach (Result userActiveDomainLibraryScan in userActiveDomainLibraryScans) { - if (userRunningDomainLibraryScan.IsFailure) - return userRunningDomainLibraryScan.Errors; - else - { - Result getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( - MediaLibraryScanCompositeId.Create(userRunningDomainLibraryScan.Value.Id, userRunningDomainLibraryScan.Value.UserId)); - if (getLibraryScanProgressResult.IsFailure) - return getLibraryScanProgressResult.Errors; - libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse()); - } + if (userActiveDomainLibraryScan.IsFailure) + return userActiveDomainLibraryScan.Errors; + + Result getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( + MediaLibraryScanCompositeId.Create(userActiveDomainLibraryScan.Value.Id, userActiveDomainLibraryScan.Value.UserId)); + // A scan whose progress was already released has ended, so it is not reported as active any more. + if (getLibraryScanProgressResult.IsFailure) + continue; + + libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse()); } return Result.From(libraryScanProgresses.AsEnumerable()); diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index 4ecc888d..9636335c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -96,6 +96,9 @@ internal sealed class LibraryRepository : ILibraryRepository .Include(library => library.PathTemplateParts) .AsSplitQuery() .Where(library => library.IsEnabled && !library.IsLocked) + // The scan queue executes the scans in this order, so it must be deterministic and match the order shown to the user. + .OrderBy(library => library.Title) + .ThenBy(library => library.Id) .ToListAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index d7719b69..4b031477 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -83,16 +83,17 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository } /// - /// Gets the media library scans that have a status, from the storage medium. + /// Gets the media library scans that have a or a + /// status, from the storage medium. /// /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. - public async Task>> GetRunningScansAsync(CancellationToken cancellationToken) + public async Task>> GetActiveScansAsync(CancellationToken cancellationToken) { return await _luminaDbContext.LibraryScans .Include(library => library.Library) .AsSplitQuery() - .Where(library => library.Status == LibraryScanJobStatus.Running) + .Where(library => library.Status == LibraryScanJobStatus.Pending || library.Status == LibraryScanJobStatus.Running) .ToListAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs index dad9c024..2ae920bc 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs @@ -14,8 +14,8 @@ public static partial class Errors 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 CanOnlyCancelPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelPendingOrRunningScans)); + public static Error CanOnlyFailPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyFailPendingOrRunningScans)); public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty)); public static Error LibraryScanAlreadyExists => Error.Conflict(description: nameof(LibraryScanAlreadyExists)); public static Error LibraryAlreadyBeingScanned => Error.Forbidden(description: nameof(LibraryAlreadyBeingScanned)); @@ -27,5 +27,6 @@ public static partial class Errors 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)); + public static Error NoScannerForLibraryType => Error.NotImplemented(description: nameof(NoScannerForLibraryType)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs index 58bdb569..438fe7a5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs @@ -8,6 +8,6 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib /// /// Interface for the media library scan job for discovering music file system items. /// -public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob +public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob { } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs index 0965e084..d8fc5f6a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs @@ -3,7 +3,6 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibrary using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System.Collections.Generic; #endregion namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; @@ -30,11 +29,11 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner } /// - /// Creates the media library scan jobs for the provided media library. + /// Creates the media library scan job graph for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// A collection of media library scan jobs. - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId) + /// The file system discovery job, which is the only top level job of the media library scan job graph. + public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId) { // Declare the list of jobs that this scanner requires. IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); @@ -75,7 +74,7 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob); mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob); - // Return the top level jobs that will be triggered when the scan will be started. - yield return fileSystemDiscoveryJob; + // The file system discovery job is the only top level job: no scanning can happen before the files are discovered. + return fileSystemDiscoveryJob; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs index 57c1ffce..9e0a58b9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.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 @@ -13,12 +14,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// /// The unique identifier of the domain event. /// The unique identifier of the queued media library scan. +/// The unique identifier of the user that initiated the queued media library scan. /// The unique identifier of the library whose scan was queued. /// The date and time when the domain event occurred. [DebuggerDisplay("Id: {Id}")] public record LibraryScanQueuedDomainEvent( Guid Id, ScanId ScanId, + UserId UserId, LibraryId LibraryId, 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 fa9d105e..40aa22fa 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs @@ -90,11 +90,11 @@ public class LibraryScan : AggregateRoot /// An representing either a successful operation, or an error. public Result QueueScan() { - // there must be no active scan for this library in the past 30 days + // There must be no active scan for this library in the past 30 days. if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending)) return Errors.LibraryScanning.LibraryAlreadyBeingScanned; - _domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow)); + _domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, UserId, LibraryId, DateTime.UtcNow)); return Result.Success; } @@ -110,7 +110,7 @@ public class LibraryScan : AggregateRoot else return Errors.LibraryScanning.CanOnlyStartPendingScans; - // there must be no active scan for this library in the past 30 days + // There must be no active scan for this library in the past 30 days. if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending)) return Errors.LibraryScanning.LibraryAlreadyBeingScanned; @@ -139,10 +139,11 @@ public class LibraryScan : AggregateRoot /// An representing either a successful operation, or an error. public Result CancelScan() { - if (Status == LibraryScanJobStatus.Running) + // A scan that is waiting in the scan queue can be cancelled just as well as one that is already executing. + if (Status == LibraryScanJobStatus.Pending || Status == LibraryScanJobStatus.Running) Status = LibraryScanJobStatus.Canceled; else - return Errors.LibraryScanning.CanOnlyCancelRunningScans; + return Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans; _domainEvents.Add(new LibraryScanCancelledDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow)); @@ -155,10 +156,11 @@ public class LibraryScan : AggregateRoot /// An representing either a successful operation, or an error. public Result FailScan() { - if (Status == LibraryScanJobStatus.Running) + // A scan can fail before it starts executing, for example when its media library type has no scanner yet. + if (Status == LibraryScanJobStatus.Pending || Status == LibraryScanJobStatus.Running) Status = LibraryScanJobStatus.Failed; else - return Errors.LibraryScanning.CanOnlyFailRunningScans; + return Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans; return Result.Success; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs index 80f1dacd..db967bfe 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Threading; using System.Threading.Tasks; @@ -13,13 +14,16 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib public interface IMediaLibraryScanningService { /// - /// Starts . + /// Starts and prepares its job graph. /// /// The media library scan to start. /// The type of the media library to be scanned. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken); + /// + /// An containing either the file system discovery job, which is the only top level job of the + /// media library scan job graph and whose execution completes the entire scan, or an error. + /// + Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken); /// /// Cancels . diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiscoveryJob.cs new file mode 100644 index 00000000..bac8c096 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiscoveryJob.cs @@ -0,0 +1,11 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job that discovers the file system items of a media library. +/// +/// +/// This is always the only top level job of a media library scan: a scan cannot process anything before the files are discovered. +/// +public interface IMediaLibraryScanDiscoveryJob : IMediaLibraryScanJob +{ +} 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 211282ad..61adaa6b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; 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; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; @@ -22,7 +22,6 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// internal class MediaLibraryScanningService : IMediaLibraryScanningService { - private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue; private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory; private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; @@ -31,19 +30,16 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// /// Initializes a new instance of the class. /// - /// 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 mediaLibrariesScanQueue, IMediaLibraryScannerFactory mediaLibraryScannerFactory, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, IDomainEventPublisher domainEventPublisher) { - _mediaLibrariesScanQueue = mediaLibrariesScanQueue; _mediaLibraryScannerFactory = mediaLibraryScannerFactory; _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; @@ -51,51 +47,48 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService } /// - /// Starts . + /// Starts and prepares its job graph. /// /// The media library scan to start. /// The type of the media library to be scanned. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken) + /// + /// An containing either the file system discovery job, which is the only top level job of the + /// media library scan job graph and whose execution completes the entire scan, or an error. + /// + public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken) { - // mark the scan itself as started + // Resolve the scanner before changing any state, so that a media library type without a scanner fails its own scan, + // without leaving it started and without affecting the other scans that are queued behind it. + Result getScannerResult = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType); + if (getScannerResult.IsFailure) + return getScannerResult.Errors; + + // Build the job graph before the scan starts, so that its jobs already carry the scan identity when they report their progress, + // and so that the total number of jobs is known for the progress tracking. + IMediaLibraryScanDiscoveryJob rootJob = getScannerResult.Value.CreateScanJobsForLibrary(scan.LibraryId); + SetScanPropertiesForJobChain(rootJob, scan.Id, scan.UserId); + int totalJobs = CountTotalJobs(rootJob); + + // Mark the scan itself as started. Result startScanResult = scan.StartScan(); if (startScanResult.IsFailure) return startScanResult.Errors; + MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId); + + // Register the scan in the tracker for cancellation tokens. + _mediaLibrariesScanCancellationTracker.RegisterScan(compositeId); + + // Initialize the progress of the scan before publishing its events, so that the handlers of the started event can already report it. + Result initializeScanProgressResult = _mediaLibrariesScanProgressTracker.InitializeScanProgress(scan.LibraryId, compositeId, totalJobs); + if (initializeScanProgressResult.IsFailure) + return initializeScanProgressResult.Errors; + foreach (IDomainEvent domainEvent in scan.GetDomainEvents()) await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); - - // register the scan in the tracker for cancellation tokens - _mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); - try - { - // link the user's cancellation token with the scan's token - using CancellationTokenSource linkedSource = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId))); - - // get a media library scanner for the provided media library type - IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType); - // get the list of scan jobs for the retrieved scanner. It is impotant to enumerate them here, because deferred execuction would destroy any graph relationships - // and properties we might set before putting the jobs on the in-memory queue. - List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId)]; - - // count total jobs in the chain by traversing the job graph - int totalJobs = CountTotalJobs(jobs); - _mediaLibrariesScanProgressTracker.InitializeScanProgress(scan.LibraryId, MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId), totalJobs); - - // enqueue the jobs on the channel from where they will be processed - foreach (IMediaLibraryScanJob job in jobs) - { - // 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) { } - return Result.Success; + return Result.From(rootJob); } /// @@ -105,7 +98,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// An representing either a successful operation, or an error. public Result CancelScan(LibraryScan scan) { - // trigger the process that cancels the jobs of the scan + // Trigger the process that cancels the jobs of the scan. _mediaLibrariesScanCancellationTracker.CancelScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)); return Result.Success; } @@ -120,21 +113,20 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService { job.ScanId = scanId; job.UserId = userId; - // recursively set properties for all children + // 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. + /// Counts the total number of unique media library scan jobs in the job graph that starts at . /// - /// A list of root media library scan jobs to traverse. + /// The file system discovery job, which is the only top level job of the scan job graph. /// The total count of unique media library scan jobs. - private static int CountTotalJobs(List rootJobs) + private static int CountTotalJobs(IMediaLibraryScanDiscoveryJob rootJob) { HashSet uniqueJobs = []; - foreach (IMediaLibraryScanJob job in rootJobs) - TraverseJobGraph(job, uniqueJobs); + TraverseJobGraph(rootJob, uniqueJobs); return uniqueJobs.Count; } 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 index 1c64364d..548a785e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs @@ -11,6 +11,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// public interface IMediaLibrariesScanProgressTracker { + /// + /// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared. + /// + /// The object representing the unique identifier of the media library being scanned. + /// Model for tracking media library scans. + /// An representing either a successful operation, or an error. + Result InitializeQueuedScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + /// /// Initializes the the progress tracking of a media library scan. /// 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 index 2f604053..8870ae4d 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs @@ -16,6 +16,36 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr { private readonly ConcurrentDictionary _scanProgresses = new(); + /// + /// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared. + /// + /// The object representing the unique identifier of the media library being scanned. + /// Model for tracking media library scans. + /// An representing either a successful operation, or an error. + public Result InitializeQueuedScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + // The total number of jobs is only known once the scan starts, because the job graph is prepared at that point. + Result createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Queued"); + if (createLibraryScanJobProgressResult.IsFailure) + return createLibraryScanJobProgressResult.Errors; + + Result createScanProgressResult = MediaLibraryScanProgress.Create( + mediaLibraryScanCompositeId.ScanId, + mediaLibraryScanCompositeId.UserId, + libraryId, + completedJobs: 0, + totalJobs: 0, + LibraryScanJobStatus.Pending, + Optional.Some(createLibraryScanJobProgressResult.Value) + ); + if (createScanProgressResult.IsFailure) + return createScanProgressResult.Errors; + + _scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value; + + return Result.Created; + } + /// /// Initializes the the progress tracking of a media library scan. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs index cb679ffe..f7f2a1c8 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs @@ -1,22 +1,23 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System.Threading.Channels; #endregion namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; /// -/// Interface for the message queue for handling instances. +/// Interface for the message queue for handling the media library scans that are waiting to execute. +/// Only one media library scan is executed at a time, so the queue guarantees that scans run consecutively. /// public interface IMediaLibrariesScanQueue { /// - /// Gets the writer for the queue, allowing producers to enqueue instances. + /// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute. /// - public ChannelWriter Writer { get; } + ChannelWriter Writer { get; } /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute. /// - public ChannelReader Reader { get; } + ChannelReader Reader { get; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs index ad1913b7..100f7d0c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaLibraryScannerFactory.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; #endregion @@ -13,6 +14,8 @@ internal interface IMediaLibraryScannerFactory /// Creates a media library scanner based on the provided library type. /// /// The type of the library that determines the type of the created media library scanner. - /// A media library scanner for the specified media library type. - IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType); + /// + /// An containing either a media library scanner for the specified media library type, or an error. + /// + Result CreateLibraryScanner(LibraryType libraryType); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs index c0027ad4..f39e2cf0 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs @@ -2,7 +2,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using System.Collections.Generic; #endregion namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; @@ -18,9 +17,9 @@ public interface IMediaTypeScanner LibraryType SupportedLibraryType { get; } /// - /// Creates the media library scan jobs for the provided media library. + /// Creates the media library scan job graph for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// A collection of media library scan jobs. - IEnumerable CreateScanJobsForLibrary(LibraryId libraryId); + /// The file system discovery job, which is the only top level job of the media library scan job graph. + IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs index f75e5d94..caebcdce 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.Extensions.DependencyInjection; using System; #endregion @@ -28,49 +30,17 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory /// Creates a media library scanner for the specified library type. /// /// The type of the media library. - /// A media library scanner for the specified library type. - public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType) + /// + /// An containing either a media library scanner for the specified media library type, or an error. + /// + public Result CreateLibraryScanner(LibraryType libraryType) { return libraryType switch { - // Implemented scanners. - LibraryType.Book => _serviceProvider.GetRequiredService(), - LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."), - LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."), - LibraryType.Magazine => throw new NotImplementedException("Magazine scanner is not implemented."), - LibraryType.Newspaper => throw new NotImplementedException("Newspaper scanner is not implemented."), - LibraryType.Manga => throw new NotImplementedException("Manga scanner is not implemented."), - LibraryType.GraphicNovel => throw new NotImplementedException("GraphicNovel scanner is not implemented."), - LibraryType.AcademicPaper => throw new NotImplementedException("AcademicPaper scanner is not implemented."), - LibraryType.SheetMusic => throw new NotImplementedException("SheetMusic scanner is not implemented."), - LibraryType.Movie => throw new NotImplementedException("Movie scanner is not implemented."), - LibraryType.TvShow => throw new NotImplementedException("TvShow scanner is not implemented."), - LibraryType.Documentary => throw new NotImplementedException("Documentary scanner is not implemented."), - LibraryType.Anime => throw new NotImplementedException("Anime scanner is not implemented."), - LibraryType.ConcertVideo => throw new NotImplementedException("ConcertVideo scanner is not implemented."), - LibraryType.TutorialVideo => throw new NotImplementedException("TutorialVideo scanner is not implemented."), - LibraryType.HomeVideo => throw new NotImplementedException("HomeVideo scanner is not implemented."), - LibraryType.YouTubeVideo => throw new NotImplementedException("YouTubeVideo scanner is not implemented."), - LibraryType.MusicVideo => throw new NotImplementedException("MusicVideo scanner is not implemented."), - LibraryType.LiveRecordingVideo => throw new NotImplementedException("LiveRecordingVideo scanner is not implemented."), - LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."), - LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."), - LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."), - LibraryType.Music => _serviceProvider.GetRequiredService(), - LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."), - LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."), - LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."), - LibraryType.CoverSongAudio => throw new NotImplementedException("CoverSongAudio scanner is not implemented."), - LibraryType.Remix => throw new NotImplementedException("Remix scanner is not implemented."), - LibraryType.SoundEffect => throw new NotImplementedException("SoundEffect scanner is not implemented."), - LibraryType.PodcastAudio => throw new NotImplementedException("PodcastAudio scanner is not implemented."), - LibraryType.Photo => throw new NotImplementedException("Photo scanner is not implemented."), - LibraryType.Playlist => throw new NotImplementedException("Playlist scanner is not implemented."), - LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."), - LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."), - LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."), - // Catch-all for unknown or unsupported types. - _ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.") + LibraryType.Book => Result.From(_serviceProvider.GetRequiredService()), + LibraryType.Music => Result.From(_serviceProvider.GetRequiredService()), + // Every other media library type is modeled, but has no scanner yet, so scanning it is reported as unsupported. + _ => Errors.LibraryScanning.NoScannerForLibraryType }; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs index 2d7868d9..df8d831a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs @@ -107,7 +107,8 @@ public sealed class MediaLibraryScanProgress : ValueObject LibraryScanJobStatus status, Optional currentJobProgress) { - if (totalJobs <= 0) + // A scan waiting in the scan queue has no jobs prepared yet, so its total number of jobs is only known once it starts. + if (totalJobs < 0 || (totalJobs == 0 && status != LibraryScanJobStatus.Pending)) return Errors.LibraryScanning.TotalScanJobsCountMustBePositive; if (completedJobs < 0) return Errors.LibraryScanning.CompletedScanJobsCountMustBePositive; diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs index 75a3f6f5..a7c3abbe 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs @@ -5,6 +5,6 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext /// /// Interface for the media library scan job for discovering books file system items. /// -public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob +public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob { } 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 82d379a6..482cabd3 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 @@ -3,7 +3,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System.Collections.Generic; #endregion namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; @@ -30,19 +29,19 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner } /// - /// Creates the media library scan jobs for the provided media library. + /// Creates the media library scan job graph for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// A collection of media library scan jobs. - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId) + /// The file system discovery job, which is the only top level job of the media library scan job graph. + public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId) { - // declare the list of jobs that this scanner requires + // Declare the list of jobs that this scanner requires. IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId); IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId); IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(libraryId); - // establish the hierarchical relationships between jobs + // Establish the hierarchical relationships between jobs. fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob); mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob); @@ -52,7 +51,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob); mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob); - // the enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration + // The enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration // invalidation job invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, the // metadata enrichment job enriches the metadata and links the media contributors, and the artwork enrichment job resolves the artwork. // The artwork enrichment job is always the last job in the directed acyclic job graph, running after the metadata enrichment job, so that @@ -70,7 +69,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob); mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob); - // return the top level jobs that will be triggered when the scan will be started - yield return fileSystemDiscoveryJob; + // The file system discovery job is the only top level job: no scanning can happen before the files are discovered. + return fileSystemDiscoveryJob; } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index b44909f7..591ca71f 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -112,7 +112,7 @@ public static class InfrastructureLayerServices // Media library scanning. services.AddSingleton(); services.AddSingleton(); - services.AddHostedService(); + services.AddHostedService(); services.AddTransient(); services.AddTransient(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs index 0e25a0ab..504ddd30 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs @@ -70,115 +70,111 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService()!; + IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Get the library from the repository. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + + // Convert it to a domain object. + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + + // When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan. + Dictionary? fingerprintsByPath = null; + if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService()!; - IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService()!; + Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getFingerprintsResult.IsFailure) + throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); + fingerprintsByPath = getFingerprintsResult.Value; + } - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // Get the library from the repository. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedContentLocations = 0; - // Convert it to a domain object. - Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsFailure) - throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + List stagingBatch = []; + List fingerprintBatch = []; - // When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan. - Dictionary? fingerprintsByPath = null; - if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) + // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. + bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; + if (shouldParallelizeReads) + _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); + + // Get the files for each of the media library content locations. + foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) + { + cancellationToken.ThrowIfCancellationRequested(); + + await DiscoverContentLocationAsync( + contentLocation.Path, + fileProviderService, + directoryProviderService, + fingerprintsByPath is not null, + shouldParallelizeReads, + fingerprintsByPath, + stagingBatch, + fingerprintBatch, + unitOfWork.LibraryScanStagingResultsRepository, + unitOfWork.DirectoryScanFingerprintRepository, + cancellationToken).ConfigureAwait(false); + processedContentLocations++; + + // Increment the number of processed elements progress in a high-frequency counter with low overhead check. + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) { - Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getFingerprintsResult.IsFailure) - throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); - fingerprintsByPath = getFingerprintsResult.Value; + publishJobProgressResult = await PublishJobProgressAsync( + domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastHeartbeat = now; } + } - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size. + if (stagingBatch.Count > 0) + { + Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + throw new InvalidOperationException(insertResult.FirstError.Description); + } + if (fingerprintBatch.Count > 0) + { + Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + throw new InvalidOperationException(upsertResult.FirstError.Description); + } - TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); - DateTime lastHeartbeat = DateTime.UtcNow; - int processedContentLocations = 0; + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; - List stagingBatch = []; - List fingerprintBatch = []; - - // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. - bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; - if (shouldParallelizeReads) - _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); - - // Get the files for each of the media library content locations. - foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) - { - cancellationToken.ThrowIfCancellationRequested(); - - await DiscoverContentLocationAsync( - contentLocation.Path, - fileProviderService, - directoryProviderService, - fingerprintsByPath is not null, - shouldParallelizeReads, - fingerprintsByPath, - stagingBatch, - fingerprintBatch, - unitOfWork.LibraryScanStagingResultsRepository, - unitOfWork.DirectoryScanFingerprintRepository, - cancellationToken).ConfigureAwait(false); - processedContentLocations++; - - // Increment the number of processed elements progress in a high-frequency counter with low overhead check. - DateTime now = DateTime.UtcNow; - if (now - lastHeartbeat >= heartbeatInterval) - { - publishJobProgressResult = await PublishJobProgressAsync( - domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastHeartbeat = now; - } - } - - // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size. - if (stagingBatch.Count > 0) - { - Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); - if (insertResult.IsFailure) - throw new InvalidOperationException(insertResult.FirstError.Description); - } - if (fingerprintBatch.Count > 0) - { - Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - throw new InvalidOperationException(upsertResult.FirstError.Description); - } - - // This job finished, increment the number of processed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs index f04ffff6..500fe710 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs @@ -67,86 +67,58 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Get the library from the repository, both to verify that it exists and to know its content locations. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + + // The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default. + ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService()!; + IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; + Result pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts); + if (pathTemplateResult.IsFailure) + throw new InvalidOperationException(pathTemplateResult.FirstError.Description); + LibraryPathTemplate pathTemplate = pathTemplateResult.Value; + + // The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items. + Result> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getPathsResult.IsFailure) + throw new InvalidOperationException(getPathsResult.FirstError.Description); + IReadOnlyList paths = getPathsResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedItems = 0; + + List metadataBatch = []; + foreach (string path in paths) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + cancellationToken.ThrowIfCancellationRequested(); - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // Get the library from the repository, both to verify that it exists and to know its content locations. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsFailure) - throw new InvalidOperationException(domainLibraryResult.FirstError.Description); - - // The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default. - ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService()!; - IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; - Result pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts); - if (pathTemplateResult.IsFailure) - throw new InvalidOperationException(pathTemplateResult.FirstError.Description); - LibraryPathTemplate pathTemplate = pathTemplateResult.Value; - - // The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items. - Result> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getPathsResult.IsFailure) - throw new InvalidOperationException(getPathsResult.FirstError.Description); - IReadOnlyList paths = getPathsResult.Value; - - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); - DateTime lastHeartbeat = DateTime.UtcNow; - int processedItems = 0; - - List metadataBatch = []; - foreach (string path in paths) - { - cancellationToken.ThrowIfCancellationRequested(); - - metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService)); - if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE) - { - Result insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false); - if (insertBatchResult.IsFailure) - throw new InvalidOperationException(insertBatchResult.FirstError.Description); - Result saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveBatchResult.IsFailure) - throw new InvalidOperationException(saveBatchResult.FirstError.Description); - metadataBatch.Clear(); - unitOfWork.ClearTrackedEntities(); - } - processedItems++; - - // Increment the number of processed elements progress in a high-frequency counter with low overhead check. - DateTime now = DateTime.UtcNow; - if (now - lastHeartbeat >= heartbeatInterval) - { - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastHeartbeat = now; - } - } - - // Flush any remaining extracted metadata items that did not reach the batch size. - if (metadataBatch.Count > 0) + metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService)); + if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE) { Result insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false); if (insertBatchResult.IsFailure) @@ -154,16 +126,40 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe Result saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveBatchResult.IsFailure) throw new InvalidOperationException(saveBatchResult.FirstError.Description); + metadataBatch.Clear(); + unitOfWork.ClearTrackedEntities(); } + processedItems++; - // This job finished, increment the number of processed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; + // Increment the number of processed elements progress in a high-frequency counter with low overhead check. + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) + { + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastHeartbeat = now; + } + } - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Flush any remaining extracted metadata items that did not reach the batch size. + if (metadataBatch.Count > 0) + { + Result insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsFailure) + throw new InvalidOperationException(insertBatchResult.FirstError.Description); + Result saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveBatchResult.IsFailure) + throw new InvalidOperationException(saveBatchResult.FirstError.Description); + } + + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs index 64b5506a..ed044244 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue. - await Task.Run(async () => - { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // Load the media library, whose type determines the artwork enricher to use. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - LibraryType libraryType = getLibraryResult.Value.LibraryType; + // Load the media library, whose type determines the artwork enricher to use. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider - .GetServices() - .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); - if (artworkEnricher is null) - throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'."); + IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (artworkEnricher is null) + throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'."); - await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); + await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); - // Increment the number of completed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. - if (Children.Count == 0) - await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 28c39806..fb7b7526 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -45,47 +45,43 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + cancellationToken.ThrowIfCancellationRequested(); + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue - await Task.Run(async () => - { - Status = LibraryScanJobStatus.Running; - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // mark the staging results against the media library scan snapshot of the previous scan - Result markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (markChangesResult.IsFailure) - throw new InvalidOperationException(markChangesResult.FirstError.Description); + // Mark the staging results against the media library scan snapshot of the previous scan. + Result markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (markChangesResult.IsFailure) + throw new InvalidOperationException(markChangesResult.FirstError.Description); - // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // this job finished, increment the number of processed jobs progress - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs index 41eff734..b0b76b80 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -49,99 +49,95 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue - await Task.Run(async () => + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Count the files that need hashing, for progress reporting purposes. + Result getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getFilesToHashCountResult.IsFailure) + throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); + int totalFilesToHash = getFilesToHashCountResult.Value; + + // Get the library only when there are files to hash, and only the scalar values needed to know whether its content is stored on a solid state drive. + // in which case the file reads run in parallel. + bool shouldParallelizeReads = false; + if (totalFilesToHash > 0) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync( + LibraryId.Value, + shouldIncludeNavigationProperties: false, + shouldTrackEntities: false, + cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + shouldParallelizeReads = getLibraryResult.Value.IsContentOnSsd; + } - IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedFilesCount = 0; + string? lastPath = null; - // count the files that need hashing, for progress reporting purposes - Result getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getFilesToHashCountResult.IsFailure) - throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); - int totalFilesToHash = getFilesToHashCountResult.Value; + // Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size. + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); - // Get the library only when there are files to hash, and only the scalar values needed to know whether its content is stored on a solid state drive,. - // in which case the file reads run in parallel. - bool shouldParallelizeReads = false; - if (totalFilesToHash > 0) + Result> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getFilesToHashPageResult.IsFailure) + throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); + IReadOnlyList filesToHashPage = getFilesToHashPageResult.Value; + if (filesToHashPage.Count == 0) + break; + + // Hash the files of the current page in parallel, invoking the progress callback before each file. + List hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () => { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync( - LibraryId.Value, - shouldIncludeNavigationProperties: false, - shouldTrackEntities: false, - cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - shouldParallelizeReads = getLibraryResult.Value.IsContentOnSsd; - } - - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedFilesCount = 0; - string? lastPath = null; - - // Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size. - while (true) - { - cancellationToken.ThrowIfCancellationRequested(); - - Result> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getFilesToHashPageResult.IsFailure) - throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); - IReadOnlyList filesToHashPage = getFilesToHashPageResult.Value; - if (filesToHashPage.Count == 0) - break; - - // Hash the files of the current page in parallel, invoking the progress callback before each file. - List hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () => + // Check if enough time has passed since last update. + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) { - // Check if enough time has passed since last update. - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) - { - // Increment the number of processed elements progress. - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastUpdateTime = now; - } - }, cancellationToken).ConfigureAwait(false); + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + }, cancellationToken).ConfigureAwait(false); - // Write the computed hashes back to the staging results. - Result updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); - if (updateHashesResult.IsFailure) - throw new InvalidOperationException(updateHashesResult.FirstError.Description); + // Write the computed hashes back to the staging results. + Result updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); + if (updateHashesResult.IsFailure) + throw new InvalidOperationException(updateHashesResult.FirstError.Description); - lastPath = filesToHashPage[^1].Path; - } + lastPath = filesToHashPage[^1].Path; + } - // This job finished, increment the number of processed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 86b77f91..41e9e3c2 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue. - await Task.Run(async () => - { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // Load the media library, whose type determines the metadata enricher to use. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - LibraryType libraryType = getLibraryResult.Value.LibraryType; + // Load the media library, whose type determines the metadata enricher to use. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider - .GetServices() - .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); - if (metadataEnricher is null) - throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'."); + IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (metadataEnricher is null) + throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'."); - await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); + await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); - // Increment the number of completed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. - if (Children.Count == 0) - await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs index 73d9af1c..8891a703 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs @@ -54,124 +54,120 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue. - await Task.Run(async () => + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + // Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints + // are compared against the current provider configuration to detect whether it changed since the last scan. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryEntity library = getLibraryResult.Value; + + // The type of the media library determines the materializer whose enrichment state is invalidated. + IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType); + if (materializer is null) + throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'."); + + // Load the provider configurations of the media library, whose fingerprint is compared against the stored one. + Result> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getMetadataConfigurationsResult.IsFailure) + throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description); + + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description); + + // Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing. + bool shouldAggregateMetadataWhenMissing = false; + bool shouldAggregateArtworkWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - // Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints - // are compared against the current provider configuration to detect whether it changed since the last scan. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - LibraryEntity library = getLibraryResult.Value; - - // The type of the media library determines the materializer whose enrichment state is invalidated. - IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider - .GetServices() - .FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType); - if (materializer is null) - throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'."); - - // Load the provider configurations of the media library, whose fingerprint is compared against the stored one. - Result> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getMetadataConfigurationsResult.IsFailure) - throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description); - - Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getArtworkConfigurationsResult.IsFailure) - throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description); - - // Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing. - bool shouldAggregateMetadataWhenMissing = false; - bool shouldAggregateArtworkWhenMissing = false; - if (unitOfWork.UserSettingsRepository is not null) + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings."); + else { - Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); - if (getUserSettingsResult.IsFailure) - _logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings."); - else - { - shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; - shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false; - } + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false; } + } - // Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration - // changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration - // was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored. - string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb); - string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb); - string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]); + // Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration + // changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration + // was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored. + string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb); + string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]); - if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint) - { - Result resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (resetMetadataResult.IsFailure) - throw new InvalidOperationException(resetMetadataResult.FirstError.Description); - } + if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint) + { + Result resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetMetadataResult.IsFailure) + throw new InvalidOperationException(resetMetadataResult.FirstError.Description); + } - // A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well. - if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint) - { - Result resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (resetPathTemplateMetadataResult.IsFailure) - throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description); - } + // A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well. + if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint) + { + Result resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetPathTemplateMetadataResult.IsFailure) + throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description); + } - if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint) - { - Result resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (resetArtworkResult.IsFailure) - throw new InvalidOperationException(resetArtworkResult.FirstError.Description); - } + if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint) + { + Result resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetArtworkResult.IsFailure) + throw new InvalidOperationException(resetArtworkResult.FirstError.Description); + } - // Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. - // The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository - // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed. - library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; - library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; - library.PathTemplateFingerprint = pathTemplateFingerprint; - library.UpdatedOnUtc = DateTime.UtcNow; - library.UpdatedBy = Guid.NewGuid(); + // Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. + // The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository + // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed. + library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; + library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; + library.PathTemplateFingerprint = pathTemplateFingerprint; + library.UpdatedOnUtc = DateTime.UtcNow; + library.UpdatedBy = Guid.NewGuid(); - Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new InvalidOperationException(saveChangesResult.FirstError.Description); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // Increment the number of processed elements progress. - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // Increment the number of completed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. - if (Children.Count == 0) - await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 34a919b6..8e9cfe60 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -48,104 +48,100 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue. - await Task.Run(async () => + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Load the media library, whose type determines the materializer used to create the media library items. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; + + IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (materializer is null) + throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'."); + + // Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + // Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them. + Result> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getDeletedPathsResult.IsFailure) + throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); + + // Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched. + Result> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getChangedPathsResult.IsFailure) + throw new InvalidOperationException(getChangedPathsResult.FirstError.Description); + + // Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan. + Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); + if (applySnapshotSwapResult.IsFailure) + throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); + + // Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow. + if (getChangedPathsResult.Value.Count > 0) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Result resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); + if (resetEnrichmentStateResult.IsFailure) + throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); + } - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + // Raise a deletion event for every media library scan snapshot item that is no longer present on disk. + foreach (string deletedPath in getDeletedPathsResult.Value) + { + cancellationToken.ThrowIfCancellationRequested(); + await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + } - // Load the media library, whose type determines the materializer used to create the media library items. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); - LibraryType libraryType = getLibraryResult.Value.LibraryType; + // Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata. + Result> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getPathsResult.IsFailure) + throw new InvalidOperationException(getPathsResult.FirstError.Description); - IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider - .GetServices() - .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); - if (materializer is null) - throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'."); + Result materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false); + if (materializeItemsResult.IsFailure) + throw new InvalidOperationException(materializeItemsResult.FirstError.Description); - // Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them. - Result> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getDeletedPathsResult.IsFailure) - throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); + // The staged data is only cleared once the materialized items are safely stored, so a failed save can be retried from the same staged data. + Result clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); + if (clearStagedDataResult.IsFailure) + throw new InvalidOperationException(clearStagedDataResult.FirstError.Description); - // Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched. - Result> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getChangedPathsResult.IsFailure) - throw new InvalidOperationException(getChangedPathsResult.FirstError.Description); + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan. - Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); - if (applySnapshotSwapResult.IsFailure) - throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow. - if (getChangedPathsResult.Value.Count > 0) - { - Result resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); - if (resetEnrichmentStateResult.IsFailure) - throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); - } - - // Raise a deletion event for every media library scan snapshot item that is no longer present on disk. - foreach (string deletedPath in getDeletedPathsResult.Value) - { - cancellationToken.ThrowIfCancellationRequested(); - await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - } - - // Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata. - Result> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getPathsResult.IsFailure) - throw new InvalidOperationException(getPathsResult.FirstError.Description); - - Result materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false); - if (materializeItemsResult.IsFailure) - throw new InvalidOperationException(materializeItemsResult.FirstError.Description); - - Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new InvalidOperationException(saveChangesResult.FirstError.Description); - - // The staged data is only cleared once the materialized items are safely stored, so a failed save can be retried from the same staged data. - Result clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); - if (clearStagedDataResult.IsFailure) - throw new InvalidOperationException(clearStagedDataResult.FirstError.Description); - - // Increment the number of processed elements progress. - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - // Increment the number of completed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. - if (Children.Count == 0) - await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index 5bd14638..c104be28 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -75,111 +75,107 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF { try { + cancellationToken.ThrowIfCancellationRequested(); // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == 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; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Get the library from the repository. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + + // Convert it to a domain object. + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + + // When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan. + Dictionary? fingerprintsByPath = null; + if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) { - Status = LibraryScanJobStatus.Running; - // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getFingerprintsResult.IsFailure) + throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); + fingerprintsByPath = getFingerprintsResult.Value; + } - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // Get the library from the repository. - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedContentLocations = 0; - // Convert it to a domain object. - Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsFailure) - throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + List stagingBatch = []; + List fingerprintBatch = []; - // When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan. - Dictionary? fingerprintsByPath = null; - if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) + // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. + bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; + if (shouldParallelizeReads) + _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); + + // Get the files for each of the media library content locations. + foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) + { + cancellationToken.ThrowIfCancellationRequested(); + + await DiscoverContentLocationAsync( + contentLocation.Path, + fingerprintsByPath is not null, + shouldParallelizeReads, + fingerprintsByPath, + stagingBatch, + fingerprintBatch, + unitOfWork.LibraryScanStagingResultsRepository, + unitOfWork.DirectoryScanFingerprintRepository, + cancellationToken).ConfigureAwait(false); + processedContentLocations++; + + // Increment the number of processed elements progress in a high-frequency counter with low overhead check. + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) { - Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getFingerprintsResult.IsFailure) - throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); - fingerprintsByPath = getFingerprintsResult.Value; + publishJobProgressResult = await PublishJobProgressAsync( + domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastHeartbeat = now; } + } - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size. + if (stagingBatch.Count > 0) + { + Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + throw new InvalidOperationException(insertResult.FirstError.Description); + } + if (fingerprintBatch.Count > 0) + { + Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + throw new InvalidOperationException(upsertResult.FirstError.Description); + } - TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); - DateTime lastHeartbeat = DateTime.UtcNow; - int processedContentLocations = 0; + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; - List stagingBatch = []; - List fingerprintBatch = []; - - // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. - bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; - if (shouldParallelizeReads) - _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); - - // Get the files for each of the media library content locations. - foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) - { - cancellationToken.ThrowIfCancellationRequested(); - - await DiscoverContentLocationAsync( - contentLocation.Path, - fingerprintsByPath is not null, - shouldParallelizeReads, - fingerprintsByPath, - stagingBatch, - fingerprintBatch, - unitOfWork.LibraryScanStagingResultsRepository, - unitOfWork.DirectoryScanFingerprintRepository, - cancellationToken).ConfigureAwait(false); - processedContentLocations++; - - // Increment the number of processed elements progress in a high-frequency counter with low overhead check. - DateTime now = DateTime.UtcNow; - if (now - lastHeartbeat >= heartbeatInterval) - { - publishJobProgressResult = await PublishJobProgressAsync( - domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastHeartbeat = now; - } - } - - // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size. - if (stagingBatch.Count > 0) - { - Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); - if (insertResult.IsFailure) - throw new InvalidOperationException(insertResult.FirstError.Description); - } - if (fingerprintBatch.Count > 0) - { - Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - throw new InvalidOperationException(upsertResult.FirstError.Description); - } - - // This job finished, increment the number of processed jobs progress. - await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - - // Call each linked child with the obtained payload. - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs index a06de708..d3227900 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs @@ -46,11 +46,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca if (cancellationToken.IsCancellationRequested) return; - // throttle network traffic to no more than 20 updates a second, any more are pointless from a progress report perspective + // Throttle network traffic to no more than 20 updates a second, any more are pointless from a progress report perspective. DebounceDispatcher debouncer = _debouncers.GetOrAdd(mediaLibraryScanCompositeId, _ => new DebounceDispatcher(TimeSpan.FromMilliseconds(50))); await debouncer.DebounceAsync(async () => { - // the token might be canceled after initial check but before debounced execution starts + // The token might be canceled after initial check but before debounced execution starts. if (cancellationToken.IsCancellationRequested) return; @@ -105,6 +105,27 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca } } + /// + /// Notifies the SignalR clients about the cancellation of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that was cancelled. + /// Cancellation token that can be used to stop the execution. + public async Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + return; + Result progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); + + CleanupDebouncer(mediaLibraryScanCompositeId); + + if (!progressResult.IsFailure) + { + MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); + await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync( + "libraryScanCancelledEvent", progress with { Status = LibraryScanJobStatus.Canceled.ToString() }, cancellationToken).ConfigureAwait(false); + } + } + /// /// Disposes the debouncer that was used in a scan identified by , that is now completed. /// diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs index b263fbd7..d174eb04 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueue.cs @@ -1,25 +1,26 @@ #region ========================================================================= USING ===================================================================================== 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 System.Threading.Channels; #endregion namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; /// -/// Provides an in-memory message queue for handling instances. +/// Provides an in-memory message queue for handling the media library scans that are waiting to execute. /// internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue { - private readonly Channel _channel = Channel.CreateUnbounded(); + private readonly Channel _channel = Channel.CreateUnbounded(); /// - /// Gets the writer for the queue, allowing producers to enqueue instances. + /// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute. /// - public ChannelWriter Writer => _channel.Writer; + public ChannelWriter Writer => _channel.Writer; /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute. /// - public ChannelReader Reader => _channel.Reader; + public ChannelReader Reader => _channel.Reader; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs deleted file mode 100644 index ae08ef86..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -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; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; - -/// -/// Background service for processing media library scan jobs from an in-memory message queue. -/// -internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService -{ - private readonly IMediaLibrariesScanQueue _mediaScanQueue; - private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; - - /// - /// Initializes a new instance of the class. - /// - /// Injected queue used for processing media libraries scan jobs. - /// Injected tracker used for canceling media library scans. - public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker) - { - _mediaScanQueue = mediaScanQueue; - _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; - } - - /// - /// Method called when the background service starts. - /// - /// Cancellation token that can be used to stop the execution. - protected override async Task ExecuteAsync(CancellationToken cancellationToken) - { - // continuously processes and executes media library scan jobs from the queue until the application shuts down - // remark: since only top level scan jobs are placed on the bus, but they themselves trigger the execution of their children jobs, and so on, - // their completion should not be awaited here due to some of them being long running tasks; therefor they are just fired synchronously - // without being awaited, while still properly handling any exceptions they might throw in their asynchronous execution - 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(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.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs new file mode 100644 index 00000000..25650cea --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs @@ -0,0 +1,181 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; + +/// +/// Background service that executes the queued media library scans one at a time, in the order in which they were queued. +/// +internal sealed class MediaLibraryScanProcessorJob : BackgroundService +{ + private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected queue used for processing the media library scans that are waiting to execute. + /// Injected tracker used for canceling media library scans. + /// Injected factory for creating scopes in which services are requested. + /// Injected service for logging. + public MediaLibraryScanProcessorJob( + IMediaLibrariesScanQueue mediaLibrariesScanQueue, + IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, + IServiceScopeFactory serviceScopeFactory, + ILogger logger) + { + _mediaLibrariesScanQueue = mediaLibrariesScanQueue; + _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Method called when the background service starts. + /// + /// Cancellation token that can be used to stop the execution. + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // The queue is only drained here, one scan at a time: only after the job graph of the current scan completes is the next scan dequeued, + // so at most one media library scan executes at any moment, regardless of how many scans were queued at once. + await foreach (MediaLibraryScanCompositeId compositeId in _mediaLibrariesScanQueue.Reader.ReadAllAsync(stoppingToken).ConfigureAwait(false)) + { + try + { + await ProcessScanAsync(compositeId, stoppingToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // A scan that fails must never stop the scans that are queued behind it, so its failure is logged and the queue keeps draining. + _logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value); + } + } + } + + /// + /// Processes a single queued media library scan, from its preparation to the completion of its job graph. + /// + /// Model for tracking the queued media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task ProcessScanAsync(MediaLibraryScanCompositeId compositeId, CancellationToken stoppingToken) + { + // Get the token that cancels this scan, and do not start the scan at all when it was already cancelled while it was waiting for its turn. + CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(compositeId); + if (scanToken.IsCancellationRequested) + return; + + // The scan must stop both when the user cancels it and when the application shuts down, so the two are linked into a single token + // that is passed to everything the scan does. Disposing the source when the scan is over releases its registrations on both tokens. + using CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, scanToken); + + LibraryId? libraryId = null; + + try + { + LibraryScan libraryScan; + LibraryType libraryType; + + // Resolve the scan in a short lived scope, so that its unit of work and its DbContext are released before the scan starts executing. + await using (AsyncServiceScope readScope = _serviceScopeFactory.CreateAsyncScope()) + { + IUnitOfWork unitOfWork = readScope.ServiceProvider.GetRequiredService(); + Result getLibraryScanResult = await unitOfWork.LibraryScanRepository.GetByIdAsync( + compositeId.ScanId.Value, shouldTrackEntities: false, cancellationToken: linkedSource.Token).ConfigureAwait(false); + if (getLibraryScanResult.IsFailure) + { + _logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description); + return; + } + + LibraryScanEntity? libraryScanEntity = getLibraryScanResult.Value; + // A scan that is not pending any more was cancelled or failed while it was waiting for its turn. + if (libraryScanEntity is null || libraryScanEntity.Status != LibraryScanJobStatus.Pending) + return; + + Result libraryScanDomainResult = libraryScanEntity.ToDomainEntity(); + if (libraryScanDomainResult.IsFailure) + { + await ReportScanFailureAsync(compositeId, LibraryId.Create(libraryScanEntity.LibraryId), new InvalidOperationException(libraryScanDomainResult.FirstError.Description), linkedSource.Token).ConfigureAwait(false); + return; + } + + libraryScan = libraryScanDomainResult.Value; + libraryType = libraryScanEntity.Library.LibraryType; + libraryId = libraryScan.LibraryId; + } + + IMediaLibraryScanDiscoveryJob rootJob; + // The job graph is prepared in its own short lived scope: the jobs create their own scopes for their persistence work. + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using (AsyncServiceScope prepareScope = _serviceScopeFactory.CreateAsyncScope()) + { + IMediaLibraryScanningService mediaLibraryScanningService = prepareScope.ServiceProvider.GetRequiredService(); + Result startScanResult = await mediaLibraryScanningService.StartScanAsync(libraryScan, libraryType, linkedSource.Token).ConfigureAwait(false); + if (startScanResult.IsFailure) + { + // The failure is reported for this scan only, so the scans that are queued behind it are still processed. + await ReportScanFailureAsync(compositeId, libraryScan.LibraryId, new InvalidOperationException(startScanResult.FirstError.Description), linkedSource.Token).ConfigureAwait(false); + return; + } + rootJob = startScanResult.Value; + } + + _logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value); + + // The file system discovery job is the only top level job of the scan job graph, and every job awaits its children, so awaiting it + // completes the entire scan. The next queued scan is only dequeued once this call returns. + await rootJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).ConfigureAwait(false); + + _logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value); + } + catch (OperationCanceledException) + { + // The scan was cancelled, or the application is shutting down, and the cancellation handler already reported it. Either way, the queue moves on. + } + catch (Exception exception) + { + // An unexpected preparation failure must still leave the scan failed instead of pending forever, and must not affect the scans queued behind it. + // The failure is reported without a cancellation token, because the scan token may already be cancelled and the report must still be published. + if (libraryId is null) + _logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value); + else + await ReportScanFailureAsync(compositeId, libraryId, exception, CancellationToken.None).ConfigureAwait(false); + } + } + + /// + /// Reports the failure of a single media library scan, without affecting the scans that are queued behind it. + /// + /// Model for tracking the failed media library scan. + /// The unique identifier of the library whose scan failed. + /// The exception that describes the failure. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task ReportScanFailureAsync(MediaLibraryScanCompositeId compositeId, LibraryId libraryId, Exception exception, CancellationToken cancellationToken) + { + _logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value); + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, libraryId, compositeId, exception, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs index f5875fdf..546e760f 100644 --- a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs @@ -18,9 +18,9 @@ namespace Lumina.Infrastructure.Core.Security; /// internal class FileHashService : IFileHashService { - private const int SAMPLE_COUNT = 6; // number of sample points for hash computation - private const ushort DEFAULT_BUFFER_SIZE = 65535; // buffer size (64KB - 1) for reading file chunks - private static readonly ThreadLocal s_threadLocalHasher = new(() => new XxHash64()); // thread-local hasher to avoid contention and pool management overhead during parallel processing + private const int SAMPLE_COUNT = 6; // Number of sample points for hash computation. + private const ushort DEFAULT_BUFFER_SIZE = 65535; // Buffer size (64KB - 1) for reading file chunks. + private static readonly ThreadLocal s_threadLocalHasher = new(() => new XxHash64()); // Thread-local hasher to avoid contention and pool management overhead during parallel processing. private static readonly ulong s_emptyFileHash = ComputeEmptyHash(); /// @@ -37,10 +37,11 @@ internal class FileHashService : IFileHashService object listLock = new(); // Solid state drives benefit from reading multiple files at once, while mechanical hard drives are faster with sequential reads because of their seek time. + // One logical processor is deliberately left out of the scan, so that the rest of the process, the web server included, keeps a processor available to it. ParallelOptions parallelOptions = new() { CancellationToken = cancellationToken, - MaxDegreeOfParallelism = shouldParallelizeReads ? Environment.ProcessorCount : 1 + MaxDegreeOfParallelism = shouldParallelizeReads ? Math.Max(1, Environment.ProcessorCount - 1) : 1 }; await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) => { 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 0aee819f..18dc00af 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 @@ -19,7 +19,7 @@ public class ScanLibrariesEndpointSummary : Summary } /// - /// Cancels the running scans of all the media libraries. + /// Cancels the running and queued scans of all the media libraries. /// /// The request object. /// Cancellation token that can be used to stop the execution. diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs index f5abed3d..fca43e41 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs @@ -19,7 +19,7 @@ public class CancelLibrariesScanEndpointSummary : Summary - /// Cancels a running scan of a media library. + /// Cancels a running or queued scan of a media library. /// /// The request containing the Ids of the media library and of the scan to cancel. /// Cancellation token that can be used to stop the execution. diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs index ec93be44..e8f6113b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -20,7 +20,7 @@ public class CancelLibraryScanEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose scan is cancelled. Required."); RequestParam(r => r.ScanId, "The Id of the scan to cancel. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs index a2f78a34..8a8be6f8 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs @@ -20,7 +20,7 @@ public class GetRunningLibraryScansEndpointSummary : Summary(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx index 763d270e..42b0c4e3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx @@ -141,6 +141,9 @@ إلغاء الفحص + + جارٍ الإلغاء + كتاب هزلي @@ -249,6 +252,9 @@ برنامج إذاعي + + في قائمة الانتظار + ريمكس diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx index b8da7f60..694f31d8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx @@ -141,6 +141,9 @@ Scan Abbrechen + + Wird abgebrochen + Comic-Heft @@ -249,6 +252,9 @@ Radiosendung + + In Warteschlange + Neuabmischung diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx index d108cf96..e652782c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx @@ -141,6 +141,9 @@ Cancel Scan + + Cancelling + Comic Book @@ -249,6 +252,9 @@ Radio Show + + Queued + Remix diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx index fec23bfe..55f6de34 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx @@ -141,6 +141,9 @@ Cancelar Escaneo + + Cancelando + Cómic @@ -249,6 +252,9 @@ Programa de Radio + + En cola + Remezcla diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx index 9d8650d5..f5215ddc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx @@ -141,6 +141,9 @@ Annuler Le Scan + + Annulation en cours + Bande Dessinée @@ -249,6 +252,9 @@ Émission Radio + + En file d'attente + Remixage diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx index 1e8e8fb1..43f3b321 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx @@ -141,6 +141,9 @@ Annulla Scansione + + Annullamento in corso + Fumetto @@ -249,6 +252,9 @@ Programma Radiofonico + + In coda + Remissaggio diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx index 82f9c3c6..26227f23 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx @@ -141,6 +141,9 @@ スキャンを中止 + + キャンセル中 + 漫画 @@ -249,6 +252,9 @@ ラジオ番組 + + 待機中 + リミックス diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx index d108cf96..e652782c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx @@ -141,6 +141,9 @@ Cancel Scan + + Cancelling + Comic Book @@ -249,6 +252,9 @@ Radio Show + + Queued + Remix diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx index 7c108058..ef76d5d9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx @@ -141,6 +141,9 @@ Anulează Scanarea + + Se anulează + Bandă Desenată @@ -249,6 +252,9 @@ Emisiune Radio + + În așteptare + Remix diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx index 03dcaa9e..b2d90602 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx @@ -141,6 +141,9 @@ Скасувати Сканування + + Скасування + Комікс @@ -249,6 +252,9 @@ Радіопередача + + У черзі + Ремікс diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx index 1e58d782..38bcd895 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx @@ -141,6 +141,9 @@ 取消扫描 + + 正在取消 + 漫画 @@ -249,6 +252,9 @@ 广播节目 + + 排队中 + 混音版 diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index 346c629e..e312d8cc 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -168,7 +168,8 @@ const jsLocalizedLibraryScanStatuses = { Completed: '@_localizer["Completed"]', Failed: '@_localizer["Failed"]', - Canceled: '@_localizer["Canceled"]' + Canceled: '@_localizer["Canceled"]', + Cancelling: '@_localizer["Cancelling"]' }; const jsLocalizedLibraryScanJobsStatuses = { DiscoveringFiles: '@_localizer["DiscoveringFiles"]', @@ -178,7 +179,8 @@ SavingScanData: '@_localizer["SavingScanData"]', InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]', EnrichingMetadata: '@_localizer["EnrichingMetadata"]', - ResolvingArtwork: '@_localizer["ResolvingArtwork"]' + ResolvingArtwork: '@_localizer["ResolvingArtwork"]', + Queued: '@_localizer["Queued"]' }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]', @@ -307,12 +309,17 @@ row.setAttribute('data-scan-id', scan.scanId); - statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[scan.currentJobProgress.currentOperation]; + // A queued scan has no progress to show yet, so only its waiting state is displayed. + const currentOperation = scan.currentJobProgress.currentOperation; + const isQueued = currentOperation === 'Queued'; + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[currentOperation] ?? currentOperation; statusSpan.classList.remove('hidden'); - scanProgress.classList.remove('hidden'); - totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`; - jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`; + scanProgress.classList.toggle('hidden', isQueued); + if (!isQueued) { + totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`; + jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`; + } scanIcon.classList.add('hidden'); cancelScanIcon.classList.remove('hidden'); @@ -369,6 +376,12 @@ scanIcon.classList.add('hidden'); cancelScanIcon.classList.remove('hidden'); + // The scan is queued until its turn comes, so it has no progress to show yet. + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses['Queued']; + statusSpan.classList.remove('hidden'); + row.querySelector('.scan-progress').classList.add('hidden'); + const scanId = scan.scanId; await signalRConnection.invoke('SubscribeToScan', scanId); } @@ -401,6 +414,12 @@ scanIcon.classList.add('hidden'); cancelScanIcon.classList.remove('hidden'); + // The scan is queued until its turn comes, so it has no progress to show yet. + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses['Queued']; + statusSpan.classList.remove('hidden'); + row.querySelector('.scan-progress').classList.add('hidden'); + const scanId = success.scanId; await signalRConnection.invoke('SubscribeToScan', scanId); } @@ -410,29 +429,20 @@ // On cancel all libraries scan button click. const handleCancelLibrariesScanClick = async function(e) { await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARIES_SCAN)', {}); - btnCancelLibrariesScan.style.display = 'none'; - btnScanAllLibraries.style.display = 'block'; - // Toggle icons for all active scan rows. + // The cancellations are only applied once the server confirms each one, so the cancel button stays hidden meanwhile. + btnCancelLibrariesScan.style.display = 'none'; + + // Ask all active scan rows to show that their cancellation is in progress. const rows = document.querySelectorAll('tr[data-scan-id]'); rows.forEach(row => { - // Remove the scan Id, its no longer being scanned. - row.removeAttribute('data-scan-id'); - const statusSpan = row.querySelector('.scan-job-status'); - statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`; - const scanProgress = row.querySelector('.scan-progress'); - scanProgress.classList.add('hidden'); - - // Show scan status icon. - const completedIdon = row.querySelector('img[src*="yellow.png"]'); - completedIdon.classList.remove('hidden'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`; + statusSpan.classList.remove('hidden'); // Toggle scan action icons. - const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); - scanIcon.classList.remove('hidden'); cancelScanIcon.classList.add('hidden'); }); }; @@ -441,6 +451,7 @@ const handleCancelLibraryScanClick = async function(e) { if (e.target.matches('img[src*="stop.svg"]')) { const row = e.target.closest('tr'); + const scanId = row.getAttribute('data-scan-id'); const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARY_SCAN, new { libraryId = default(Guid), scanId = default(Guid) })'; @@ -460,29 +471,18 @@ ).join('/'); await callApiPostAsync(finalUrl); - - // Remove the scan Id, its no longer being scanned. - row.removeAttribute('data-scan-id'); - const statusSpan = row.querySelector('.scan-job-status'); - statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`; - const scanProgress = row.querySelector('.scan-progress'); - scanProgress.classList.add('hidden'); + // The cancellation is only applied once the server confirms it, so the scan keeps its Id and is shown as being cancelled meanwhile. + // The server might have confirmed it already, in which case the row no longer carries the Id and is left as it is. + if (row.getAttribute('data-scan-id') === scanId) { + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`; + statusSpan.classList.remove('hidden'); - // Show scan status icon. - const completedIdon = row.querySelector('img[src*="yellow.png"]'); - completedIdon.classList.remove('hidden'); - - // Toggle scan action icons. - const scanIcon = row.querySelector('img[src*="trigger.svg"]'); - const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); - scanIcon.classList.remove('hidden'); - cancelScanIcon.classList.add('hidden'); - - // Toggle scan action buttons. - const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0; - btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none'; - btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; + // Toggle scan action icons. + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + cancelScanIcon.classList.add('hidden'); + } } }; @@ -502,17 +502,21 @@ const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`); rows.forEach(row => { // Update status text. + const currentOperation = progress.currentJobProgress.currentOperation; + const isQueued = currentOperation === 'Queued'; const statusSpan = row.querySelector('.scan-job-status'); - statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[progress.currentJobProgress.currentOperation]; + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[currentOperation] ?? currentOperation; statusSpan.classList.remove('hidden'); - // Update progress bars. + // Update progress bars. A queued scan has no progress to show yet. const scanProgress = row.querySelector('.scan-progress'); const totalProgressDiv = row.querySelector('.scan-progress-total > div'); const jobProgressDiv = row.querySelector('.scan-progress-job > div'); - scanProgress.classList.remove('hidden'); - totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`; - jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`; + scanProgress.classList.toggle('hidden', isQueued); + if (!isQueued) { + totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`; + jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`; + } // Toggle scan action icons. const scanIcon = row.querySelector('img[src*="trigger.svg"]'); @@ -576,10 +580,38 @@ btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; }; + // Scan cancellation handler. + const cancelledHandler = (progress) => { + const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`); + rows.forEach(row => { + // Remove the scan Id, its no longer being scanned. + row.removeAttribute('data-scan-id'); + + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses[progress.status]}.`; + const scanProgress = row.querySelector('.scan-progress'); + scanProgress.classList.add('hidden'); + + // Show scan status icon. + const canceledIdon = row.querySelector('img[src*="yellow.png"]'); + canceledIdon.classList.remove('hidden'); + + // Toggle scan action icons. + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + scanIcon.classList.remove('hidden'); + cancelScanIcon.classList.add('hidden'); + }); + const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0; + btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none'; + btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; + }; + // Subscribe to events. signalRConnection.on("libraryScanProgressUpdateEvent", progressHandler); signalRConnection.on("libraryScanFinishedEvent", completionHandler); signalRConnection.on("libraryScanFailedEvent", failureHandler); + signalRConnection.on("libraryScanCancelledEvent", cancelledHandler); signalRConnection.onclose(onClose); signalRConnection.onreconnecting(onReconnecting); signalRConnection.onreconnected(onReconnected); @@ -588,6 +620,7 @@ signalRConnection.off("libraryScanProgressUpdateEvent", progressHandler); signalRConnection.off("libraryScanFinishedEvent", completionHandler); signalRConnection.off("libraryScanFailedEvent", failureHandler); + signalRConnection.off("libraryScanCancelledEvent", cancelledHandler); signalRConnection.off("close", onClose); signalRConnection.off("reconnecting", onReconnecting); signalRConnection.off("reconnected", onReconnected); diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventFixture.cs index 8e729533..df661149 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventFixture.cs @@ -2,8 +2,10 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -17,6 +19,7 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedCo public class LibraryScanQueuedDomainEventFixture { private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); /// @@ -24,18 +27,21 @@ public class LibraryScanQueuedDomainEventFixture /// /// Optional. The Id of the domain event. /// Optional. The unique identifier of the queued media library scan. + /// Optional. The unique identifier of the user that initiated the queued media library scan. /// Optional. The unique identifier of the library whose scan was queued. /// Optional. The date and time when the domain event occurred. /// The created . public LibraryScanQueuedDomainEvent Create( Guid? id = null, ScanId? scanId = null, + UserId? userId = null, LibraryId? libraryId = null, DateTime? occurredOnUtc = null) { return new LibraryScanQueuedDomainEvent( id ?? Guid.NewGuid(), scanId ?? _scanIdFixture.Create(), + userId ?? _userIdFixture.Create(), libraryId ?? _libraryIdFixture.Create(), occurredOnUtc ?? DateTime.UtcNow); } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/FakeMediaLibraryScanDiscoveryJob.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/FakeMediaLibraryScanDiscoveryJob.cs new file mode 100644 index 00000000..cc3e500b --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/FakeMediaLibraryScanDiscoveryJob.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Controllable test double for the interface. +/// +[ExcludeFromCodeCoverage] +public sealed class FakeMediaLibraryScanDiscoveryJob : IMediaLibraryScanDiscoveryJob +{ + private readonly TaskCompletionSource _executionStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _executionCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// + /// Gets or sets the Id of the media library scan that this job is part of. + /// + public required ScanId ScanId { get; set; } + + /// + /// Gets or sets the Id of the user that initiated the media library scan that this job is part of. + /// + public required UserId UserId { get; set; } + + /// + /// Gets or sets the unique identifier of the media library upon which the scan is performed. + /// + public required LibraryId LibraryId { get; set; } + + /// + /// Gets the list of child media scan jobs that will be triggered when this job's payload completes execution. + /// + public List Children { get; } = []; + + /// + /// Gets the list of parent media scan jobs that will trigger this job when their payload will complete execution. + /// + public List Parents { get; } = []; + + /// + /// Gets the status of the current media library scan job. + /// + public LibraryScanJobStatus Status { get; private set; } = LibraryScanJobStatus.Pending; + + /// + /// Gets the number of times this job was executed. + /// + public int ExecutionCount { get; private set; } + + /// + /// Gets a value indicating whether this job is currently executing. + /// + public bool IsExecuting { get; private set; } + + /// + /// Gets the Id this job was last executed with. + /// + public Guid? LastExecutionId { get; private set; } + + /// + /// Gets the cancellation token this job was last executed with. + /// + public CancellationToken LastCancellationToken { get; private set; } + + /// + /// Gets or sets the optional callback invoked while the job executes, allowing a test to block or throw. + /// + public Func? OnExecute { get; set; } + + /// + /// Gets a task that completes as soon as the job starts executing. + /// + public Task ExecutionStarted => _executionStarted.Task; + + /// + /// Gets a task that completes as soon as the job finishes executing successfully. + /// + public Task ExecutionCompleted => _executionCompleted.Task; + + /// + /// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution. + /// + /// The child media library scan job to be added. + public void AddChild(IMediaLibraryScanJob job) + { + if (!Children.Contains(job) && !Parents.Contains(job)) + Children.Add(job); + } + + /// + /// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution. + /// + /// The child media library scan job to be added. + public void AddParent(IMediaLibraryScanJob job) + { + if (!Parents.Contains(job) && !Children.Contains(job)) + Parents.Add(job); + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The id of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + ExecutionCount++; + LastExecutionId = id; + LastCancellationToken = cancellationToken; + IsExecuting = true; + Status = LibraryScanJobStatus.Running; + _executionStarted.TrySetResult(); + + if (OnExecute is not null) + await OnExecute(cancellationToken).ConfigureAwait(false); + + Status = LibraryScanJobStatus.Completed; + IsExecuting = false; + _executionCompleted.TrySetResult(); + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanDiscoveryJobFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanDiscoveryJobFixture.cs new file mode 100644 index 00000000..1e65df58 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanDiscoveryJobFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Fixture class for the interface. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanDiscoveryJobFixture +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + /// + /// Creates a controllable . + /// + /// Optional. The Id of the media library scan that the job is part of. + /// Optional. The Id of the user that initiated the media library scan. + /// Optional. The Id of the media library that is scanned. + /// Optional. The child jobs of the created job. + /// Optional. The callback invoked while the job executes. + /// The created . + public FakeMediaLibraryScanDiscoveryJob Create( + ScanId? scanId = null, + UserId? userId = null, + LibraryId? libraryId = null, + List? children = null, + Func? onExecute = null) + { + FakeMediaLibraryScanDiscoveryJob job = new() + { + ScanId = scanId ?? _scanIdFixture.Create(), + UserId = userId ?? _userIdFixture.Create(), + LibraryId = libraryId ?? _libraryIdFixture.Create(), + OnExecute = onExecute + }; + + foreach (IMediaLibraryScanJob child in children ?? []) + job.AddChild(child); + + return job; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs index a665f741..a53c45b8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs @@ -52,7 +52,7 @@ public class CancelLibrariesScanCommandHandlerTests _mockDomainEventsQueue = Substitute.For(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated and is an admin + // Default stubs: the current user is authenticated and is an admin. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -62,15 +62,15 @@ public class CancelLibrariesScanCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllRunningScans() + public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllActiveScans() { // Arrange - List runningScans = + List activeScans = [ _libraryScanEntityFixture.Create(userId: _userId), _libraryScanEntityFixture.Create(userId: _userId) ]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); // Act Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); @@ -83,17 +83,36 @@ public class CancelLibrariesScanCommandHandlerTests _mockDomainEventsQueue.Received(2).Enqueue(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenAnActiveScanIsPending_ShouldCancelItToo() + { + // Arrange + // A scan that is still waiting in the scan queue is an active scan, so cancelling all scans must cancel it as well. + List activeScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Pending)]; + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); + + // Act + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryScanRepository.Received(1).UpdateAsync( + Arg.Is(libraryScan => libraryScan.Status == LibraryScanJobStatus.Canceled), + Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent.ScanId.Value == activeScans[0].Id)); + } + [Fact] public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyCancelScansOwnedByTheUser() { // Arrange Guid otherUserId = Guid.NewGuid(); - List runningScans = + List activeScans = [ _libraryScanEntityFixture.Create(userId: _userId), _libraryScanEntityFixture.Create(userId: otherUserId) ]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act @@ -117,16 +136,16 @@ public class CancelLibrariesScanCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetRunningScansAsync(Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetActiveScansAsync(Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError() + public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError() { // Arrange - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()) - .Returns(Error.Failure(description: "Failed to get running scans")); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get active scans")); // Act Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); @@ -141,8 +160,8 @@ public class CancelLibrariesScanCommandHandlerTests public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() { // Arrange - List runningScans = [_libraryScanEntityFixture.Create(userId: _userId)]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + List activeScans = [_libraryScanEntityFixture.Create(userId: _userId)]; + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to update library scan")); @@ -155,18 +174,18 @@ public class CancelLibrariesScanCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError() + public async Task HandleAsync_WhenScanIsInATerminalState_ShouldReturnError() { // Arrange - List runningScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + List activeScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)]; + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); // Act Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError); await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs index d8b40e6d..777da9be 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs @@ -58,7 +58,7 @@ public class CancelLibraryScanCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated and the ownership policy allows the cancellation + // Default stubs: the current user is authenticated and the ownership policy allows the cancellation. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); @@ -89,6 +89,28 @@ public class CancelLibraryScanCommandHandlerTests _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenPendingScanExists_ShouldCancelScanAndReturnSuccess() + { + // Arrange + // A scan that is still waiting in the scan queue can be cancelled as well. + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId, status: LibraryScanJobStatus.Pending); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) + .Returns(Result.From(pendingScan)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryScanRepository.Received(1).UpdateAsync( + Arg.Is(libraryScan => libraryScan.Status == LibraryScanJobStatus.Canceled), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenScanDoesNotExist_ShouldReturnNotFoundError() { @@ -163,7 +185,7 @@ public class CancelLibraryScanCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError() + public async Task HandleAsync_WhenScanIsInATerminalState_ShouldReturnError() { // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); @@ -176,7 +198,7 @@ public class CancelLibraryScanCommandHandlerTests // Assert Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + Assert.Equal(DomainErrors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError); await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs index d07d80b8..495f5490 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -10,7 +11,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using DomainErrors = Lumina.Domain.Common.Errors.Errors; @@ -35,7 +35,7 @@ public class LibraryScanCancelledDomainEventHandlerTests private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository; private readonly ILibraryScanSnapshotRepository _mockLibraryScanSnapshotRepository; private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService; - private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibraryScanProgressNotifier _mockMediaLibraryScanProgressNotifier; private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker; private readonly LibraryScanCancelledDomainEventHandler _sut; private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); @@ -55,17 +55,19 @@ public class LibraryScanCancelledDomainEventHandlerTests _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository); _mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockLibraryScanSnapshotRepository); _mockMediaLibraryScanningService = Substitute.For(); - _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockMediaLibraryScanProgressNotifier = Substitute.For(); _mockMediaLibrariesScanCancellationTracker = Substitute.For(); - // default stubs: the cancellation service, the snapshot rollback and the staging results clearing succeed + // Default stubs: the cancellation service, the client notification, the snapshot rollback and the staging results clearing succeed. _mockMediaLibraryScanningService.CancelScan(Arg.Any()).Returns(Result.Success); + _mockMediaLibraryScanProgressNotifier.SendLibraryScanCancelledEventAsync(Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); _mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Deleted); _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) .Returns(Result.Success); - _sut = new LibraryScanCancelledDomainEventHandler(_mockMediaLibraryScanningService, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibrariesScanProgressTracker, _mockUnitOfWork); + _sut = new LibraryScanCancelledDomainEventHandler(_mockMediaLibraryScanningService, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibraryScanProgressNotifier, _mockUnitOfWork); } [Fact] @@ -84,12 +86,46 @@ public class LibraryScanCancelledDomainEventHandlerTests // Assert _mockMediaLibraryScanningService.Received(1).CancelScan(Arg.Is(libraryScan => libraryScan.Id.Value == scan.Id)); - _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(Arg.Any()); - _mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(Arg.Any()); + await _mockMediaLibraryScanProgressNotifier.Received(1).SendLibraryScanCancelledEventAsync( + Arg.Is(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId.Value == scan.UserId), + Arg.Any()); + _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan( + Arg.Is(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId.Value == scan.UserId)); await _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, domainEvent.ScanId.Value, CancellationToken.None); await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None); } + [Fact] + public async Task HandleAsync_WhenScanExists_ShouldNotifyClientsBeforeReleasingTheScanResources() + { + // Arrange + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(scan)); + List cleanupSteps = []; + _mockMediaLibraryScanProgressNotifier + .When(notifier => notifier.SendLibraryScanCancelledEventAsync(Arg.Any(), Arg.Any())) + .Do(_ => cleanupSteps.Add("notifyClients")); + _mockMediaLibrariesScanCancellationTracker + .When(tracker => tracker.RemoveScan(Arg.Any())) + .Do(_ => cleanupSteps.Add("removeCancellationToken")); + _mockLibraryScanSnapshotRepository + .When(repository => repository.RollbackSnapshotForScanAsync(Arg.Any(), Arg.Any(), Arg.Any())) + .Do(_ => cleanupSteps.Add("rollbackSnapshot")); + _mockLibraryScanStagingResultsRepository + .When(repository => repository.ClearForScanAsync(Arg.Any(), Arg.Any())) + .Do(_ => cleanupSteps.Add("clearStagingResults")); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + Assert.Equal(["notifyClients", "removeCancellationToken", "rollbackSnapshot", "clearStagingResults"], cleanupSteps); + } + [Fact] public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() { @@ -105,6 +141,7 @@ public class LibraryScanCancelledDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); + await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any(), Arg.Any()); await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); } @@ -123,6 +160,7 @@ public class LibraryScanCancelledDomainEventHandlerTests // Assert Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); + await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any(), Arg.Any()); await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); } @@ -145,6 +183,7 @@ public class LibraryScanCancelledDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); + await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any(), Arg.Any()); _mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any()); await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs index 409bfbf3..f8ee9645 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -1,24 +1,18 @@ #region ========================================================================= USING ===================================================================================== -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.Core.MediaLibrary.Management.Events; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Domain.Common.Events; -using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +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.Services.Queue; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; +using System.Threading.Channels; using System.Threading.Tasks; -using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; @@ -29,109 +23,90 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; [ExcludeFromCodeCoverage] public class LibraryScanQueuedDomainEventHandlerTests { - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryScanRepository _mockLibraryScanRepository; - private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService; - private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IMediaLibrariesScanQueue _mockScanQueue; + private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker; private readonly LibraryScanQueuedDomainEventHandler _sut; - private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new(); + private readonly Channel _channel; /// /// Initializes a new instance of the class. /// public LibraryScanQueuedDomainEventHandlerTests() { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockLibraryScanRepository = Substitute.For(); - _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); - _mockMediaLibraryScanningService = Substitute.For(); - _mockDomainEventsQueue = Substitute.For(); + _channel = Channel.CreateUnbounded(); + _mockScanQueue = Substitute.For(); + _mockScanQueue.Writer.Returns(_channel.Writer); + _mockScanQueue.Reader.Returns(_channel.Reader); + _mockCancellationTracker = Substitute.For(); + _mockProgressTracker = Substitute.For(); - // default stubs: the scanning service starts the scan successfully - _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Success); + // Default stubs: the queued scan progress is initialized successfully. + _mockProgressTracker.InitializeQueuedScanProgress(Arg.Any(), Arg.Any()) + .Returns(Result.Created); - _sut = new LibraryScanQueuedDomainEventHandler(_mockMediaLibraryScanningService, _mockDomainEventsQueue, _mockUnitOfWork); + _sut = new LibraryScanQueuedDomainEventHandler(_mockScanQueue, _mockCancellationTracker, _mockProgressTracker); } [Fact] - public async Task HandleAsync_WhenScanExists_ShouldStartTheScan() + public async Task HandleAsync_WhenCalled_ShouldRegisterTheScanForCancellation() { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - LibraryScanEntity scan = _libraryScanEntityFixture.Create( - id: domainEvent.ScanId.Value, - libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) - .Returns(Result.From(scan)); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - await _mockMediaLibraryScanningService.Received(1).StartScanAsync( - Arg.Is(libraryScan => libraryScan.Id.Value == scan.Id), - scan.Library.LibraryType, - Arg.Any()); + _mockCancellationTracker.Received(1).RegisterScan( + Arg.Is(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId == domainEvent.UserId)); } [Fact] - public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() + public async Task HandleAsync_WhenCalled_ShouldInitializeTheQueuedScanProgress() { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) - .Returns(error); // Act - EventualConsistencyException exception = await Assert.ThrowsAsync( - () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal(error, exception.EventualConsistencyError); - await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); + _mockProgressTracker.Received(1).InitializeQueuedScanProgress( + domainEvent.LibraryId, + Arg.Is(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId == domainEvent.UserId)); } [Fact] - public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() + public async Task HandleAsync_WhenCalled_ShouldWriteTheCompositeScanIdToTheQueue() { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) - .Returns(Result.Success(null)); // Act - EventualConsistencyException exception = await Assert.ThrowsAsync( - () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); - await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); + Assert.True(_channel.Reader.TryRead(out MediaLibraryScanCompositeId? enqueuedScanId)); + Assert.Equal(domainEvent.ScanId, enqueuedScanId!.ScanId); + Assert.Equal(domainEvent.UserId, enqueuedScanId.UserId); + Assert.False(_channel.Reader.TryRead(out _)); } [Fact] - public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException() + public async Task HandleAsync_WhenCalled_ShouldNotStartProcessingTheScan() { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - LibraryScanEntity scan = _libraryScanEntityFixture.Create( - id: domainEvent.ScanId.Value, - libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) - .Returns(Result.From(scan)); - Error error = Error.Failure(description: "Failed to start scan"); - _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(error); // Act - EventualConsistencyException exception = await Assert.ThrowsAsync( - () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal(error, exception.EventualConsistencyError); - _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + // Queuing a scan only registers it and reports it as waiting: the scan processor prepares and starts it later, one scan at a time. + _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); + _mockProgressTracker.DidNotReceive().UpdateScanProgress(Arg.Any(), Arg.Any()); + _mockProgressTracker.DidNotReceive().UpdateScanJobProgress(Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs index dd128719..f819c5a0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs @@ -10,6 +10,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -58,7 +59,7 @@ public class GetRunningLibraryScansQueryHandlerTests _mockMediaLibrariesScanProgressTracker = Substitute.For(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, is an admin, and every scan has progress + // Default stubs: the current user is authenticated, is an admin, and every scan has progress. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) @@ -72,15 +73,15 @@ public class GetRunningLibraryScansQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllRunningScans() + public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllActiveScans() { // Arrange - List runningScans = + List activeScans = [ _libraryScanEntityFixture.Create(userId: _userId), _libraryScanEntityFixture.Create(userId: Guid.NewGuid()) ]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); // Act Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); @@ -94,12 +95,12 @@ public class GetRunningLibraryScansQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnProgressOnlyForScansOwnedByTheUser() { // Arrange - List runningScans = + List activeScans = [ _libraryScanEntityFixture.Create(userId: _userId), _libraryScanEntityFixture.Create(userId: Guid.NewGuid()) ]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act @@ -110,6 +111,32 @@ public class GetRunningLibraryScansQueryHandlerTests Assert.Single(result.Value); } + [Fact] + public async Task HandleAsync_WhenActiveScanIsPending_ShouldReturnItsQueuedProgress() + { + // Arrange + LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Pending); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()) + .Returns(Result.From>([pendingScan])); + _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) + .Returns(Result.From(_mediaLibraryScanProgressFixture.Create( + scanId: ScanId.Create(pendingScan.Id), + userId: _userIdFixture.Create(value: _userId), + libraryId: LibraryId.Create(pendingScan.LibraryId), + completedJobs: 0, + totalJobs: 0, + status: LibraryScanJobStatus.Pending))); + + // Act + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + MediaLibraryScanProgressResponse response = Assert.Single(result.Value); + Assert.Equal(pendingScan.Id, response.ScanId); + Assert.Equal(LibraryScanJobStatus.Pending.ToString(), response.Status); + } + [Fact] public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() { @@ -122,15 +149,15 @@ public class GetRunningLibraryScansQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetRunningScansAsync(Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetActiveScansAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError() + public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError() { // Arrange - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()) - .Returns(Error.Failure(description: "Failed to get running scans")); + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get active scans")); // Act Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); @@ -140,18 +167,29 @@ public class GetRunningLibraryScansQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenGettingScanProgressFails_ShouldReturnError() + public async Task HandleAsync_WhenAnActiveScanHasNoProgress_ShouldSkipThatScan() { // Arrange - List runningScans = [_libraryScanEntityFixture.Create(userId: _userId)]; - _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + List activeScans = + [ + _libraryScanEntityFixture.Create(userId: _userId), + _libraryScanEntityFixture.Create(userId: _userId) + ]; + _mockLibraryScanRepository.GetActiveScansAsync(Arg.Any()).Returns(Result.From>(activeScans)); + // A scan whose progress was already released has ended, so it is not reported as active any more, without failing the whole query. + MediaLibraryScanProgress releasedProgress = _mediaLibraryScanProgressFixture.Create( + userId: _userIdFixture.Create(value: _userId), + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running); _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) - .Returns(Error.Failure(description: "Failed to get scan progress")); + .Returns(Result.From(releasedProgress), Error.Failure(description: "The scan progress was already released")); // Act Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert - Assert.True(result.IsFailure); + Assert.False(result.IsFailure); + Assert.Single(result.Value); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs index 9fede070..809a2185 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -123,22 +123,25 @@ public class LibraryScanRepositoryTests } [Fact] - public async Task GetRunningScansAsync_WhenCalled_ShouldReturnOnlyRunningScans() + public async Task GetActiveScansAsync_WhenCalled_ShouldReturnPendingAndRunningScansOnly() { // Arrange LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running); - LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed); LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending); - _mockContext.LibraryScans.AddRange(runningScan, completedScan, pendingScan); + LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed); + LibraryScanEntity canceledScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Canceled); + LibraryScanEntity failedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed); + _mockContext.LibraryScans.AddRange(runningScan, pendingScan, completedScan, canceledScan, failedScan); await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetRunningScansAsync(CancellationToken.None); + Result> result = await _sut.GetActiveScansAsync(CancellationToken.None); // Assert Assert.False(result.IsFailure); - LibraryScanEntity retrievedScan = Assert.Single(result.Value); - Assert.Equal(runningScan.Id, retrievedScan.Id); + Assert.Equal(2, result.Value.Count()); + Assert.Contains(result.Value, libraryScan => libraryScan.Id == runningScan.Id); + Assert.Contains(result.Value, libraryScan => libraryScan.Id == pendingScan.Id); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 91c15e08..702123cc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -18,12 +18,12 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(16, typeof(DomainErrors.LibraryScanning).GetProperties().Length); + Assert.Equal(17, typeof(DomainErrors.LibraryScanning).GetProperties().Length); AssertError(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.LibraryScanning.CanOnlyStartPendingScans, ErrorType.Forbidden); AssertError(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, ErrorType.Forbidden); - AssertError(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, ErrorType.Forbidden); - AssertError(DomainErrors.LibraryScanning.CanOnlyFailRunningScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.CanOnlyFailPendingOrRunningScans, ErrorType.Forbidden); AssertError(DomainErrors.LibraryScanning.ScanIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.LibraryScanning.LibraryScanAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, ErrorType.Forbidden); @@ -35,6 +35,7 @@ public class ErrorsTests AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, ErrorType.Validation); AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, ErrorType.Validation); AssertError(DomainErrors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.NoScannerForLibraryType, ErrorType.Unexpected); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs index 2ad9ebb3..2bcd32d2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs @@ -11,7 +11,6 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -55,11 +54,11 @@ public class MusicLibraryTypeScannerTests MusicLibraryTypeScanner sut = new(_mockJobFactory); // Act - List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)]; + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); // Assert - IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); Assert.Same(discoveryJob, rootJob); + Assert.IsAssignableFrom(rootJob); Assert.Contains(diffJob, discoveryJob.Children); Assert.Contains(discoveryJob, diffJob.Parents); Assert.Contains(hashJob, diffJob.Children); @@ -79,6 +78,61 @@ public class MusicLibraryTypeScannerTests _mockJobFactory.Received(1).CreateJob(libraryId); } + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldReturnTheFileSystemDiscoveryJobAsTheOnlyRoot() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); + + // Assert + Assert.Same(discoveryJob, rootJob); + // The file system discovery job is the only top level job, so nothing else is reachable without it. + Assert.Empty(discoveryJob.Parents); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldMakeTheWholeChainReachableFromTheRoot() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + TestScanJob diffJob = CreateJob(); + TestScanJob hashJob = CreateJob(); + TestScanJob metadataExtractionJob = CreateJob(); + TestScanJob saveJob = CreateJob(); + TestScanJob invalidationJob = CreateJob(); + TestScanJob enrichmentJob = CreateJob(); + TestScanJob artworkEnrichmentJob = CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); + HashSet reachableJobs = GetReachableJobs(rootJob); + + // Assert + Assert.Equal(8, reachableJobs.Count); + Assert.Contains(discoveryJob, reachableJobs); + Assert.Contains(diffJob, reachableJobs); + Assert.Contains(hashJob, reachableJobs); + Assert.Contains(metadataExtractionJob, reachableJobs); + Assert.Contains(saveJob, reachableJobs); + Assert.Contains(invalidationJob, reachableJobs); + Assert.Contains(enrichmentJob, reachableJobs); + Assert.Contains(artworkEnrichmentJob, reachableJobs); + } + [Fact] public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary() { @@ -95,7 +149,7 @@ public class MusicLibraryTypeScannerTests MusicLibraryTypeScanner sut = new(_mockJobFactory); // Act - _ = sut.CreateScanJobsForLibrary(libraryId).ToList(); + _ = sut.CreateScanJobsForLibrary(libraryId); // Assert _mockJobFactory.Received(1).CreateJob(libraryId); @@ -108,6 +162,27 @@ public class MusicLibraryTypeScannerTests _mockJobFactory.Received(1).CreateJob(libraryId); } + /// + /// Collects every job that is reachable from through the child relationships. + /// + /// The root job of the job graph. + /// The set of reachable jobs. + private static HashSet GetReachableJobs(IMediaLibraryScanJob rootJob) + { + HashSet reachableJobs = []; + Queue jobsToVisit = new(); + jobsToVisit.Enqueue(rootJob); + while (jobsToVisit.Count > 0) + { + IMediaLibraryScanJob currentJob = jobsToVisit.Dequeue(); + if (!reachableJobs.Add(currentJob)) + continue; + foreach (IMediaLibraryScanJob childJob in currentJob.Children) + jobsToVisit.Enqueue(childJob); + } + return reachableJobs; + } + private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob { TestScanJob job = new() diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs index 14029bae..84717788 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs @@ -3,9 +3,11 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -19,6 +21,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC public class LibraryScanQueuedDomainEventTests { private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new(); @@ -28,15 +31,17 @@ public class LibraryScanQueuedDomainEventTests // Arrange Guid id = Guid.NewGuid(); ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); LibraryId libraryId = _libraryIdFixture.Create(); DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, userId, libraryId, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); Assert.Equal(scanId, domainEvent.ScanId); + Assert.Equal(userId, domainEvent.UserId); Assert.Equal(libraryId, domainEvent.LibraryId); Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); Assert.IsType(domainEvent, exactMatch: false); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs index 4c4eadb2..7442dc68 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs @@ -96,6 +96,7 @@ public class LibraryScanTests Assert.Equal(LibraryScanJobStatus.Pending, scan.Status); LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType(Assert.Single(scan.GetDomainEvents())); Assert.Equal(scan.Id, queuedEvent.ScanId); + Assert.Equal(scan.UserId, queuedEvent.UserId); Assert.Equal(scan.LibraryId, queuedEvent.LibraryId); } @@ -149,10 +150,10 @@ public class LibraryScanTests } [Theory] - [InlineData(LibraryScanJobStatus.Running)] // cannot start an already running scan - [InlineData(LibraryScanJobStatus.Completed)] // cannot start a completed scan - [InlineData(LibraryScanJobStatus.Canceled)] // cannot start a canceled scan - [InlineData(LibraryScanJobStatus.Failed)] // cannot start a failed scan + [InlineData(LibraryScanJobStatus.Running)] // Cannot start an already running scan. + [InlineData(LibraryScanJobStatus.Completed)] // Cannot start a completed scan. + [InlineData(LibraryScanJobStatus.Canceled)] // Cannot start a canceled scan. + [InlineData(LibraryScanJobStatus.Failed)] // Cannot start a failed scan. public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status) { // Arrange @@ -200,10 +201,10 @@ public class LibraryScanTests } [Theory] - [InlineData(LibraryScanJobStatus.Pending)] // cannot complete a pending scan - [InlineData(LibraryScanJobStatus.Completed)] // cannot complete an already completed scan - [InlineData(LibraryScanJobStatus.Canceled)] // cannot complete a canceled scan - [InlineData(LibraryScanJobStatus.Failed)] // cannot complete a failed scan + [InlineData(LibraryScanJobStatus.Pending)] // Cannot complete a pending scan. + [InlineData(LibraryScanJobStatus.Completed)] // Cannot complete an already completed scan. + [InlineData(LibraryScanJobStatus.Canceled)] // Cannot complete a canceled scan. + [InlineData(LibraryScanJobStatus.Failed)] // Cannot complete a failed scan. public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) { // Arrange @@ -218,11 +219,13 @@ public class LibraryScanTests Assert.Equal(status, scan.Status); } - [Fact] - public void CancelScan_WhenRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent() + [Theory] + [InlineData(LibraryScanJobStatus.Pending)] // A scan waiting in the scan queue can be canceled too. + [InlineData(LibraryScanJobStatus.Running)] // A scan that is already executing can be canceled. + public void CancelScan_WhenPendingOrRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent(LibraryScanJobStatus status) { // Arrange - LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScan scan = _libraryScanFixture.Create(status: status); // Act Result result = scan.CancelScan(); @@ -237,11 +240,10 @@ public class LibraryScanTests } [Theory] - [InlineData(LibraryScanJobStatus.Pending)] // cannot cancel a pending scan - [InlineData(LibraryScanJobStatus.Completed)] // cannot cancel a completed scan - [InlineData(LibraryScanJobStatus.Canceled)] // cannot cancel an already canceled scan - [InlineData(LibraryScanJobStatus.Failed)] // cannot cancel a failed scan - public void CancelScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) + [InlineData(LibraryScanJobStatus.Completed)] // Cannot cancel a completed scan. + [InlineData(LibraryScanJobStatus.Canceled)] // Cannot cancel an already canceled scan. + [InlineData(LibraryScanJobStatus.Failed)] // Cannot cancel a failed scan. + public void CancelScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status) { // Arrange LibraryScan scan = _libraryScanFixture.Create(status: status); @@ -251,16 +253,18 @@ public class LibraryScanTests // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + Assert.Equal(Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError); Assert.Equal(status, scan.Status); Assert.Empty(scan.GetDomainEvents()); } - [Fact] - public void FailScan_WhenRunning_ShouldTransitionToFailed() + [Theory] + [InlineData(LibraryScanJobStatus.Pending)] // A scan that has no scanner yet fails before it starts executing. + [InlineData(LibraryScanJobStatus.Running)] // A scan that is executing can fail too. + public void FailScan_WhenPendingOrRunning_ShouldTransitionToFailed(LibraryScanJobStatus status) { // Arrange - LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScan scan = _libraryScanFixture.Create(status: status); // Act Result result = scan.FailScan(); @@ -272,11 +276,10 @@ public class LibraryScanTests } [Theory] - [InlineData(LibraryScanJobStatus.Pending)] // cannot fail a pending scan - [InlineData(LibraryScanJobStatus.Completed)] // cannot fail a completed scan - [InlineData(LibraryScanJobStatus.Canceled)] // cannot fail a canceled scan - [InlineData(LibraryScanJobStatus.Failed)] // cannot fail an already failed scan - public void FailScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) + [InlineData(LibraryScanJobStatus.Completed)] // Cannot fail a completed scan. + [InlineData(LibraryScanJobStatus.Canceled)] // Cannot fail a canceled scan. + [InlineData(LibraryScanJobStatus.Failed)] // Cannot fail an already failed scan. + public void FailScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status) { // Arrange LibraryScan scan = _libraryScanFixture.Create(status: status); @@ -286,7 +289,7 @@ public class LibraryScanTests // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.LibraryScanning.CanOnlyFailRunningScans, result.FirstError); + Assert.Equal(Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans, result.FirstError); Assert.Equal(status, scan.Status); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs index 46c95657..85d7dd8f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -8,20 +9,19 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library 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; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using NSubstitute; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; -using System.Threading.Channels; using System.Threading.Tasks; #endregion @@ -33,7 +33,6 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC [ExcludeFromCodeCoverage] public class MediaLibraryScanningServiceTests { - private readonly IMediaLibrariesScanQueue _mockScanQueue; private readonly IMediaLibraryScannerFactory _mockScannerFactory; private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker; @@ -42,85 +41,168 @@ public class MediaLibraryScanningServiceTests private readonly LibraryScanFixture _libraryScanFixture = new(); private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); - private readonly Channel _channel; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new(); /// /// Initializes a new instance of the class. /// public MediaLibraryScanningServiceTests() { - _channel = Channel.CreateUnbounded(); - _mockScanQueue = Substitute.For(); - _mockScanQueue.Writer.Returns(_channel.Writer); - _mockScanQueue.Reader.Returns(_channel.Reader); _mockScannerFactory = Substitute.For(); _mockCancellationTracker = Substitute.For(); - _mockCancellationTracker.GetTokenForScan(Arg.Any()).Returns(CancellationToken.None); _mockProgressTracker = Substitute.For(); - _mockProgressTracker.InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockProgressTracker.InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Created); _mockDomainEventPublisher = Substitute.For(); - _sut = new MediaLibraryScanningService(_mockScanQueue, _mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher); + _sut = new MediaLibraryScanningService(_mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher); } [Fact] - public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishEventsAndEnqueueJobs() + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldReturnTheDiscoveryRootJob() { // Arrange LibraryScan scan = _libraryScanFixture.Create(); - IMediaLibraryScanJob job = CreateJob(children: []); - IMediaTypeScanner scanner = CreateScanner([job]); + FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterScanner(LibraryType.Book, rootJob); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(Result.Success, result.Value); + Assert.Same(rootJob, result.Value); Assert.Equal(LibraryScanJobStatus.Running, scan.Status); - await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any(), Arg.Any()); - _mockCancellationTracker.Received(1).RegisterScan(Arg.Is(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId)); - _mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any(), totalJobs: 1); - Assert.Equal(scan.Id, job.ScanId); - Assert.Equal(scan.UserId, job.UserId); - Assert.True(_channel.Reader.TryRead(out IMediaLibraryScanJob? enqueuedJob)); - Assert.Same(job, enqueuedJob); - Assert.False(_channel.Reader.TryRead(out _)); } [Fact] - public async Task StartScanAsync_WhenScanCannotStart_ShouldReturnErrorAndNotEnqueueJobs() + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishTheStartedEvent() { // Arrange - LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScan scan = _libraryScanFixture.Create(); + RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create()); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync( + Arg.Is(domainEvent => domainEvent.GetType() == typeof(LibraryScanStartedDomainEvent) + && ((LibraryScanStartedDomainEvent)domainEvent).LibraryScan == scan), + Arg.Any()); + } + + [Fact] + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldRegisterTheScanForCancellation() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create()); + + // Act + await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + + // Assert + _mockCancellationTracker.Received(1).RegisterScan( + Arg.Is(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId)); + } + + [Fact] + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldInitializeProgressWithTheRealJobCount() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]); + FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]); + RegisterScanner(LibraryType.Book, rootJob); + + // Act + await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + + // Assert + _mockProgressTracker.Received(1).InitializeScanProgress( + scan.LibraryId, + Arg.Is(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId), + totalJobs: 3); + } + + [Fact] + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldSetScanPropertiesOnTheWholeJobChain() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]); + FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]); + RegisterScanner(LibraryType.Book, rootJob); + + // Act + await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + + // Assert + AssertScanProperties(rootJob, scan); + AssertScanProperties(middleJob, scan); + AssertScanProperties(leafJob, scan); + } + + [Fact] + public async Task StartScanAsync_WhenScannerIsUnavailable_ShouldReturnErrorAndChangeNothing() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + _mockScannerFactory.CreateLibraryScanner(LibraryType.Movie).Returns(Errors.LibraryScanning.NoScannerForLibraryType); + + // Act + Result result = await _sut.StartScanAsync(scan, LibraryType.Movie, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError); - await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError); + Assert.Equal(LibraryScanJobStatus.Pending, scan.Status); + Assert.Empty(scan.GetDomainEvents()); + _mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any()); _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); - Assert.False(_channel.Reader.TryRead(out _)); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); } [Fact] - public async Task StartScanAsync_WhenScannerThrowsNotImplementedException_ShouldSucceedWithoutEnqueuingJobs() + public async Task StartScanAsync_WhenScanIsNotPending_ShouldReturnErrorWithoutRegisteringOrPublishing() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create()); + + // Act + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError); + Assert.Equal(LibraryScanJobStatus.Running, scan.Status); + Assert.Empty(scan.GetDomainEvents()); + _mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any()); + _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task StartScanAsync_WhenProgressInitializationFails_ShouldReturnErrorWithoutPublishingEvents() { // Arrange LibraryScan scan = _libraryScanFixture.Create(); - IMediaTypeScanner scanner = Substitute.For(); - scanner.CreateScanJobsForLibrary(Arg.Any()).Returns(_ => throw new NotImplementedException()); - _mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner); + RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create()); + Error error = Error.Failure(description: "Failed to initialize the media library scan progress"); + _mockProgressTracker.InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Success, result.Value); - _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); - Assert.False(_channel.Reader.TryRead(out _)); + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -129,17 +211,16 @@ public class MediaLibraryScanningServiceTests // Arrange LibraryScan scan = _libraryScanFixture.Create(); IMediaLibraryScanJob sharedChild = CreateJob(children: []); - IMediaLibraryScanJob firstRoot = CreateJob(children: [sharedChild]); - IMediaLibraryScanJob secondRoot = CreateJob(children: [sharedChild]); - IMediaTypeScanner scanner = CreateScanner([firstRoot, secondRoot]); + IMediaLibraryScanJob firstChild = CreateJob(children: [sharedChild]); + IMediaLibraryScanJob secondChild = CreateJob(children: [sharedChild]); + FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [firstChild, secondChild]); + RegisterScanner(LibraryType.Book, rootJob); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); + await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert - Assert.False(result.IsFailure); - _mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any(), totalJobs: 3); - Assert.Equal(2, CountEnqueuedJobs()); + _mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any(), totalJobs: 4); } [Fact] @@ -180,15 +261,16 @@ public class MediaLibraryScanningServiceTests } /// - /// Creates a mocked and registers it with the mocked scanner factory. + /// Registers a mocked media library scanner that returns with the mocked scanner factory. /// - /// The scan jobs the scanner returns when asked to create scan jobs for a library. + /// The media library type that the scanner is registered for. + /// The file system discovery job returned by the scanner. /// The created mocked scanner. - private IMediaTypeScanner CreateScanner(List jobs) + private IMediaTypeScanner RegisterScanner(LibraryType libraryType, IMediaLibraryScanDiscoveryJob rootJob) { IMediaTypeScanner scanner = Substitute.For(); - scanner.CreateScanJobsForLibrary(Arg.Any()).Returns(jobs); - _mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner); + scanner.CreateScanJobsForLibrary(Arg.Any()).Returns(rootJob); + _mockScannerFactory.CreateLibraryScanner(libraryType).Returns(Result.From(scanner)); return scanner; } @@ -205,14 +287,13 @@ public class MediaLibraryScanningServiceTests } /// - /// Counts and drains the scan jobs currently enqueued on the scan queue channel. + /// Asserts that the scan identity of the scan was propagated to . /// - /// The number of enqueued scan jobs. - private int CountEnqueuedJobs() + /// The job whose scan properties are asserted. + /// The media library scan that owns the job. + private static void AssertScanProperties(IMediaLibraryScanJob job, LibraryScan scan) { - int count = 0; - while (_channel.Reader.TryRead(out _)) - count++; - return count; + Assert.Equal(scan.Id, job.ScanId); + Assert.Equal(scan.UserId, job.UserId); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs index ffa634d3..e0a8d8a0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs @@ -23,6 +23,51 @@ public class MediaLibrariesScanProgressTrackerTests private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + [Fact] + public void InitializeQueuedScanProgress_WhenCalled_ShouldCreatePendingProgressWithZeroTotalJobs() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + Result result = _sut.InitializeQueuedScanProgress(libraryId, compositeId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.Equal(compositeId.ScanId, progressResult.Value.ScanId); + Assert.Equal(compositeId.UserId, progressResult.Value.UserId); + Assert.Equal(libraryId, progressResult.Value.LibraryId); + Assert.Equal(0, progressResult.Value.CompletedJobs); + Assert.Equal(0, progressResult.Value.TotalJobs); + Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status); + Assert.True(progressResult.Value.CurrentJobProgress.HasValue); + Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation); + } + + [Fact] + public void InitializeQueuedScanProgress_WhenCalledTwice_ShouldReplaceThePreviousProgress() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + _sut.InitializeQueuedScanProgress(libraryId, compositeId); + Result result = _sut.InitializeQueuedScanProgress(libraryId, compositeId); + + // Assert + Assert.False(result.IsFailure); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.Equal(0, progressResult.Value.CompletedJobs); + Assert.Equal(0, progressResult.Value.TotalJobs); + Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation); + } + [Fact] public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs() { @@ -46,14 +91,14 @@ public class MediaLibrariesScanProgressTrackerTests } [Fact] - public void InitializeScanProgress_WhenTotalJobsIsNotPositive_ShouldReturnError() + public void InitializeScanProgress_WhenTotalJobsIsNegative_ShouldReturnError() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); // Act - Result result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 0); + Result result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: -1); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs index e495f603..589536ee 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs @@ -1,4 +1,6 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; @@ -15,96 +17,122 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class MediaLibraryScannerFactoryTests +public class MediaLibraryScannerFactoryTests : IDisposable { + private readonly IBookLibraryTypeScanner _mockBookLibraryTypeScanner; + private readonly IMusicLibraryTypeScanner _mockMusicLibraryTypeScanner; + private readonly ServiceProvider _serviceProvider; + private readonly MediaLibraryScannerFactory _sut; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScannerFactoryTests() + { + _mockBookLibraryTypeScanner = Substitute.For(); + _mockMusicLibraryTypeScanner = Substitute.For(); + + ServiceCollection services = new(); + services.AddSingleton(_mockBookLibraryTypeScanner); + services.AddSingleton(_mockMusicLibraryTypeScanner); + _serviceProvider = services.BuildServiceProvider(); + _sut = new MediaLibraryScannerFactory(_serviceProvider); + } + [Fact] public void CreateLibraryScanner_WhenLibraryTypeIsBook_ShouldReturnBookLibraryTypeScanner() { - // Arrange - IBookLibraryTypeScanner expectedScanner = Substitute.For(); - ServiceCollection services = new(); - services.AddSingleton(expectedScanner); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); - MediaLibraryScannerFactory sut = new(serviceProvider); - // Act - IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Book); + Result result = _sut.CreateLibraryScanner(LibraryType.Book); // Assert - Assert.Same(expectedScanner, scanner); + Assert.False(result.IsFailure); + Assert.Same(_mockBookLibraryTypeScanner, result.Value); } [Fact] public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner() { - // Arrange - IMusicLibraryTypeScanner expectedScanner = Substitute.For(); - ServiceCollection services = new(); - services.AddSingleton(expectedScanner); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); - MediaLibraryScannerFactory sut = new(serviceProvider); - // Act - IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music); + Result result = _sut.CreateLibraryScanner(LibraryType.Music); // Assert - Assert.Same(expectedScanner, scanner); + Assert.False(result.IsFailure); + Assert.Same(_mockMusicLibraryTypeScanner, result.Value); } [Theory] - [InlineData(LibraryType.EBook)] // eBook scanner is not implemented - [InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented - [InlineData(LibraryType.Magazine)] // magazine scanner is not implemented - [InlineData(LibraryType.Newspaper)] // newspaper scanner is not implemented - [InlineData(LibraryType.Manga)] // manga scanner is not implemented - [InlineData(LibraryType.GraphicNovel)] // graphic novel scanner is not implemented - [InlineData(LibraryType.AcademicPaper)] // academic paper scanner is not implemented - [InlineData(LibraryType.SheetMusic)] // sheet music scanner is not implemented - [InlineData(LibraryType.Movie)] // movie scanner is not implemented - [InlineData(LibraryType.TvShow)] // TV show scanner is not implemented - [InlineData(LibraryType.Documentary)] // documentary scanner is not implemented - [InlineData(LibraryType.Anime)] // anime scanner is not implemented - [InlineData(LibraryType.ConcertVideo)] // concert video scanner is not implemented - [InlineData(LibraryType.TutorialVideo)] // tutorial video scanner is not implemented - [InlineData(LibraryType.HomeVideo)] // home video scanner is not implemented - [InlineData(LibraryType.YouTubeVideo)] // YouTube video scanner is not implemented - [InlineData(LibraryType.MusicVideo)] // music video scanner is not implemented - [InlineData(LibraryType.LiveRecordingVideo)] // live recording video scanner is not implemented - [InlineData(LibraryType.InterviewVideo)] // interview video scanner is not implemented - [InlineData(LibraryType.CoverSongVideo)] // cover song video scanner is not implemented - [InlineData(LibraryType.PodcastVideo)] // podcast video scanner is not implemented - [InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented - [InlineData(LibraryType.LiveRecordingAudio)] // live recording audio scanner is not implemented - [InlineData(LibraryType.InterviewAudio)] // interview audio scanner is not implemented - [InlineData(LibraryType.CoverSongAudio)] // cover song audio scanner is not implemented - [InlineData(LibraryType.Remix)] // remix scanner is not implemented - [InlineData(LibraryType.SoundEffect)] // sound effect scanner is not implemented - [InlineData(LibraryType.PodcastAudio)] // podcast audio scanner is not implemented - [InlineData(LibraryType.Photo)] // photo scanner is not implemented - [InlineData(LibraryType.Playlist)] // playlist scanner is not implemented - [InlineData(LibraryType.Collection)] // collection scanner is not implemented - [InlineData(LibraryType.Subtitles)] // subtitles scanner is not implemented - [InlineData(LibraryType.Lyrics)] // lyrics scanner is not implemented - public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldThrowNotImplementedException(LibraryType libraryType) + [InlineData(LibraryType.EBook)] // EBook scanner is not implemented. + [InlineData(LibraryType.ComicBook)] // Comic book scanner is not implemented. + [InlineData(LibraryType.Magazine)] // Magazine scanner is not implemented. + [InlineData(LibraryType.Newspaper)] // Newspaper scanner is not implemented. + [InlineData(LibraryType.Manga)] // Manga scanner is not implemented. + [InlineData(LibraryType.GraphicNovel)] // Graphic novel scanner is not implemented. + [InlineData(LibraryType.AcademicPaper)] // Academic paper scanner is not implemented. + [InlineData(LibraryType.SheetMusic)] // Sheet music scanner is not implemented. + [InlineData(LibraryType.Movie)] // Movie scanner is not implemented. + [InlineData(LibraryType.TvShow)] // TV show scanner is not implemented. + [InlineData(LibraryType.Documentary)] // Documentary scanner is not implemented. + [InlineData(LibraryType.Anime)] // Anime scanner is not implemented. + [InlineData(LibraryType.ConcertVideo)] // Concert video scanner is not implemented. + [InlineData(LibraryType.TutorialVideo)] // Tutorial video scanner is not implemented. + [InlineData(LibraryType.HomeVideo)] // Home video scanner is not implemented. + [InlineData(LibraryType.YouTubeVideo)] // YouTube video scanner is not implemented. + [InlineData(LibraryType.MusicVideo)] // Music video scanner is not implemented. + [InlineData(LibraryType.LiveRecordingVideo)] // Live recording video scanner is not implemented. + [InlineData(LibraryType.InterviewVideo)] // Interview video scanner is not implemented. + [InlineData(LibraryType.CoverSongVideo)] // Cover song video scanner is not implemented. + [InlineData(LibraryType.PodcastVideo)] // Podcast video scanner is not implemented. + [InlineData(LibraryType.Audiobook)] // Audiobook scanner is not implemented. + [InlineData(LibraryType.LiveRecordingAudio)] // Live recording audio scanner is not implemented. + [InlineData(LibraryType.InterviewAudio)] // Interview audio scanner is not implemented. + [InlineData(LibraryType.CoverSongAudio)] // Cover song audio scanner is not implemented. + [InlineData(LibraryType.Remix)] // Remix scanner is not implemented. + [InlineData(LibraryType.SoundEffect)] // Sound effect scanner is not implemented. + [InlineData(LibraryType.PodcastAudio)] // Podcast audio scanner is not implemented. + [InlineData(LibraryType.Photo)] // Photo scanner is not implemented. + [InlineData(LibraryType.Playlist)] // Playlist scanner is not implemented. + [InlineData(LibraryType.Collection)] // Collection scanner is not implemented. + [InlineData(LibraryType.Subtitles)] // Subtitles scanner is not implemented. + [InlineData(LibraryType.Lyrics)] // Lyrics scanner is not implemented. + public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldReturnNoScannerError(LibraryType libraryType) { - // Arrange - ServiceCollection services = new(); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); - MediaLibraryScannerFactory sut = new(serviceProvider); + // Act + Result result = _sut.CreateLibraryScanner(libraryType); - // Act & Assert - Assert.Throws(() => sut.CreateLibraryScanner(libraryType)); + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError); + Assert.IsType(result.FirstError); } [Fact] - public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldThrowArgumentOutOfRangeException() + public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldNotThrow() { - // Arrange - ServiceCollection services = new(); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); - MediaLibraryScannerFactory sut = new(serviceProvider); + // Act + Exception? exception = Record.Exception(() => _sut.CreateLibraryScanner(LibraryType.Movie)); - // Act & Assert - Assert.Throws(() => sut.CreateLibraryScanner((LibraryType)999)); + // Assert + Assert.Null(exception); + } + + [Fact] + public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldReturnNoScannerError() + { + // Act + Result result = _sut.CreateLibraryScanner((LibraryType)999); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError); + Assert.IsType(result.FirstError); + } + + /// + /// Disposes the test dependencies. + /// + public void Dispose() + { + _serviceProvider.Dispose(); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs index 8a3c3ee7..31e72a45 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs @@ -69,10 +69,8 @@ public class MediaLibraryScanProgressTests Assert.False(result.Value.CurrentJobProgress.HasValue); } - [Theory] - [InlineData(0)] // total jobs must be positive - [InlineData(-1)] // total jobs must be positive - public void Create_WhenTotalJobsIsNotPositive_ShouldReturnError(int totalJobs) + [Fact] + public void Create_WhenTotalJobsIsZeroAndStatusIsPending_ShouldCreateQueuedProgress() { // Act Result result = MediaLibraryScanProgress.Create( @@ -80,10 +78,52 @@ public class MediaLibraryScanProgressTests _userIdFixture.Create(), _libraryIdFixture.Create(), completedJobs: 0, - totalJobs: totalJobs, + totalJobs: 0, LibraryScanJobStatus.Pending, Optional.None()); + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0, result.Value.TotalJobs); + Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status); + Assert.Equal(0, result.Value.OverallProgressPercentage); + } + + [Fact] + public void Create_WhenTotalJobsIsNegative_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: 0, + totalJobs: -1, + LibraryScanJobStatus.Pending, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError); + } + + [Theory] + [InlineData(LibraryScanJobStatus.Running)] // Only a scan that is still queued may have no jobs yet. + [InlineData(LibraryScanJobStatus.Completed)] // A completed scan must have had at least one job. + [InlineData(LibraryScanJobStatus.Canceled)] // A canceled scan must have had at least one job. + [InlineData(LibraryScanJobStatus.Failed)] // A failed scan must have had at least one job. + public void Create_WhenTotalJobsIsZeroAndStatusIsNotPending_ShouldReturnError(LibraryScanJobStatus status) + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: 0, + totalJobs: 0, + status, + Optional.None()); + // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs index 16c76795..3a9e1a44 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs @@ -11,7 +11,6 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -54,11 +53,11 @@ public class BookLibraryTypeScannerTests BookLibraryTypeScanner sut = new(_mockJobFactory); // Act - List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)]; + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); // Assert - IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); Assert.Same(discoveryJob, rootJob); + Assert.IsAssignableFrom(rootJob); Assert.Contains(diffJob, discoveryJob.Children); Assert.Contains(discoveryJob, diffJob.Parents); Assert.Contains(hashJob, diffJob.Children); @@ -75,6 +74,58 @@ public class BookLibraryTypeScannerTests _mockJobFactory.Received(1).CreateJob(libraryId); } + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldReturnTheFileSystemDiscoveryJobAsTheOnlyRoot() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + BookLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); + + // Assert + Assert.Same(discoveryJob, rootJob); + // The file system discovery job is the only top level job, so nothing else is reachable without it. + Assert.Empty(discoveryJob.Parents); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldMakeTheWholeChainReachableFromTheRoot() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + TestScanJob diffJob = CreateJob(); + TestScanJob hashJob = CreateJob(); + TestScanJob saveJob = CreateJob(); + TestScanJob invalidationJob = CreateJob(); + TestScanJob enrichmentJob = CreateJob(); + TestScanJob artworkEnrichmentJob = CreateJob(); + BookLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId); + HashSet reachableJobs = GetReachableJobs(rootJob); + + // Assert + Assert.Equal(7, reachableJobs.Count); + Assert.Contains(discoveryJob, reachableJobs); + Assert.Contains(diffJob, reachableJobs); + Assert.Contains(hashJob, reachableJobs); + Assert.Contains(saveJob, reachableJobs); + Assert.Contains(invalidationJob, reachableJobs); + Assert.Contains(enrichmentJob, reachableJobs); + Assert.Contains(artworkEnrichmentJob, reachableJobs); + } + [Fact] public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary() { @@ -90,7 +141,7 @@ public class BookLibraryTypeScannerTests BookLibraryTypeScanner sut = new(_mockJobFactory); // Act - _ = sut.CreateScanJobsForLibrary(libraryId).ToList(); + _ = sut.CreateScanJobsForLibrary(libraryId); // Assert _mockJobFactory.Received(1).CreateJob(libraryId); @@ -102,6 +153,27 @@ public class BookLibraryTypeScannerTests _mockJobFactory.Received(1).CreateJob(libraryId); } + /// + /// Collects every job that is reachable from through the child relationships. + /// + /// The root job of the job graph. + /// The set of reachable jobs. + private static HashSet GetReachableJobs(IMediaLibraryScanJob rootJob) + { + HashSet reachableJobs = []; + Queue jobsToVisit = new(); + jobsToVisit.Enqueue(rootJob); + while (jobsToVisit.Count > 0) + { + IMediaLibraryScanJob currentJob = jobsToVisit.Dequeue(); + if (!reachableJobs.Add(currentJob)) + continue; + foreach (IMediaLibraryScanJob childJob in currentJob.Children) + jobsToVisit.Enqueue(childJob); + } + return reachableJobs; + } + private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob { TestScanJob job = new() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs index 09778c31..8c957255 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs @@ -201,6 +201,62 @@ public class DebouncedMediaLibraryScanProgressNotifierTests _mockHubClients.DidNotReceive().Group(Arg.Any()); } + [Fact] + public async Task SendLibraryScanCancelledEventAsync_WhenProgressExists_ShouldSendCancelledEventWithCanceledStatus() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create( + scanId: compositeId.ScanId, + userId: compositeId.UserId, + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Pending); + _mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress)); + + // Act + await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.Received(1).SendCoreAsync( + "libraryScanCancelledEvent", + Arg.Is(args => args.Length == 1 + && args[0] != null + && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Canceled.ToString()), + Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanCancelledEventAsync_WhenProgressIsMissing_ShouldNotSendCancelledEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _mockProgressTracker.RemoveScanProgress(compositeId) + .Returns(Error.Failure("Tracking.Error", "The scan progress is missing")); + + // Act + await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanCancelledEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryScanCancelledEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + [Fact] public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs index 9819f68a..2bee20df 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; -using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -16,37 +16,58 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning. public class MediaLibrariesScanQueueTests { private readonly MediaLibrariesScanQueue _sut = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); [Fact] - public async Task Writer_WhenJobIsWritten_ShouldAllowReadingItFromReader() + public async Task Writer_WhenScanIsWritten_ShouldAllowReadingItFromReader() { // Arrange - IMediaLibraryScanJob job = Substitute.For(); + MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create(); // Act - bool writeResult = _sut.Writer.TryWrite(job); - IMediaLibraryScanJob readJob = await _sut.Reader.ReadAsync(CancellationToken.None); + bool writeResult = _sut.Writer.TryWrite(scanId); + MediaLibraryScanCompositeId readScanId = await _sut.Reader.ReadAsync(CancellationToken.None); // Assert Assert.True(writeResult); - Assert.Same(job, readJob); + Assert.Equal(scanId, readScanId); } [Fact] - public async Task Writer_WhenMultipleJobsAreWritten_ShouldReadThemInFifoOrder() + public async Task Writer_WhenMultipleScansAreWritten_ShouldReadThemInFifoOrder() { // Arrange - IMediaLibraryScanJob firstJob = Substitute.For(); - IMediaLibraryScanJob secondJob = Substitute.For(); + MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId thirdScanId = _mediaLibraryScanCompositeIdFixture.Create(); // Act - _sut.Writer.TryWrite(firstJob); - _sut.Writer.TryWrite(secondJob); - IMediaLibraryScanJob firstReadJob = await _sut.Reader.ReadAsync(CancellationToken.None); - IMediaLibraryScanJob secondReadJob = await _sut.Reader.ReadAsync(CancellationToken.None); + _sut.Writer.TryWrite(firstScanId); + _sut.Writer.TryWrite(secondScanId); + _sut.Writer.TryWrite(thirdScanId); + MediaLibraryScanCompositeId firstReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None); + MediaLibraryScanCompositeId secondReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None); + MediaLibraryScanCompositeId thirdReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None); // Assert - Assert.Same(firstJob, firstReadJob); - Assert.Same(secondJob, secondReadJob); + // The scan processor relies on the queue order: scans must run in the order in which they were queued. + Assert.Equal(firstScanId, firstReadScanId); + Assert.Equal(secondScanId, secondReadScanId); + Assert.Equal(thirdScanId, thirdReadScanId); + } + + [Fact] + public async Task Reader_WhenQueueIsEmpty_ShouldNotCompleteUntilAScanIsWritten() + { + // Arrange + MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + Task readTask = _sut.Reader.ReadAsync(CancellationToken.None).AsTask(); + _sut.Writer.TryWrite(scanId); + + // Assert + MediaLibraryScanCompositeId readScanId = await readTask; + Assert.Equal(scanId, readScanId); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs deleted file mode 100644 index 14c8da73..00000000 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -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.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class MediaLibraryScanJobProcessorJobTests -{ - private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly UserIdFixture _userIdFixture = new(); - private readonly LibraryIdFixture _libraryIdFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public MediaLibraryScanJobProcessorJobTests() - { - _mockCancellationTracker = Substitute.For(); - } - - [Fact] - public async Task StartAsync_WhenJobIsEnqueued_ShouldExecuteTheJobWithLinkedCancellationToken() - { - // Arrange - MediaLibrariesScanQueue queue = new(); - MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker); - RecordingScanJob job = CreateRecordingScanJob(); - _mockCancellationTracker.GetTokenForScan(Arg.Any()) - .Returns(CancellationToken.None); - - await sut.StartAsync(CancellationToken.None); - - // Act - queue.Writer.TryWrite(job); - await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5)); - - // Assert - Assert.True(job.WasExecuted); - Assert.False(job.ReceivedCancellationToken.IsCancellationRequested); - _mockCancellationTracker.Received(1).GetTokenForScan( - Arg.Is(compositeId => compositeId.ScanId == job.ScanId && compositeId.UserId == job.UserId)); - - await sut.StopAsync(CancellationToken.None); - } - - [Fact] - public async Task StartAsync_WhenScanWasAlreadyCancelled_ShouldExecuteJobWithAlreadyCancelledLinkedToken() - { - // Arrange - MediaLibrariesScanQueue queue = new(); - MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker); - RecordingScanJob job = CreateRecordingScanJob(); - using CancellationTokenSource scanCancellationTokenSource = new(); - scanCancellationTokenSource.Cancel(); - _mockCancellationTracker.GetTokenForScan(Arg.Any()) - .Returns(scanCancellationTokenSource.Token); - - await sut.StartAsync(CancellationToken.None); - - // Act - queue.Writer.TryWrite(job); - await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5)); - - // Assert - Assert.True(job.WasExecuted); - Assert.True(job.ReceivedCancellationToken.IsCancellationRequested); - - await sut.StopAsync(CancellationToken.None); - } - - /// - /// Creates a recording scan job with a random scan and user identity. - /// - /// The created recording scan job. - private RecordingScanJob CreateRecordingScanJob() - { - return new RecordingScanJob - { - ScanId = _scanIdFixture.Create(), - UserId = _userIdFixture.Create(), - LibraryId = _libraryIdFixture.Create() - }; - } - - /// - /// Test double for that records the token it was executed with. - /// - private sealed class RecordingScanJob : IMediaLibraryScanJob - { - private readonly TaskCompletionSource _executed = new(TaskCreationOptions.RunContinuationsAsynchronously); - - public required ScanId ScanId { get; set; } - - public required UserId UserId { get; set; } - - public required LibraryId LibraryId { get; set; } - - public List Children { get; } = []; - - public List Parents { get; } = []; - - public LibraryScanJobStatus Status { get; private set; } - - public Task ExecutedTask => _executed.Task; - - public bool WasExecuted { get; private set; } - - public CancellationToken ReceivedCancellationToken { get; private set; } - - public void AddChild(IMediaLibraryScanJob job) - { - } - - public void AddParent(IMediaLibraryScanJob job) - { - } - - public Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - WasExecuted = true; - ReceivedCancellationToken = cancellationToken; - _executed.TrySetResult(true); - return Task.CompletedTask; - } - } -} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs new file mode 100644 index 00000000..937c54c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs @@ -0,0 +1,317 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +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.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProcessorJobTests : IDisposable +{ + private static readonly TimeSpan s_testTimeout = TimeSpan.FromSeconds(5); + private readonly MediaLibrariesScanQueue _queue; + private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly ServiceProvider _serviceProvider; + private readonly MediaLibraryScanProcessorJob _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanProcessorJobTests() + { + _queue = new MediaLibrariesScanQueue(); + _mockCancellationTracker = Substitute.For(); + _mockCancellationTracker.GetTokenForScan(Arg.Any()).Returns(CancellationToken.None); + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockMediaLibraryScanningService = Substitute.For(); + _mockDomainEventPublisher = Substitute.For(); + _mockLogger = Substitute.For>(); + + ServiceCollection services = new(); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockMediaLibraryScanningService); + services.AddSingleton(_mockDomainEventPublisher); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new MediaLibraryScanProcessorJob( + _queue, + _mockCancellationTracker, + _serviceProvider.GetRequiredService(), + _mockLogger); + } + + [Fact] + public async Task ExecuteAsync_WhenScansAreQueued_ShouldProcessThemOneAtATimeInOrder() + { + // Arrange + MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(firstScanId, LibraryScanJobStatus.Pending); + RegisterScan(secondScanId, LibraryScanJobStatus.Pending); + TaskCompletionSource releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously); + List startedScanIds = []; + FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ => + { + startedScanIds.Add(firstScanId.ScanId.Value); + await releaseFirstScan.Task; + }); + FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ => + { + startedScanIds.Add(secondScanId.ScanId.Value); + return Task.CompletedTask; + }); + RegisterRootJob(firstScanId, firstRootJob); + RegisterRootJob(secondScanId, secondRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(firstScanId); + _queue.Writer.TryWrite(secondScanId); + await firstRootJob.ExecutionStarted.WaitAsync(s_testTimeout); + + // Assert + // The second scan must not start while the job graph of the first one is still executing. + Assert.Equal([firstScanId.ScanId.Value], startedScanIds); + Assert.Equal(0, secondRootJob.ExecutionCount); + + releaseFirstScan.SetResult(true); + await secondRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + Assert.Equal([firstScanId.ScanId.Value, secondScanId.ScanId.Value], startedScanIds); + Assert.Equal(1, firstRootJob.ExecutionCount); + await _sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task ExecuteAsync_WhenScanIsNotPending_ShouldSkipItAndProcessTheNextScan() + { + // Arrange + MediaLibraryScanCompositeId completedScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(completedScanId, LibraryScanJobStatus.Completed); + RegisterScan(pendingScanId, LibraryScanJobStatus.Pending); + FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterRootJob(pendingScanId, pendingRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(completedScanId); + _queue.Writer.TryWrite(pendingScanId); + await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + + // Assert + // A scan that was cancelled or otherwise finished while it was waiting for its turn must not be started. + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == completedScanId.ScanId.Value), + Arg.Any(), + Arg.Any()); + await _mockMediaLibraryScanningService.Received(1).StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value), + Arg.Any(), + Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + await _sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task ExecuteAsync_WhenScanTokenIsAlreadyCancelled_ShouldSkipItAndProcessTheNextScan() + { + // Arrange + MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending); + RegisterScan(pendingScanId, LibraryScanJobStatus.Pending); + using CancellationTokenSource cancelledTokenSource = new(); + cancelledTokenSource.Cancel(); + _mockCancellationTracker.GetTokenForScan(cancelledScanId).Returns(cancelledTokenSource.Token); + FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterRootJob(pendingScanId, pendingRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(cancelledScanId); + _queue.Writer.TryWrite(pendingScanId); + await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + + // Assert + // A scan that was cancelled while it was waiting for its turn is not even loaded from the repository. + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync( + cancelledScanId.ScanId.Value, + Arg.Any(), + false, + Arg.Any()); + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == cancelledScanId.ScanId.Value), + Arg.Any(), + Arg.Any()); + await _mockMediaLibraryScanningService.Received(1).StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value), + Arg.Any(), + Arg.Any()); + await _sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task ExecuteAsync_WhenPreparingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan() + { + // Arrange + MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(failingScanId, LibraryScanJobStatus.Pending); + RegisterScan(pendingScanId, LibraryScanJobStatus.Pending); + Error error = Error.Failure(description: "Failed to prepare the media library scan"); + _mockMediaLibraryScanningService.StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == failingScanId.ScanId.Value), + Arg.Any(), + Arg.Any()) + .Returns(error); + FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterRootJob(pendingScanId, pendingRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(failingScanId); + _queue.Writer.TryWrite(pendingScanId); + await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync( + Arg.Is(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent) + && ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId), + Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any(), Arg.Any()); + Assert.Equal(1, pendingRootJob.ExecutionCount); + await _sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task ExecuteAsync_WhenExecutingAScanIsCancelled_ShouldNotStopProcessingTheNextScan() + { + // Arrange + MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending); + RegisterScan(pendingScanId, LibraryScanJobStatus.Pending); + FakeMediaLibraryScanDiscoveryJob cancelledRootJob = _mediaLibraryScanDiscoveryJobFixture.Create( + onExecute: _ => throw new OperationCanceledException()); + FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterRootJob(cancelledScanId, cancelledRootJob); + RegisterRootJob(pendingScanId, pendingRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(cancelledScanId); + _queue.Writer.TryWrite(pendingScanId); + await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + + // Assert + Assert.Equal(1, cancelledRootJob.ExecutionCount); + Assert.Equal(1, pendingRootJob.ExecutionCount); + // A cancelled scan was already reported by its own cancellation event, so no failure is published for it. + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + await _sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task ExecuteAsync_WhenExecutingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan() + { + // Arrange + MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create(); + RegisterScan(failingScanId, LibraryScanJobStatus.Pending); + RegisterScan(pendingScanId, LibraryScanJobStatus.Pending); + FakeMediaLibraryScanDiscoveryJob failingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create( + onExecute: _ => throw new InvalidOperationException("The scan job payload failed")); + FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(); + RegisterRootJob(failingScanId, failingRootJob); + RegisterRootJob(pendingScanId, pendingRootJob); + await _sut.StartAsync(CancellationToken.None); + + // Act + _queue.Writer.TryWrite(failingScanId); + _queue.Writer.TryWrite(pendingScanId); + await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync( + Arg.Is(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent) + && ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId), + Arg.Any()); + Assert.Equal(1, pendingRootJob.ExecutionCount); + await _sut.StopAsync(CancellationToken.None); + } + + /// + /// Registers a media library scan with the given status in the mocked repository. + /// + /// The composite identifier of the scan to register. + /// The status of the media library scan. + /// The created media library scan entity. + private LibraryScanEntity RegisterScan(MediaLibraryScanCompositeId compositeId, LibraryScanJobStatus status) + { + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value, + status: status); + _mockLibraryScanRepository + .GetByIdAsync(scan.Id, Arg.Any(), false, Arg.Any()) + .Returns(Result.From(scan)); + return scan; + } + + /// + /// Registers the file system discovery job that the mocked scanning service prepares for a media library scan. + /// + /// The composite identifier of the scan that owns the job. + /// The root job to return when the scan is prepared. + private void RegisterRootJob(MediaLibraryScanCompositeId compositeId, IMediaLibraryScanDiscoveryJob rootJob) + { + _mockMediaLibraryScanningService.StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == compositeId.ScanId.Value), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(rootJob)); + } + + /// + /// Disposes the test dependencies. + /// + public void Dispose() + { + _serviceProvider.Dispose(); + } +}