mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #261 from BinaryAlley/feature/serialized-media-library-scans
Serializes media library scans through a scan queue
This commit is contained in:
98 files changed
+2613
-1445
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+12
-3
@@ -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<TInput>(Guid id, TInput input, CancellationToken token)` on `IMediaLibraryScanJob`. The `IServiceScopeFactory` decision itself is unchanged.
|
||||
|
||||
## Consequences
|
||||
|
||||
@@ -105,3 +102,15 @@ services.AddDbContextFactory<LuminaDbContext>(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<TInput>(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.
|
||||
+13
-14
@@ -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<FileInfo> 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.
|
||||
+4
-4
@@ -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<TInput>` 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.
|
||||
+8
@@ -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.
|
||||
+12
-8
@@ -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.
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
+1
-3
@@ -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<CreateSen
|
||||
| Familiar Surface | `RuleFor` / `Must` / `When` / `WithError` pattern is intentionally close to FluentValidation, minimising cognitive load during migration |
|
||||
| Encapsulation | `IValidationRule` and `ValidationRule` are `internal`; consumers only interact with `IValidator` and `IRuleBuilder` |
|
||||
|
||||
### Risks and Mitigations
|
||||
|
||||
### Risks and Tradeoffs
|
||||
| Risk | Mitigation Strategy |
|
||||
|---|---|
|
||||
| Missing built-in rules surfacing post-migration | Audit all existing FluentValidation rule usages before removal; add corresponding `ValidatorUtilities` extensions as needed |
|
||||
|
||||
+1
-3
@@ -1,7 +1,6 @@
|
||||
# Architecture Decision Record (ADR): 0013 - Replace Mediator Domain Event Publishing with a Custom Implementation
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-08-13)
|
||||
|
||||
## Context
|
||||
@@ -53,8 +52,7 @@ The existing assembly scan that registers `ICommandHandler<>`, `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 |
|
||||
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
+1
-3
@@ -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 |
|
||||
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
# Architecture Decision Record (ADR): 0019 - SSD Aware Read Parallelism During Media Library Scans
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-10-30)
|
||||
|
||||
## Context
|
||||
|
||||
+2
-2
@@ -28,11 +28,11 @@ public interface ILibraryScanRepository : IRepository<LibraryScanEntity>,
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scans have a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Pending"/> or a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryScanEntity"/>, or an error.</returns>
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetRunningScansAsync(CancellationToken cancellationToken);
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetActiveScansAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still
|
||||
|
||||
+6
-6
@@ -64,18 +64,18 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Get the running library scans of the current user from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> 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<IEnumerable<LibraryScanEntity>> getActiveLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getActiveLibraryScansResult.IsFailure)
|
||||
return getActiveLibraryScansResult.Errors;
|
||||
|
||||
// Filter the library scans to process.
|
||||
List<LibraryScanEntity> 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<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
||||
|
||||
+10
-7
@@ -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<Librar
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IMediaLibraryScanProgressNotifier _mediaLibraryScanProgressNotifier;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
@@ -35,17 +35,17 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="mediaLibraryScanProgressNotifier">Injected service for notifying media libraries scan progress changes to third parties.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
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<Librar
|
||||
if (cancelScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||
|
||||
// Release the scan processing resources.
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
||||
|
||||
// Report the cancellation to the clients and release the progress entry of the scan, so that they stop showing it as active.
|
||||
await _mediaLibraryScanProgressNotifier.SendLibraryScanCancelledEventAsync(compositeId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Release the scan processing resources.
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
|
||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
|
||||
// Cancelling the scan cancels its own token, so the cleanup must not observe it, otherwise the staged results of the cancelled scan would survive the cancellation.
|
||||
// A scan that was cancelled after its snapshot was applied has not materialized its items yet, so its snapshot entries are rolled back, allowing the next
|
||||
// scan to treat the files as new and extract their metadata again instead of skipping them as unchanged.
|
||||
|
||||
+27
-38
@@ -1,15 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.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.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -21,22 +16,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
/// </summary>
|
||||
public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibraryScanQueuedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="domainEventsQueue">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork)
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing the media library scans that are waiting to execute.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
public LibraryScanQueuedDomainEventHandler(
|
||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,26 +43,18 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get the library scan that was queued, from the repository.
|
||||
Result<LibraryScanEntity?> 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<LibraryScan> 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<Success> 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);
|
||||
}
|
||||
}
|
||||
+7
@@ -31,4 +31,11 @@ public interface IMediaLibraryScanProgressNotifier
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that failed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the cancellation of a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that was cancelled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken);
|
||||
}
|
||||
+19
-19
@@ -65,33 +65,33 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Get the ongoing library scans from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> 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<IEnumerable<LibraryScanEntity>> 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<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
||||
IEnumerable<Result<LibraryScan>> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> userRunningDomainLibraryScan in userRunningDomainLibraryScans)
|
||||
IEnumerable<Result<LibraryScan>> userActiveDomainLibraryScans = userActiveRepositoryLibraryScans.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> userActiveDomainLibraryScan in userActiveDomainLibraryScans)
|
||||
{
|
||||
if (userRunningDomainLibraryScan.IsFailure)
|
||||
return userRunningDomainLibraryScan.Errors;
|
||||
else
|
||||
{
|
||||
Result<MediaLibraryScanProgress> 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<MediaLibraryScanProgress> 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());
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -83,16 +83,17 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Pending"/> or a
|
||||
/// <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryScanEntity"/>, or an error.</returns>
|
||||
public async Task<Result<IEnumerable<LibraryScanEntity>>> GetRunningScansAsync(CancellationToken cancellationToken)
|
||||
public async Task<Result<IEnumerable<LibraryScanEntity>>> 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -8,6 +8,6 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering music file system items.
|
||||
/// </summary>
|
||||
public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob
|
||||
{
|
||||
}
|
||||
+5
-6
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
{
|
||||
// Declare the list of jobs that this scanner requires.
|
||||
IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IMusicFileSystemDiscoveryJob>(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;
|
||||
}
|
||||
}
|
||||
+3
@@ -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
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="ScanId">The unique identifier of the queued media library scan.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that initiated the queued media library scan.</param>
|
||||
/// <param name="LibraryId">The unique identifier of the library whose scan was queued.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record LibraryScanQueuedDomainEvent(
|
||||
Guid Id,
|
||||
ScanId ScanId,
|
||||
UserId UserId,
|
||||
LibraryId LibraryId,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+9
-7
@@ -90,11 +90,11 @@ public class LibraryScan : AggregateRoot<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> 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<ScanId>
|
||||
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<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> 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<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> 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;
|
||||
}
|
||||
|
||||
+7
-3
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Starts <paramref name="scan"/>.
|
||||
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||
/// </summary>
|
||||
/// <param name="scan">The media library scan to start.</param>
|
||||
/// <param name="libraryType">The type of the media library to be scanned.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> 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.
|
||||
/// </returns>
|
||||
Task<Result<IMediaLibraryScanDiscoveryJob>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Cancels <paramref name="scan"/>.
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job that discovers the file system items of a media library.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is always the only top level job of a media library scan: a scan cannot process anything before the files are discovered.
|
||||
/// </remarks>
|
||||
public interface IMediaLibraryScanDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+37
-45
@@ -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
|
||||
/// </summary>
|
||||
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
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing media libraries scan jobs.</param>
|
||||
/// <param name="mediaLibraryScannerFactory">Injected factory for creating media library scanners.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <paramref name="scan"/>.
|
||||
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||
/// </summary>
|
||||
/// <param name="scan">The media library scan to start.</param>
|
||||
/// <param name="libraryType">The type of the media library to be scanned.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken)
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> 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.
|
||||
/// </returns>
|
||||
public async Task<Result<IMediaLibraryScanDiscoveryJob>> 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<IMediaTypeScanner> 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<Success> 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<Created> 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<IMediaLibraryScanJob> 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<IMediaLibraryScanDiscoveryJob>(rootJob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -105,7 +98,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="rootJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="rootJobs">A list of root media library scan jobs to traverse.</param>
|
||||
/// <param name="rootJob">The file system discovery job, which is the only top level job of the scan job graph.</param>
|
||||
/// <returns>The total count of unique media library scan jobs.</returns>
|
||||
private static int CountTotalJobs(List<IMediaLibraryScanJob> rootJobs)
|
||||
private static int CountTotalJobs(IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
HashSet<IMediaLibraryScanJob> uniqueJobs = [];
|
||||
foreach (IMediaLibraryScanJob job in rootJobs)
|
||||
TraverseJobGraph(job, uniqueJobs);
|
||||
TraverseJobGraph(rootJob, uniqueJobs);
|
||||
return uniqueJobs.Count;
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -11,6 +11,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// </summary>
|
||||
public interface IMediaLibrariesScanProgressTracker
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The object representing the unique identifier of the media library being scanned.</param>
|
||||
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Created> InitializeQueuedScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the the progress tracking of a media library scan.
|
||||
/// </summary>
|
||||
|
||||
+30
@@ -16,6 +16,36 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr
|
||||
{
|
||||
private readonly ConcurrentDictionary<MediaLibraryScanCompositeId, MediaLibraryScanProgress> _scanProgresses = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The object representing the unique identifier of the media library being scanned.</param>
|
||||
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Created> 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<MediaLibraryScanJobProgress> createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Queued");
|
||||
if (createLibraryScanJobProgressResult.IsFailure)
|
||||
return createLibraryScanJobProgressResult.Errors;
|
||||
|
||||
Result<MediaLibraryScanProgress> createScanProgressResult = MediaLibraryScanProgress.Create(
|
||||
mediaLibraryScanCompositeId.ScanId,
|
||||
mediaLibraryScanCompositeId.UserId,
|
||||
libraryId,
|
||||
completedJobs: 0,
|
||||
totalJobs: 0,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.Some(createLibraryScanJobProgressResult.Value)
|
||||
);
|
||||
if (createScanProgressResult.IsFailure)
|
||||
return createScanProgressResult.Errors;
|
||||
|
||||
_scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value;
|
||||
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the the progress tracking of a media library scan.
|
||||
/// </summary>
|
||||
|
||||
+7
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the message queue for handling <see cref="IMediaLibraryScanJob"/> 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.
|
||||
/// </summary>
|
||||
public interface IMediaLibrariesScanQueue
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelWriter<IMediaLibraryScanJob> Writer { get; }
|
||||
ChannelWriter<MediaLibraryScanCompositeId> Writer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelReader<IMediaLibraryScanJob> Reader { get; }
|
||||
ChannelReader<MediaLibraryScanCompositeId> Reader { get; }
|
||||
}
|
||||
+5
-2
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
|
||||
/// <returns>A media library scanner for the specified media library type.</returns>
|
||||
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a media library scanner for the specified media library type, or an error.
|
||||
/// </returns>
|
||||
Result<IMediaTypeScanner> CreateLibraryScanner(LibraryType libraryType);
|
||||
}
|
||||
+3
-4
@@ -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; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId);
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId);
|
||||
}
|
||||
+11
-41
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>A media library scanner for the specified library type.</returns>
|
||||
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a media library scanner for the specified media library type, or an error.
|
||||
/// </returns>
|
||||
public Result<IMediaTypeScanner> CreateLibraryScanner(LibraryType libraryType)
|
||||
{
|
||||
return libraryType switch
|
||||
{
|
||||
// Implemented scanners.
|
||||
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
|
||||
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<IMusicLibraryTypeScanner>(),
|
||||
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<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IBookLibraryTypeScanner>()),
|
||||
LibraryType.Music => Result.From<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IMusicLibraryTypeScanner>()),
|
||||
// Every other media library type is modeled, but has no scanner yet, so scanning it is reported as unsupported.
|
||||
_ => Errors.LibraryScanning.NoScannerForLibraryType
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -107,7 +107,8 @@ public sealed class MediaLibraryScanProgress : ValueObject
|
||||
LibraryScanJobStatus status,
|
||||
Optional<MediaLibraryScanJobProgress> 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;
|
||||
|
||||
+1
-1
@@ -5,6 +5,6 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering books file system items.
|
||||
/// </summary>
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob
|
||||
{
|
||||
}
|
||||
+8
-9
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
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<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(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;
|
||||
}
|
||||
}
|
||||
@@ -112,7 +112,7 @@ public static class InfrastructureLayerServices
|
||||
// Media library scanning.
|
||||
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
||||
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
||||
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
|
||||
services.AddHostedService<MediaLibraryScanProcessorJob>();
|
||||
|
||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMusicFileSystemDiscoveryJob, MusicFileSystemDiscoveryJob>();
|
||||
|
||||
+90
-94
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
|
||||
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> 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<Library> 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<string, DirectoryScanFingerprintEntity>? 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
|
||||
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Success> 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<LibraryEntity?> 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<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> 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<string, DirectoryScanFingerprintEntity>? 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<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Success> 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<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> 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<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> 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<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> 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)
|
||||
|
||||
+76
-80
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<LibraryEntity?> 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<Library> 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<ILibraryPathTemplateService>()!;
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
Result<LibraryPathTemplate> 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<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
IReadOnlyList<string> paths = getPathsResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> 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<MusicLibraryScanItemMetadataEntity> 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
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<LibraryEntity?> 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<Library> 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<ILibraryPathTemplateService>()!;
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
Result<LibraryPathTemplate> 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<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
IReadOnlyList<string> paths = getPathsResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> 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<MusicLibraryScanItemMetadataEntity> 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<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
Result<Success> 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<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
@@ -154,16 +126,40 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
|
||||
Result<Success> 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<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
Result<Success> 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)
|
||||
|
||||
+27
-31
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<LibraryEntity?> 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<LibraryEntity?> 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<IMediaLibraryScanArtworkEnricher>()
|
||||
.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<IMediaLibraryScanArtworkEnricher>()
|
||||
.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)
|
||||
|
||||
+27
-31
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
|
||||
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<Success> 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<Success> 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<Updated> 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<Updated> 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)
|
||||
|
||||
+73
-77
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Count the files that need hashing, for progress reporting purposes.
|
||||
Result<int> 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<LibraryEntity?> 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<IFileHashService>()!;
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> 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<int> 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<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFileDto> 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<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () =>
|
||||
{
|
||||
Result<LibraryEntity?> 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<Success> 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<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFileDto> 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<HashedFileSystemFileDto> 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<Updated> 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<Updated> 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)
|
||||
|
||||
+27
-31
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<LibraryEntity?> 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<LibraryEntity?> 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<IMediaLibraryScanMetadataEnricher>()
|
||||
.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<IMediaLibraryScanMetadataEnricher>()
|
||||
.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)
|
||||
|
||||
+97
-101
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<Success> 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<LibraryEntity?> 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<IMediaLibraryScanItemMaterializer>()
|
||||
.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<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<Success> 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<LibraryEntity?> 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<IMediaLibraryScanItemMaterializer>()
|
||||
.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<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<UserSettingsEntity?> 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<UserSettingsEntity?> 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<Updated> 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<Updated> 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<Updated> 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<Updated> 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<Updated> 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<Updated> 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<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
Result<Success> 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)
|
||||
|
||||
+80
-84
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Load the media library, whose type determines the materializer used to create the media library items.
|
||||
Result<LibraryEntity?> 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<IMediaLibraryScanItemMaterializer>()
|
||||
.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<Success> 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<IReadOnlyList<string>> 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<IReadOnlyList<string>> 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<Updated> 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<Updated> 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<LibraryEntity?> 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<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
|
||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (materializer is null)
|
||||
throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'.");
|
||||
Result<Success> 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<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
Result<Success> 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<IReadOnlyList<string>> 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<Deleted> 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<IReadOnlyList<string>> 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<Updated> 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<Updated> 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<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
|
||||
Result<Success> materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (materializeItemsResult.IsFailure)
|
||||
throw new InvalidOperationException(materializeItemsResult.FirstError.Description);
|
||||
|
||||
Result<Success> 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<Deleted> 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)
|
||||
|
||||
+87
-91
@@ -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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> 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<Library> 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<string, DirectoryScanFingerprintEntity>? 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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Success> 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<LibraryEntity?> 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<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> 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<string, DirectoryScanFingerprintEntity>? 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<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Success> 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<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> 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<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> 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<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> 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)
|
||||
|
||||
+23
-2
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the cancellation of a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that was cancelled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return;
|
||||
Result<MediaLibraryScanProgress> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the debouncer that was used in a scan identified by <paramref name="mediaLibraryScanCompositeId"/>, that is now completed.
|
||||
/// </summary>
|
||||
|
||||
+7
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Provides an in-memory message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Provides an in-memory message queue for handling the media library scans that are waiting to execute.
|
||||
/// </summary>
|
||||
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
|
||||
{
|
||||
private readonly Channel<IMediaLibraryScanJob> _channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
|
||||
private readonly Channel<MediaLibraryScanCompositeId> _channel = Channel.CreateUnbounded<MediaLibraryScanCompositeId>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelWriter<IMediaLibraryScanJob> Writer => _channel.Writer;
|
||||
public ChannelWriter<MediaLibraryScanCompositeId> Writer => _channel.Writer;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelReader<IMediaLibraryScanJob> Reader => _channel.Reader;
|
||||
public ChannelReader<MediaLibraryScanCompositeId> Reader => _channel.Reader;
|
||||
}
|
||||
-53
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Background service for processing media library scan jobs from an in-memory message queue.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker)
|
||||
{
|
||||
_mediaScanQueue = mediaScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method called when the background service starts.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+181
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that executes the queued media library scans one at a time, in the order in which they were queued.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanProcessorJob : BackgroundService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanProcessorJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProcessorJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing the media library scans that are waiting to execute.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
|
||||
/// <param name="logger">Injected service for logging.</param>
|
||||
public MediaLibraryScanProcessorJob(
|
||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IServiceScopeFactory serviceScopeFactory,
|
||||
ILogger<MediaLibraryScanProcessorJob> logger)
|
||||
{
|
||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method called when the background service starts.
|
||||
/// </summary>
|
||||
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a single queued media library scan, from its preparation to the completion of its job graph.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">Model for tracking the queued media library scan.</param>
|
||||
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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<IUnitOfWork>();
|
||||
Result<LibraryScanEntity?> 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<LibraryScan> 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<IMediaLibraryScanningService>();
|
||||
Result<IMediaLibraryScanDiscoveryJob> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the failure of a single media library scan, without affecting the scans that are queued behind it.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">Model for tracking the failed media library scan.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan failed.</param>
|
||||
/// <param name="exception">The exception that describes the failure.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@ namespace Lumina.Infrastructure.Core.Security;
|
||||
/// </summary>
|
||||
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<XxHash64> 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<XxHash64> 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();
|
||||
|
||||
/// <summary>
|
||||
@@ -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) =>
|
||||
{
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ public class ScanLibrariesEndpointSummary : Summary<ScanLibrariesEndpoint, Empty
|
||||
public ScanLibrariesEndpointSummary()
|
||||
{
|
||||
Summary = "Triggers the scan of all media libraries.";
|
||||
Description = "Starts the scanning process of all media libraries of a user, or all libraries, if the user is an Admin.";
|
||||
Description = "Queues the scanning process of all media libraries of a user, or all libraries if the user is an Admin. The scans run one at a time, in the order in which they were queued.";
|
||||
|
||||
Response(200, "The media libraries scan was successfully started.",
|
||||
example: new MediaLibraryScanResponse[] {
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, ScanLibra
|
||||
public ScanLibraryEndpointSummary()
|
||||
{
|
||||
Summary = "Triggers the scan of a media library.";
|
||||
Description = "Starts the scanning process of a media library of a user.";
|
||||
Description = "Queues the scanning process of a media library of a user. Queued scans run one at a time.";
|
||||
|
||||
ExampleRequest = new ScanLibraryRequest(
|
||||
Id: Guid.NewGuid()
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels the running scans of all the media libraries.
|
||||
/// Cancels the running and queued scans of all the media libraries.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ public class CancelLibrariesScanEndpointSummary : Summary<CancelLibrariesScanEnd
|
||||
public CancelLibrariesScanEndpointSummary()
|
||||
{
|
||||
Summary = "Cancels the scan of all the media libraries.";
|
||||
Description = "Cancels the running scans of all the media libraries.";
|
||||
Description = "Cancels the running and queued scans of all the media libraries.";
|
||||
|
||||
Response(200, "The scan of all media libraries is cancelled.", example: new SuccessResponse(true));
|
||||
}
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ public class CancelLibraryScanEndpoint : BaseEndpoint<CancelLibraryScanRequest,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels a running scan of a media library.
|
||||
/// Cancels a running or queued scan of a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the media library and of the scan to cancel.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ public class CancelLibraryScanEndpointSummary : Summary<CancelLibraryScanEndpoin
|
||||
public CancelLibraryScanEndpointSummary()
|
||||
{
|
||||
Summary = "Cancels the scan of a media library.";
|
||||
Description = "Cancels a running scan of the media library identified by the route.";
|
||||
Description = "Cancels a running or queued scan of the media library identified by the route.";
|
||||
|
||||
RequestParam(r => 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.");
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ public class GetRunningLibraryScansEndpointSummary : Summary<GetRunningLibrarySc
|
||||
public GetRunningLibraryScansEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves the running media library scans.";
|
||||
Description = "Retrieves the collection of ongoing media library scans.";
|
||||
Description = "Retrieves the collection of ongoing media library scans, including the scans waiting in the scan queue.";
|
||||
|
||||
Response(200, "The collection of ongoing media library scans is returned.", example: new SuccessResponse<LibraryScanProgressDto[]>(true, default));
|
||||
}
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>إلغاء الفحص</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>جارٍ الإلغاء</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>كتاب هزلي</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>برنامج إذاعي</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>في قائمة الانتظار</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>ريمكس</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Scan Abbrechen</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Wird abgebrochen</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic-Heft</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radiosendung</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>In Warteschlange</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Neuabmischung</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancel Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelling</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic Book</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radio Show</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>Queued</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancelar Escaneo</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelando</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Cómic</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Programa de Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>En cola</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remezcla</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Annuler Le Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Annulation en cours</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Bande Dessinée</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Émission Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>En file d'attente</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remixage</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Annulla Scansione</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Annullamento in corso</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Fumetto</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Programma Radiofonico</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>In coda</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remissaggio</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>スキャンを中止</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>キャンセル中</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>漫画</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>ラジオ番組</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>待機中</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>リミックス</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancel Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelling</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic Book</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radio Show</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>Queued</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Anulează Scanarea</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Se anulează</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Bandă Desenată</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Emisiune Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>În așteptare</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Скасувати Сканування</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Скасування</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Комікс</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Радіопередача</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>У черзі</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Ремікс</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>取消扫描</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>正在取消</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>漫画</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>广播节目</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>排队中</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>混音版</value>
|
||||
</data>
|
||||
|
||||
@@ -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);
|
||||
|
||||
+6
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
@@ -24,18 +27,21 @@ public class LibraryScanQueuedDomainEventFixture
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the domain event.</param>
|
||||
/// <param name="scanId">Optional. The unique identifier of the queued media library scan.</param>
|
||||
/// <param name="userId">Optional. The unique identifier of the user that initiated the queued media library scan.</param>
|
||||
/// <param name="libraryId">Optional. The unique identifier of the library whose scan was queued.</param>
|
||||
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
|
||||
/// <returns>The created <see cref="LibraryScanQueuedDomainEvent"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
+134
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Controllable test double for the <see cref="IMediaLibraryScanDiscoveryJob"/> interface.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class FakeMediaLibraryScanDiscoveryJob : IMediaLibraryScanDiscoveryJob
|
||||
{
|
||||
private readonly TaskCompletionSource _executionStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly TaskCompletionSource _executionCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media library scan that this job is part of.
|
||||
/// </summary>
|
||||
public required ScanId ScanId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that initiated the media library scan that this job is part of.
|
||||
/// </summary>
|
||||
public required UserId UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier of the media library upon which the scan is performed.
|
||||
/// </summary>
|
||||
public required LibraryId LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of child media scan jobs that will be triggered when this job's payload completes execution.
|
||||
/// </summary>
|
||||
public List<IMediaLibraryScanJob> Children { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of parent media scan jobs that will trigger this job when their payload will complete execution.
|
||||
/// </summary>
|
||||
public List<IMediaLibraryScanJob> Parents { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status of the current media library scan job.
|
||||
/// </summary>
|
||||
public LibraryScanJobStatus Status { get; private set; } = LibraryScanJobStatus.Pending;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of times this job was executed.
|
||||
/// </summary>
|
||||
public int ExecutionCount { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this job is currently executing.
|
||||
/// </summary>
|
||||
public bool IsExecuting { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id this job was last executed with.
|
||||
/// </summary>
|
||||
public Guid? LastExecutionId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cancellation token this job was last executed with.
|
||||
/// </summary>
|
||||
public CancellationToken LastCancellationToken { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional callback invoked while the job executes, allowing a test to block or throw.
|
||||
/// </summary>
|
||||
public Func<CancellationToken, Task>? OnExecute { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a task that completes as soon as the job starts executing.
|
||||
/// </summary>
|
||||
public Task ExecutionStarted => _executionStarted.Task;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a task that completes as soon as the job finishes executing successfully.
|
||||
/// </summary>
|
||||
public Task ExecutionCompleted => _executionCompleted.Task;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="job">The child media library scan job to be added.</param>
|
||||
public void AddChild(IMediaLibraryScanJob job)
|
||||
{
|
||||
if (!Children.Contains(job) && !Parents.Contains(job))
|
||||
Children.Add(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="job">The child media library scan job to be added.</param>
|
||||
public void AddParent(IMediaLibraryScanJob job)
|
||||
{
|
||||
if (!Parents.Contains(job) && !Children.Contains(job))
|
||||
Parents.Add(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The id of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task ExecuteAsync<TInput>(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();
|
||||
}
|
||||
}
|
||||
+57
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="IMediaLibraryScanDiscoveryJob"/> interface.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanDiscoveryJobFixture
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a controllable <see cref="FakeMediaLibraryScanDiscoveryJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="scanId">Optional. The Id of the media library scan that the job is part of.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that initiated the media library scan.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that is scanned.</param>
|
||||
/// <param name="children">Optional. The child jobs of the created job.</param>
|
||||
/// <param name="onExecute">Optional. The callback invoked while the job executes.</param>
|
||||
/// <returns>The created <see cref="FakeMediaLibraryScanDiscoveryJob"/>.</returns>
|
||||
public FakeMediaLibraryScanDiscoveryJob Create(
|
||||
ScanId? scanId = null,
|
||||
UserId? userId = null,
|
||||
LibraryId? libraryId = null,
|
||||
List<IMediaLibraryScanJob>? children = null,
|
||||
Func<CancellationToken, Task>? 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;
|
||||
}
|
||||
}
|
||||
+35
-16
@@ -52,7 +52,7 @@ public class CancelLibrariesScanCommandHandlerTests
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_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<CancellationToken>()).Returns(true);
|
||||
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
||||
@@ -62,15 +62,15 @@ public class CancelLibrariesScanCommandHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllRunningScans()
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllActiveScans()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryScanEntity> runningScans =
|
||||
List<LibraryScanEntity> activeScans =
|
||||
[
|
||||
_libraryScanEntityFixture.Create(userId: _userId),
|
||||
_libraryScanEntityFixture.Create(userId: _userId)
|
||||
];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||
@@ -83,17 +83,36 @@ public class CancelLibrariesScanCommandHandlerTests
|
||||
_mockDomainEventsQueue.Received(2).Enqueue(Arg.Any<LibraryScanCancelledDomainEvent>());
|
||||
}
|
||||
|
||||
[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<LibraryScanEntity> activeScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Pending)];
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockLibraryScanRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<LibraryScanEntity>(libraryScan => libraryScan.Status == LibraryScanJobStatus.Canceled),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<LibraryScanCancelledDomainEvent>(domainEvent => domainEvent.ScanId.Value == activeScans[0].Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyCancelScansOwnedByTheUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
List<LibraryScanEntity> runningScans =
|
||||
List<LibraryScanEntity> activeScans =
|
||||
[
|
||||
_libraryScanEntityFixture.Create(userId: _userId),
|
||||
_libraryScanEntityFixture.Create(userId: otherUserId)
|
||||
];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).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<CancellationToken>());
|
||||
await _mockLibraryScanRepository.DidNotReceive().GetActiveScansAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError()
|
||||
public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get running scans"));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get active scans"));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||
@@ -141,8 +160,8 @@ public class CancelLibrariesScanCommandHandlerTests
|
||||
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId)];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
List<LibraryScanEntity> activeScans = [_libraryScanEntityFixture.Create(userId: _userId)];
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
||||
.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<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
List<LibraryScanEntity> activeScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)];
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
|
||||
// Act
|
||||
Result<Success> 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<LibraryScanEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
+25
-3
@@ -58,7 +58,7 @@ public class CancelLibraryScanCommandHandlerTests
|
||||
_mockValidator = Substitute.For<IValidator<CancelLibraryScanCommand>>();
|
||||
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -89,6 +89,28 @@ public class CancelLibraryScanCommandHandlerTests
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibraryScanCancelledDomainEvent>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(pendingScan));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockLibraryScanRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<LibraryScanEntity>(libraryScan => libraryScan.Status == LibraryScanJobStatus.Canceled),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibraryScanCancelledDomainEvent>());
|
||||
}
|
||||
|
||||
[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<LibraryScanEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
+46
-7
@@ -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<IMediaLibraryScanningService>();
|
||||
_mockMediaLibrariesScanProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
_mockMediaLibraryScanProgressNotifier = Substitute.For<IMediaLibraryScanProgressNotifier>();
|
||||
_mockMediaLibrariesScanCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
|
||||
// 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<LibraryScan>()).Returns(Result.Success);
|
||||
_mockMediaLibraryScanProgressNotifier.SendLibraryScanCancelledEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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 => libraryScan.Id.Value == scan.Id));
|
||||
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
await _mockMediaLibraryScanProgressNotifier.Received(1).SendLibraryScanCancelledEventAsync(
|
||||
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId.Value == scan.UserId),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(
|
||||
Arg.Is<MediaLibraryScanCompositeId>(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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(scan));
|
||||
List<string> cleanupSteps = [];
|
||||
_mockMediaLibraryScanProgressNotifier
|
||||
.When(notifier => notifier.SendLibraryScanCancelledEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>()))
|
||||
.Do(_ => cleanupSteps.Add("notifyClients"));
|
||||
_mockMediaLibrariesScanCancellationTracker
|
||||
.When(tracker => tracker.RemoveScan(Arg.Any<MediaLibraryScanCompositeId>()))
|
||||
.Do(_ => cleanupSteps.Add("removeCancellationToken"));
|
||||
_mockLibraryScanSnapshotRepository
|
||||
.When(repository => repository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()))
|
||||
.Do(_ => cleanupSteps.Add("rollbackSnapshot"));
|
||||
_mockLibraryScanStagingResultsRepository
|
||||
.When(repository => repository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()))
|
||||
.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<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -123,6 +160,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError);
|
||||
await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -145,6 +183,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
|
||||
_mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
|
||||
+40
-65
@@ -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<MediaLibraryScanCompositeId> _channel;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryScanQueuedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
|
||||
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
|
||||
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_channel = Channel.CreateUnbounded<MediaLibraryScanCompositeId>();
|
||||
_mockScanQueue = Substitute.For<IMediaLibrariesScanQueue>();
|
||||
_mockScanQueue.Writer.Returns(_channel.Writer);
|
||||
_mockScanQueue.Reader.Returns(_channel.Reader);
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
|
||||
// default stubs: the scanning service starts the scan successfully
|
||||
_mockMediaLibraryScanningService.StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
// Default stubs: the queued scan progress is initialized successfully.
|
||||
_mockProgressTracker.InitializeQueuedScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>())
|
||||
.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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(scan));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == scan.Id),
|
||||
scan.Library.LibraryType,
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockCancellationTracker.Received(1).RegisterScan(
|
||||
Arg.Is<MediaLibraryScanCompositeId>(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<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
_mockProgressTracker.Received(1).InitializeQueuedScanProgress(
|
||||
domainEvent.LibraryId,
|
||||
Arg.Is<MediaLibraryScanCompositeId>(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<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryScanEntity?>.Success(null));
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _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<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(scan));
|
||||
Error error = Error.Failure(description: "Failed to start scan");
|
||||
_mockMediaLibraryScanningService.StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
// 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<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
_mockProgressTracker.DidNotReceive().UpdateScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockProgressTracker.DidNotReceive().UpdateScanJobProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<MediaLibraryScanJobProgress>());
|
||||
}
|
||||
}
|
||||
+53
-15
@@ -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<IMediaLibrariesScanProgressTracker>();
|
||||
_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<CancellationToken>()).Returns(true);
|
||||
_mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>())
|
||||
@@ -72,15 +73,15 @@ public class GetRunningLibraryScansQueryHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllRunningScans()
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllActiveScans()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryScanEntity> runningScans =
|
||||
List<LibraryScanEntity> activeScans =
|
||||
[
|
||||
_libraryScanEntityFixture.Create(userId: _userId),
|
||||
_libraryScanEntityFixture.Create(userId: Guid.NewGuid())
|
||||
];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
||||
@@ -94,12 +95,12 @@ public class GetRunningLibraryScansQueryHandlerTests
|
||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnProgressOnlyForScansOwnedByTheUser()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryScanEntity> runningScans =
|
||||
List<LibraryScanEntity> activeScans =
|
||||
[
|
||||
_libraryScanEntityFixture.Create(userId: _userId),
|
||||
_libraryScanEntityFixture.Create(userId: Guid.NewGuid())
|
||||
];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).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<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([pendingScan]));
|
||||
_mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>())
|
||||
.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<IEnumerable<MediaLibraryScanProgressResponse>> 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<CancellationToken>());
|
||||
await _mockLibraryScanRepository.DidNotReceive().GetActiveScansAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError()
|
||||
public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get running scans"));
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get active scans"));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> 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<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId)];
|
||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
||||
List<LibraryScanEntity> activeScans =
|
||||
[
|
||||
_libraryScanEntityFixture.Create(userId: _userId),
|
||||
_libraryScanEntityFixture.Create(userId: _userId)
|
||||
];
|
||||
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(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<MediaLibraryScanCompositeId>())
|
||||
.Returns(Error.Failure(description: "Failed to get scan progress"));
|
||||
.Returns(Result.From(releasedProgress), Error.Failure(description: "The scan progress was already released"));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
}
|
||||
}
|
||||
+9
-6
@@ -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<IEnumerable<LibraryScanEntity>> result = await _sut.GetRunningScansAsync(CancellationToken.None);
|
||||
Result<IEnumerable<LibraryScanEntity>> 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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
+79
-4
@@ -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<IMediaLibraryScanJob> rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)];
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
IMediaLibraryScanJob rootJob = Assert.Single(rootJobs);
|
||||
Assert.Same(discoveryJob, rootJob);
|
||||
Assert.IsAssignableFrom<IMusicFileSystemDiscoveryJob>(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<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldReturnTheFileSystemDiscoveryJobAsTheOnlyRoot()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMusicMetadataExtractionJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
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<IMusicFileSystemDiscoveryJob>();
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob metadataExtractionJob = CreateJob<IMusicMetadataExtractionJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
HashSet<IMediaLibraryScanJob> 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<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||
@@ -108,6 +162,27 @@ public class MusicLibraryTypeScannerTests
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects every job that is reachable from <paramref name="rootJob"/> through the child relationships.
|
||||
/// </summary>
|
||||
/// <param name="rootJob">The root job of the job graph.</param>
|
||||
/// <returns>The set of reachable jobs.</returns>
|
||||
private static HashSet<IMediaLibraryScanJob> GetReachableJobs(IMediaLibraryScanJob rootJob)
|
||||
{
|
||||
HashSet<IMediaLibraryScanJob> reachableJobs = [];
|
||||
Queue<IMediaLibraryScanJob> 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<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
{
|
||||
TestScanJob job = new()
|
||||
|
||||
+6
-1
@@ -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<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
|
||||
+29
-26
@@ -96,6 +96,7 @@ public class LibraryScanTests
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
||||
LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType<LibraryScanQueuedDomainEvent>(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<Success> 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<Success> 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);
|
||||
}
|
||||
}
|
||||
+140
-59
@@ -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<IMediaLibraryScanJob> _channel;
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanningServiceTests()
|
||||
{
|
||||
_channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
|
||||
_mockScanQueue = Substitute.For<IMediaLibrariesScanQueue>();
|
||||
_mockScanQueue.Writer.Returns(_channel.Writer);
|
||||
_mockScanQueue.Reader.Returns(_channel.Reader);
|
||||
_mockScannerFactory = Substitute.For<IMediaLibraryScannerFactory>();
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>()).Returns(CancellationToken.None);
|
||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>()).Returns(Result.Created);
|
||||
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
|
||||
.Returns(Result.Created);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_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<Success> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
Result<IMediaLibraryScanDiscoveryJob> 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<LibraryScanStartedDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
_mockCancellationTracker.Received(1).RegisterScan(Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId));
|
||||
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), 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<Success> 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<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanStartedDomainEvent)
|
||||
&& ((LibraryScanStartedDomainEvent)domainEvent).LibraryScan == scan),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<MediaLibraryScanCompositeId>(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<MediaLibraryScanCompositeId>(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<IMediaLibraryScanDiscoveryJob> 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<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
_mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
Assert.False(_channel.Reader.TryRead(out _));
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<IMediaLibraryScanDiscoveryJob> 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<MediaLibraryScanCompositeId>());
|
||||
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenProgressInitializationFails_ShouldReturnErrorWithoutPublishingEvents()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).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<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
Result<IMediaLibraryScanDiscoveryJob> 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<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
Assert.False(_channel.Reader.TryRead(out _));
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<Success> 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<MediaLibraryScanCompositeId>(), totalJobs: 3);
|
||||
Assert.Equal(2, CountEnqueuedJobs());
|
||||
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), totalJobs: 4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -180,15 +261,16 @@ public class MediaLibraryScanningServiceTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked <see cref="IMediaTypeScanner"/> and registers it with the mocked scanner factory.
|
||||
/// Registers a mocked media library scanner that returns <paramref name="rootJob"/> with the mocked scanner factory.
|
||||
/// </summary>
|
||||
/// <param name="jobs">The scan jobs the scanner returns when asked to create scan jobs for a library.</param>
|
||||
/// <param name="libraryType">The media library type that the scanner is registered for.</param>
|
||||
/// <param name="rootJob">The file system discovery job returned by the scanner.</param>
|
||||
/// <returns>The created mocked scanner.</returns>
|
||||
private IMediaTypeScanner CreateScanner(List<IMediaLibraryScanJob> jobs)
|
||||
private IMediaTypeScanner RegisterScanner(LibraryType libraryType, IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(jobs);
|
||||
_mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner);
|
||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(rootJob);
|
||||
_mockScannerFactory.CreateLibraryScanner(libraryType).Returns(Result.From(scanner));
|
||||
return scanner;
|
||||
}
|
||||
|
||||
@@ -205,14 +287,13 @@ public class MediaLibraryScanningServiceTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts and drains the scan jobs currently enqueued on the scan queue channel.
|
||||
/// Asserts that the scan identity of the scan was propagated to <paramref name="job"/>.
|
||||
/// </summary>
|
||||
/// <returns>The number of enqueued scan jobs.</returns>
|
||||
private int CountEnqueuedJobs()
|
||||
/// <param name="job">The job whose scan properties are asserted.</param>
|
||||
/// <param name="scan">The media library scan that owns the job.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+47
-2
@@ -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<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Result<MediaLibraryScanProgress> 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<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Result<MediaLibraryScanProgress> 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<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 0);
|
||||
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: -1);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
|
||||
+94
-66
@@ -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 <see cref="MediaLibraryScannerFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScannerFactoryTests
|
||||
public class MediaLibraryScannerFactoryTests : IDisposable
|
||||
{
|
||||
private readonly IBookLibraryTypeScanner _mockBookLibraryTypeScanner;
|
||||
private readonly IMusicLibraryTypeScanner _mockMusicLibraryTypeScanner;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly MediaLibraryScannerFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScannerFactoryTests()
|
||||
{
|
||||
_mockBookLibraryTypeScanner = Substitute.For<IBookLibraryTypeScanner>();
|
||||
_mockMusicLibraryTypeScanner = Substitute.For<IMusicLibraryTypeScanner>();
|
||||
|
||||
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<IBookLibraryTypeScanner>();
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(expectedScanner);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
MediaLibraryScannerFactory sut = new(serviceProvider);
|
||||
|
||||
// Act
|
||||
IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Book);
|
||||
Result<IMediaTypeScanner> 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<IMusicLibraryTypeScanner>();
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(expectedScanner);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
MediaLibraryScannerFactory sut = new(serviceProvider);
|
||||
|
||||
// Act
|
||||
IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music);
|
||||
Result<IMediaTypeScanner> 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<IMediaTypeScanner> result = _sut.CreateLibraryScanner(libraryType);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => sut.CreateLibraryScanner(libraryType));
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.IsType<NotImplementedError>(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<ArgumentOutOfRangeException>(() => sut.CreateLibraryScanner((LibraryType)999));
|
||||
// Assert
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldReturnNoScannerError()
|
||||
{
|
||||
// Act
|
||||
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner((LibraryType)999);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.IsType<NotImplementedError>(result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the test dependencies.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_serviceProvider.Dispose();
|
||||
}
|
||||
}
|
||||
+45
-5
@@ -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<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
@@ -80,10 +78,52 @@ public class MediaLibraryScanProgressTests
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: totalJobs,
|
||||
totalJobs: 0,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.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<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: -1,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.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<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: 0,
|
||||
status,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
||||
|
||||
+76
-4
@@ -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<IMediaLibraryScanJob> rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)];
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
IMediaLibraryScanJob rootJob = Assert.Single(rootJobs);
|
||||
Assert.Same(discoveryJob, rootJob);
|
||||
Assert.IsAssignableFrom<IBooksFileSystemDiscoveryJob>(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<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldReturnTheFileSystemDiscoveryJobAsTheOnlyRoot()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IBooksFileSystemDiscoveryJob>();
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
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<IBooksFileSystemDiscoveryJob>();
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
HashSet<IMediaLibraryScanJob> 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<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
@@ -102,6 +153,27 @@ public class BookLibraryTypeScannerTests
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects every job that is reachable from <paramref name="rootJob"/> through the child relationships.
|
||||
/// </summary>
|
||||
/// <param name="rootJob">The root job of the job graph.</param>
|
||||
/// <returns>The set of reachable jobs.</returns>
|
||||
private static HashSet<IMediaLibraryScanJob> GetReachableJobs(IMediaLibraryScanJob rootJob)
|
||||
{
|
||||
HashSet<IMediaLibraryScanJob> reachableJobs = [];
|
||||
Queue<IMediaLibraryScanJob> 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<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
{
|
||||
TestScanJob job = new()
|
||||
|
||||
+56
@@ -201,6 +201,62 @@ public class DebouncedMediaLibraryScanProgressNotifierTests
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[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<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Canceled.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer()
|
||||
{
|
||||
|
||||
+37
-16
@@ -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<IMediaLibraryScanJob>();
|
||||
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>();
|
||||
IMediaLibraryScanJob secondJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
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<MediaLibraryScanCompositeId> readTask = _sut.Reader.ReadAsync(CancellationToken.None).AsTask();
|
||||
_sut.Writer.TryWrite(scanId);
|
||||
|
||||
// Assert
|
||||
MediaLibraryScanCompositeId readScanId = await readTask;
|
||||
Assert.Equal(scanId, readScanId);
|
||||
}
|
||||
}
|
||||
-146
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanJobProcessorJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanJobProcessorJobTests
|
||||
{
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanJobProcessorJobTests()
|
||||
{
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenJobIsEnqueued_ShouldExecuteTheJobWithLinkedCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanQueue queue = new();
|
||||
MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker);
|
||||
RecordingScanJob job = CreateRecordingScanJob();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>())
|
||||
.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<MediaLibraryScanCompositeId>(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<MediaLibraryScanCompositeId>())
|
||||
.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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a recording scan job with a random scan and user identity.
|
||||
/// </summary>
|
||||
/// <returns>The created recording scan job.</returns>
|
||||
private RecordingScanJob CreateRecordingScanJob()
|
||||
{
|
||||
return new RecordingScanJob
|
||||
{
|
||||
ScanId = _scanIdFixture.Create(),
|
||||
UserId = _userIdFixture.Create(),
|
||||
LibraryId = _libraryIdFixture.Create()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test double for <see cref="IMediaLibraryScanJob"/> that records the token it was executed with.
|
||||
/// </summary>
|
||||
private sealed class RecordingScanJob : IMediaLibraryScanJob
|
||||
{
|
||||
private readonly TaskCompletionSource<bool> _executed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public required ScanId ScanId { get; set; }
|
||||
|
||||
public required UserId UserId { get; set; }
|
||||
|
||||
public required LibraryId LibraryId { get; set; }
|
||||
|
||||
public List<IMediaLibraryScanJob> Children { get; } = [];
|
||||
|
||||
public List<IMediaLibraryScanJob> 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<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
WasExecuted = true;
|
||||
ReceivedCancellationToken = cancellationToken;
|
||||
_executed.TrySetResult(true);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+317
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProcessorJob"/> class.
|
||||
/// </summary>
|
||||
[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<MediaLibraryScanProcessorJob> _mockLogger;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly MediaLibraryScanProcessorJob _sut;
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProcessorJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanProcessorJobTests()
|
||||
{
|
||||
_queue = new MediaLibrariesScanQueue();
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>()).Returns(CancellationToken.None);
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
|
||||
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
|
||||
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProcessorJob>>();
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockMediaLibraryScanningService);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MediaLibraryScanProcessorJob(
|
||||
_queue,
|
||||
_mockCancellationTracker,
|
||||
_serviceProvider.GetRequiredService<IServiceScopeFactory>(),
|
||||
_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<bool> releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
List<Guid> 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 => libraryScan.Id.Value == completedScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
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<bool>(),
|
||||
false,
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == cancelledScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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 => libraryScan.Id.Value == failingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.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<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
|
||||
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
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<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
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<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
|
||||
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(1, pendingRootJob.ExecutionCount);
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a media library scan with the given status in the mocked repository.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">The composite identifier of the scan to register.</param>
|
||||
/// <param name="status">The status of the media library scan.</param>
|
||||
/// <returns>The created media library scan entity.</returns>
|
||||
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<bool>(), false, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(scan));
|
||||
return scan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the file system discovery job that the mocked scanning service prepares for a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">The composite identifier of the scan that owns the job.</param>
|
||||
/// <param name="rootJob">The root job to return when the scan is prepared.</param>
|
||||
private void RegisterRootJob(MediaLibraryScanCompositeId compositeId, IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
_mockMediaLibraryScanningService.StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == compositeId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(rootJob));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the test dependencies.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_serviceProvider.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user