mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +00:00
Serializes media library scans through a scan queue
Replaces the job queue with a scan queue that executes one media library scan at a time, in the order in which the scans were queued, so several libraries requested at once no longer run one complete job chain each on the thread pool shared with the web server. Keeps queued scans Pending and cancellable, reports them as queued, and cancels the executing scan and the queued ones when the user cancels all scans. A media library type without a scanner now fails its own scan instead of leaving it stuck Pending, without stopping the scans queued behind it. Makes the file system discovery job the only top level job of a scan graph, so awaiting it completes the whole scan, and leaves one logical processor free for the rest of the process while discovery and hashing read files in parallel. Removes the per job Task.Run wrappers, links the scan cancellation with the host shutdown token in the scan processor, updates the ADR amendments, API documentation, manual, web client and tests, and normalizes the comments of the touched files.
This commit is contained in:
1 parent
b0c24a1722
commit
8ff5149b6e
85 files changed
+2559
-1394
No files matched your search
@@ -116,17 +116,17 @@ The template is read on every scan, so changing it changes how your folders are
|
|||||||
|
|
||||||
## Scanning a library
|
## 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.
|
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.
|
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
|
## Editing a library
|
||||||
|
|
||||||
|
|||||||
@@ -368,10 +368,27 @@ GET api/v1/libraries/scans/running
|
|||||||
},
|
},
|
||||||
"status": "Running",
|
"status": "Running",
|
||||||
"overallProgressPercentage": 40.0
|
"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
|
||||||
|
|
||||||
#### Get Library Scan Progress Request
|
#### 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
|
## 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.
|
**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.
|
||||||
+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.
|
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.
|
**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.
|
||||||
+2
-2
@@ -28,11 +28,11 @@ public interface ILibraryScanRepository : IRepository<LibraryScanEntity>,
|
|||||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
Task<Result<IEnumerable<LibraryScanEntity>>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <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>
|
/// <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>
|
/// <summary>
|
||||||
/// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still
|
/// 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;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Guid userId = currentUserId.Value;
|
Guid userId = currentUserId.Value;
|
||||||
|
|
||||||
// Get the running library scans of the current user from the repository.
|
// Get the scans of the current user that are either executing or still waiting in the scan queue, from the repository.
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> getActiveLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getRunningLibraryScansResult.IsFailure)
|
if (getActiveLibraryScansResult.IsFailure)
|
||||||
return getRunningLibraryScansResult.Errors;
|
return getActiveLibraryScansResult.Errors;
|
||||||
|
|
||||||
// Filter the library scans to process.
|
// Filter the library scans to process.
|
||||||
List<LibraryScanEntity> authorizedLibraryScans = [];
|
List<LibraryScanEntity> authorizedLibraryScans = [];
|
||||||
// Admins can see all library scans.
|
// Admins can see all library scans.
|
||||||
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
|
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.
|
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.
|
// Convert persistence library scans to domain entities.
|
||||||
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
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.Repositories.MediaLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
|
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||||
using Lumina.Domain.Common.Errors;
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Common.Exceptions;
|
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.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
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.Cancellation;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -27,7 +27,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
{
|
{
|
||||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
private readonly IMediaLibraryScanProgressNotifier _mediaLibraryScanProgressNotifier;
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -35,17 +35,17 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</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>
|
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||||
public LibraryScanCancelledDomainEventHandler(
|
public LibraryScanCancelledDomainEventHandler(
|
||||||
IMediaLibraryScanningService mediaLibraryScanningService,
|
IMediaLibraryScanningService mediaLibraryScanningService,
|
||||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
IMediaLibraryScanProgressNotifier mediaLibraryScanProgressNotifier,
|
||||||
IUnitOfWork unitOfWork)
|
IUnitOfWork unitOfWork)
|
||||||
{
|
{
|
||||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
_mediaLibraryScanProgressNotifier = mediaLibraryScanProgressNotifier;
|
||||||
_unitOfWork = unitOfWork;
|
_unitOfWork = unitOfWork;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,10 +73,13 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
|||||||
if (cancelScanResult.IsFailure)
|
if (cancelScanResult.IsFailure)
|
||||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||||
|
|
||||||
// Release the scan processing resources.
|
|
||||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
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);
|
_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.
|
// 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
|
// 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.
|
// 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 =====================================================================================
|
#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.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.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;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -21,22 +16,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibraryScanQueuedDomainEvent>
|
public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibraryScanQueuedDomainEvent>
|
||||||
{
|
{
|
||||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandler"/> class.
|
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandler"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing the media library scans that are waiting to execute.</param>
|
||||||
/// <param name="domainEventsQueue">Injected unit of work for interacting with the data access layer repositories.</param>
|
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
public LibraryScanQueuedDomainEventHandler(
|
||||||
public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork)
|
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||||
|
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||||
|
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
|
||||||
{
|
{
|
||||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||||
_domainEventsQueue = domainEventsQueue;
|
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||||
_unitOfWork = unitOfWork;
|
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -46,26 +43,18 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
|
|||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// Get the library scan that was queued, from the repository.
|
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId);
|
||||||
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);
|
|
||||||
|
|
||||||
// Convert the repository entity to a domain entity.
|
// Register the scan for cancellation before it is queued, so that a cancellation that arrives while the scan is still
|
||||||
Result<LibraryScan> libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity();
|
// waiting for its turn is honored when the scan processor finally picks it up.
|
||||||
if (libraryScanDomainResult.IsFailure)
|
_mediaLibrariesScanCancellationTracker.RegisterScan(compositeId);
|
||||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
|
||||||
|
|
||||||
// Start the media library scan.
|
// Report the scan as queued, so clients can show it while it waits for the scans ahead of it to finish.
|
||||||
Result<Success> startScanResult = await _mediaLibraryScanningService.StartScanAsync(
|
// This is only a display concern, so it must never prevent the scan from being queued.
|
||||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false);
|
_ = _mediaLibrariesScanProgressTracker.InitializeQueuedScanProgress(domainEvent.LibraryId, compositeId);
|
||||||
if (startScanResult.IsFailure)
|
|
||||||
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
|
|
||||||
|
|
||||||
// Queue any domain events.
|
// Only the scan itself is queued, not its jobs. The scan processor prepares and executes the jobs of one scan at a time,
|
||||||
foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents())
|
// so the scans run consecutively, in the order in which they were queued.
|
||||||
_domainEventsQueue.Enqueue(queuedDomainEvent);
|
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="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>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken);
|
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;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Guid userId = currentUserId.Value;
|
Guid userId = currentUserId.Value;
|
||||||
|
|
||||||
// Get the ongoing library scans from the repository.
|
// Get the library scans that are executing or still waiting in the scan queue, from the repository.
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> getActiveScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getRunningScansResult.IsFailure)
|
if (getActiveScansResult.IsFailure)
|
||||||
return getRunningScansResult.Errors;
|
return getActiveScansResult.Errors;
|
||||||
|
|
||||||
// Filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own.
|
// 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))
|
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
|
||||||
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
|
userActiveRepositoryLibraryScans = [.. getActiveScansResult.Value];
|
||||||
else
|
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.
|
// For each of the filtered library scans, get their progress.
|
||||||
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
||||||
IEnumerable<Result<LibraryScan>> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities();
|
IEnumerable<Result<LibraryScan>> userActiveDomainLibraryScans = userActiveRepositoryLibraryScans.ToDomainEntities();
|
||||||
foreach (Result<LibraryScan> userRunningDomainLibraryScan in userRunningDomainLibraryScans)
|
foreach (Result<LibraryScan> userActiveDomainLibraryScan in userActiveDomainLibraryScans)
|
||||||
{
|
{
|
||||||
if (userRunningDomainLibraryScan.IsFailure)
|
if (userActiveDomainLibraryScan.IsFailure)
|
||||||
return userRunningDomainLibraryScan.Errors;
|
return userActiveDomainLibraryScan.Errors;
|
||||||
else
|
|
||||||
{
|
Result<MediaLibraryScanProgress> getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
|
||||||
Result<MediaLibraryScanProgress> getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
|
MediaLibraryScanCompositeId.Create(userActiveDomainLibraryScan.Value.Id, userActiveDomainLibraryScan.Value.UserId));
|
||||||
MediaLibraryScanCompositeId.Create(userRunningDomainLibraryScan.Value.Id, userRunningDomainLibraryScan.Value.UserId));
|
// A scan whose progress was already released has ended, so it is not reported as active any more.
|
||||||
if (getLibraryScanProgressResult.IsFailure)
|
if (getLibraryScanProgressResult.IsFailure)
|
||||||
return getLibraryScanProgressResult.Errors;
|
continue;
|
||||||
libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse());
|
|
||||||
}
|
libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse());
|
||||||
}
|
}
|
||||||
|
|
||||||
return Result.From(libraryScanProgresses.AsEnumerable());
|
return Result.From(libraryScanProgresses.AsEnumerable());
|
||||||
|
|||||||
@@ -96,6 +96,9 @@ internal sealed class LibraryRepository : ILibraryRepository
|
|||||||
.Include(library => library.PathTemplateParts)
|
.Include(library => library.PathTemplateParts)
|
||||||
.AsSplitQuery()
|
.AsSplitQuery()
|
||||||
.Where(library => library.IsEnabled && !library.IsLocked)
|
.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);
|
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -83,16 +83,17 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <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>
|
/// <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
|
return await _luminaDbContext.LibraryScans
|
||||||
.Include(library => library.Library)
|
.Include(library => library.Library)
|
||||||
.AsSplitQuery()
|
.AsSplitQuery()
|
||||||
.Where(library => library.Status == LibraryScanJobStatus.Running)
|
.Where(library => library.Status == LibraryScanJobStatus.Pending || library.Status == LibraryScanJobStatus.Running)
|
||||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
.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 LibraryScanIdCannotBeEmpty => Error.Validation(description: nameof(LibraryScanIdCannotBeEmpty));
|
||||||
public static Error CanOnlyStartPendingScans => Error.Forbidden(description: nameof(CanOnlyStartPendingScans));
|
public static Error CanOnlyStartPendingScans => Error.Forbidden(description: nameof(CanOnlyStartPendingScans));
|
||||||
public static Error CanOnlyCompleteRunningScans => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScans));
|
public static Error CanOnlyCompleteRunningScans => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScans));
|
||||||
public static Error CanOnlyCancelRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelRunningScans));
|
public static Error CanOnlyCancelPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelPendingOrRunningScans));
|
||||||
public static Error CanOnlyFailRunningScans => Error.Forbidden(description: nameof(CanOnlyFailRunningScans));
|
public static Error CanOnlyFailPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyFailPendingOrRunningScans));
|
||||||
public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty));
|
public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty));
|
||||||
public static Error LibraryScanAlreadyExists => Error.Conflict(description: nameof(LibraryScanAlreadyExists));
|
public static Error LibraryScanAlreadyExists => Error.Conflict(description: nameof(LibraryScanAlreadyExists));
|
||||||
public static Error LibraryAlreadyBeingScanned => Error.Forbidden(description: nameof(LibraryAlreadyBeingScanned));
|
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 CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount => Error.Validation(description: nameof(CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount));
|
||||||
public static Error CompletedScanJobsCountCantExceedTotalScanJobsCount => Error.Validation(description: nameof(CompletedScanJobsCountCantExceedTotalScanJobsCount));
|
public static Error CompletedScanJobsCountCantExceedTotalScanJobsCount => Error.Validation(description: nameof(CompletedScanJobsCountCantExceedTotalScanJobsCount));
|
||||||
public static Error ScanJobCurrentOperationCannotBeEmpty => Error.Validation(description: nameof(ScanJobCurrentOperationCannotBeEmpty));
|
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>
|
/// <summary>
|
||||||
/// Interface for the media library scan job for discovering music file system items.
|
/// Interface for the media library scan job for discovering music file system items.
|
||||||
/// </summary>
|
/// </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.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using System.Collections.Generic;
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||||
@@ -30,11 +29,11 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
/// <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>
|
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId)
|
||||||
{
|
{
|
||||||
// Declare the list of jobs that this scanner requires.
|
// Declare the list of jobs that this scanner requires.
|
||||||
IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||||
@@ -75,7 +74,7 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
|
|||||||
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
|
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
|
||||||
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
||||||
|
|
||||||
// Return the top level jobs that will be triggered when the scan will be started.
|
// The file system discovery job is the only top level job: no scanning can happen before the files are discovered.
|
||||||
yield return fileSystemDiscoveryJob;
|
return fileSystemDiscoveryJob;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
@@ -2,6 +2,7 @@
|
|||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -13,12 +14,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
/// <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="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="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>
|
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||||
[DebuggerDisplay("Id: {Id}")]
|
[DebuggerDisplay("Id: {Id}")]
|
||||||
public record LibraryScanQueuedDomainEvent(
|
public record LibraryScanQueuedDomainEvent(
|
||||||
Guid Id,
|
Guid Id,
|
||||||
ScanId ScanId,
|
ScanId ScanId,
|
||||||
|
UserId UserId,
|
||||||
LibraryId LibraryId,
|
LibraryId LibraryId,
|
||||||
DateTime OccurredOnUtc
|
DateTime OccurredOnUtc
|
||||||
) : IDomainEvent;
|
) : 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>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public Result<Success> QueueScan()
|
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))
|
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
|
||||||
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
|
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;
|
return Result.Success;
|
||||||
}
|
}
|
||||||
@@ -110,7 +110,7 @@ public class LibraryScan : AggregateRoot<ScanId>
|
|||||||
else
|
else
|
||||||
return Errors.LibraryScanning.CanOnlyStartPendingScans;
|
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))
|
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
|
||||||
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
|
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>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public Result<Success> CancelScan()
|
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;
|
Status = LibraryScanJobStatus.Canceled;
|
||||||
else
|
else
|
||||||
return Errors.LibraryScanning.CanOnlyCancelRunningScans;
|
return Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans;
|
||||||
|
|
||||||
_domainEvents.Add(new LibraryScanCancelledDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow));
|
_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>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public Result<Success> FailScan()
|
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;
|
Status = LibraryScanJobStatus.Failed;
|
||||||
else
|
else
|
||||||
return Errors.LibraryScanning.CanOnlyFailRunningScans;
|
return Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans;
|
||||||
|
|
||||||
return Result.Success;
|
return Result.Success;
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-3
@@ -1,5 +1,6 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -13,13 +14,16 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
|||||||
public interface IMediaLibraryScanningService
|
public interface IMediaLibraryScanningService
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Starts <paramref name="scan"/>.
|
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="scan">The media library scan to start.</param>
|
/// <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="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>
|
/// <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>
|
/// <returns>
|
||||||
Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
|
/// 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>
|
/// <summary>
|
||||||
/// Cancels <paramref name="scan"/>.
|
/// 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 =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
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.Jobs;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
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.Services.Scanners;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
@@ -22,7 +22,6 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||||
{
|
{
|
||||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
|
||||||
private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory;
|
private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory;
|
||||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||||
@@ -31,19 +30,16 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
|
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
|
||||||
/// </summary>
|
/// </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="mediaLibraryScannerFactory">Injected factory for creating media library scanners.</param>
|
||||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</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="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||||
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
|
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
|
||||||
public MediaLibraryScanningService(
|
public MediaLibraryScanningService(
|
||||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
|
||||||
IMediaLibraryScannerFactory mediaLibraryScannerFactory,
|
IMediaLibraryScannerFactory mediaLibraryScannerFactory,
|
||||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
||||||
IDomainEventPublisher domainEventPublisher)
|
IDomainEventPublisher domainEventPublisher)
|
||||||
{
|
{
|
||||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
|
||||||
_mediaLibraryScannerFactory = mediaLibraryScannerFactory;
|
_mediaLibraryScannerFactory = mediaLibraryScannerFactory;
|
||||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||||
@@ -51,51 +47,48 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Starts <paramref name="scan"/>.
|
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="scan">The media library scan to start.</param>
|
/// <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="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>
|
/// <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>
|
/// <returns>
|
||||||
public async Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken)
|
/// 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();
|
Result<Success> startScanResult = scan.StartScan();
|
||||||
if (startScanResult.IsFailure)
|
if (startScanResult.IsFailure)
|
||||||
return startScanResult.Errors;
|
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())
|
foreach (IDomainEvent domainEvent in scan.GetDomainEvents())
|
||||||
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
|
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// register the scan in the tracker for cancellation tokens
|
|
||||||
_mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId));
|
|
||||||
|
|
||||||
try
|
return Result.From<IMediaLibraryScanDiscoveryJob>(rootJob);
|
||||||
{
|
|
||||||
// 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -105,7 +98,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public Result<Success> CancelScan(LibraryScan scan)
|
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));
|
_mediaLibrariesScanCancellationTracker.CancelScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId));
|
||||||
return Result.Success;
|
return Result.Success;
|
||||||
}
|
}
|
||||||
@@ -120,21 +113,20 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
|||||||
{
|
{
|
||||||
job.ScanId = scanId;
|
job.ScanId = scanId;
|
||||||
job.UserId = userId;
|
job.UserId = userId;
|
||||||
// recursively set properties for all children
|
// Recursively set properties for all children.
|
||||||
foreach (IMediaLibraryScanJob childJob in job.Children)
|
foreach (IMediaLibraryScanJob childJob in job.Children)
|
||||||
SetScanPropertiesForJobChain(childJob, scanId, userId);
|
SetScanPropertiesForJobChain(childJob, scanId, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </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>
|
/// <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 = [];
|
HashSet<IMediaLibraryScanJob> uniqueJobs = [];
|
||||||
foreach (IMediaLibraryScanJob job in rootJobs)
|
TraverseJobGraph(rootJob, uniqueJobs);
|
||||||
TraverseJobGraph(job, uniqueJobs);
|
|
||||||
return uniqueJobs.Count;
|
return uniqueJobs.Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+8
@@ -11,6 +11,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IMediaLibrariesScanProgressTracker
|
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>
|
/// <summary>
|
||||||
/// Initializes the the progress tracking of a media library scan.
|
/// Initializes the the progress tracking of a media library scan.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
+30
@@ -16,6 +16,36 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr
|
|||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<MediaLibraryScanCompositeId, MediaLibraryScanProgress> _scanProgresses = new();
|
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>
|
/// <summary>
|
||||||
/// Initializes the the progress tracking of a media library scan.
|
/// Initializes the the progress tracking of a media library scan.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
+7
-6
@@ -1,22 +1,23 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using System.Threading.Channels;
|
using System.Threading.Channels;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public interface IMediaLibrariesScanQueue
|
public interface IMediaLibrariesScanQueue
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public ChannelWriter<IMediaLibraryScanJob> Writer { get; }
|
ChannelWriter<MediaLibraryScanCompositeId> Writer { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public ChannelReader<IMediaLibraryScanJob> Reader { get; }
|
ChannelReader<MediaLibraryScanCompositeId> Reader { get; }
|
||||||
}
|
}
|
||||||
+5
-2
@@ -1,4 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -13,6 +14,8 @@ internal interface IMediaLibraryScannerFactory
|
|||||||
/// Creates a media library scanner based on the provided library type.
|
/// Creates a media library scanner based on the provided library type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
|
/// <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>
|
/// <returns>
|
||||||
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
|
/// 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.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||||
using System.Collections.Generic;
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||||
@@ -18,9 +17,9 @@ public interface IMediaTypeScanner
|
|||||||
LibraryType SupportedLibraryType { get; }
|
LibraryType SupportedLibraryType { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
/// <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>
|
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||||
IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId);
|
IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId);
|
||||||
}
|
}
|
||||||
+11
-41
@@ -1,7 +1,9 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#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.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||||
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System;
|
using System;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -28,49 +30,17 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
|
|||||||
/// Creates a media library scanner for the specified library type.
|
/// Creates a media library scanner for the specified library type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="libraryType">The type of the media library.</param>
|
/// <param name="libraryType">The type of the media library.</param>
|
||||||
/// <returns>A media library scanner for the specified library type.</returns>
|
/// <returns>
|
||||||
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
|
/// 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
|
return libraryType switch
|
||||||
{
|
{
|
||||||
// Implemented scanners.
|
LibraryType.Book => Result.From<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IBookLibraryTypeScanner>()),
|
||||||
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
|
LibraryType.Music => Result.From<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IMusicLibraryTypeScanner>()),
|
||||||
LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."),
|
// Every other media library type is modeled, but has no scanner yet, so scanning it is reported as unsupported.
|
||||||
LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."),
|
_ => Errors.LibraryScanning.NoScannerForLibraryType
|
||||||
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}'.")
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -107,7 +107,8 @@ public sealed class MediaLibraryScanProgress : ValueObject
|
|||||||
LibraryScanJobStatus status,
|
LibraryScanJobStatus status,
|
||||||
Optional<MediaLibraryScanJobProgress> currentJobProgress)
|
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;
|
return Errors.LibraryScanning.TotalScanJobsCountMustBePositive;
|
||||||
if (completedJobs < 0)
|
if (completedJobs < 0)
|
||||||
return Errors.LibraryScanning.CompletedScanJobsCountMustBePositive;
|
return Errors.LibraryScanning.CompletedScanJobsCountMustBePositive;
|
||||||
|
|||||||
+1
-1
@@ -5,6 +5,6 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Interface for the media library scan job for discovering books file system items.
|
/// Interface for the media library scan job for discovering books file system items.
|
||||||
/// </summary>
|
/// </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.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using System.Collections.Generic;
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||||
@@ -30,19 +29,19 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
/// <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>
|
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
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);
|
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||||
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||||
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||||
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||||
|
|
||||||
// establish the hierarchical relationships between jobs
|
// Establish the hierarchical relationships between jobs.
|
||||||
fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
|
fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
|
||||||
mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
|
mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
|
||||||
|
|
||||||
@@ -52,7 +51,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
|||||||
mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
|
mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
|
||||||
mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob);
|
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
|
// 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.
|
// 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
|
// 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);
|
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
|
||||||
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
||||||
|
|
||||||
// return the top level jobs that will be triggered when the scan will be started
|
// The file system discovery job is the only top level job: no scanning can happen before the files are discovered.
|
||||||
yield return fileSystemDiscoveryJob;
|
return fileSystemDiscoveryJob;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,7 +112,7 @@ public static class InfrastructureLayerServices
|
|||||||
// Media library scanning.
|
// Media library scanning.
|
||||||
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
||||||
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
||||||
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
|
services.AddHostedService<MediaLibraryScanProcessorJob>();
|
||||||
|
|
||||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||||
services.AddTransient<IMusicFileSystemDiscoveryJob, MusicFileSystemDiscoveryJob>();
|
services.AddTransient<IMusicFileSystemDiscoveryJob, MusicFileSystemDiscoveryJob>();
|
||||||
|
|||||||
+90
-94
@@ -70,115 +70,111 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
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;
|
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
if (getFingerprintsResult.IsFailure)
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
fingerprintsByPath = getFingerprintsResult.Value;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
}
|
||||||
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
|
|
||||||
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
|
|
||||||
|
|
||||||
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.
|
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
int processedContentLocations = 0;
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
|
||||||
|
|
||||||
// Convert it to a domain object.
|
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||||
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.
|
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
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);
|
publishJobProgressResult = await PublishJobProgressAsync(
|
||||||
if (getFingerprintsResult.IsFailure)
|
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
if (publishJobProgressResult.IsFailure)
|
||||||
fingerprintsByPath = getFingerprintsResult.Value;
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
lastHeartbeat = now;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Set the initial progress of the scan job.
|
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
if (stagingBatch.Count > 0)
|
||||||
if (publishJobProgressResult.IsFailure)
|
{
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
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);
|
// This job finished, increment the number of processed jobs progress.
|
||||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
int processedContentLocations = 0;
|
Status = LibraryScanJobStatus.Completed;
|
||||||
|
|
||||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
// Call each linked child with the obtained payload.
|
||||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
// 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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+76
-80
@@ -67,86 +67,58 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
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;
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// 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);
|
metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService));
|
||||||
|
if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE)
|
||||||
// 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)
|
|
||||||
{
|
{
|
||||||
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||||
if (insertBatchResult.IsFailure)
|
if (insertBatchResult.IsFailure)
|
||||||
@@ -154,16 +126,40 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
|
|||||||
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (saveBatchResult.IsFailure)
|
if (saveBatchResult.IsFailure)
|
||||||
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
|
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
|
||||||
|
metadataBatch.Clear();
|
||||||
|
unitOfWork.ClearTrackedEntities();
|
||||||
}
|
}
|
||||||
|
processedItems++;
|
||||||
|
|
||||||
// This job finished, increment the number of processed jobs progress.
|
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
DateTime now = DateTime.UtcNow;
|
||||||
Status = LibraryScanJobStatus.Completed;
|
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.
|
// Flush any remaining extracted metadata items that did not reach the batch size.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
if (metadataBatch.Count > 0)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
{
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
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)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+27
-31
@@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
{
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
Status = LibraryScanJobStatus.Running;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
// 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.
|
// 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);
|
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||||
|
|
||||||
IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
|
IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
|
||||||
.GetServices<IMediaLibraryScanArtworkEnricher>()
|
.GetServices<IMediaLibraryScanArtworkEnricher>()
|
||||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||||
if (artworkEnricher is null)
|
if (artworkEnricher is null)
|
||||||
throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'.");
|
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.
|
// Increment the number of completed jobs progress.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
Status = LibraryScanJobStatus.Completed;
|
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.
|
// 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)
|
if (Children.Count == 0)
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// Call each linked child with the obtained payload.
|
// Call each linked child with the obtained payload.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+27
-31
@@ -45,47 +45,43 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
{
|
{
|
||||||
try
|
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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||||
await Task.Run(async () =>
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
{
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
Status = LibraryScanJobStatus.Running;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
// 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
|
// 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);
|
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||||
if (publishJobProgressResult.IsFailure)
|
if (publishJobProgressResult.IsFailure)
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
|
||||||
// mark the staging results against the media library scan snapshot of the previous scan
|
// 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);
|
Result<Updated> markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (markChangesResult.IsFailure)
|
if (markChangesResult.IsFailure)
|
||||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||||
|
|
||||||
// increment the number of processed elements progress
|
// Increment the number of processed elements progress.
|
||||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||||
if (publishJobProgressResult.IsFailure)
|
if (publishJobProgressResult.IsFailure)
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
|
||||||
// this job finished, increment the number of processed jobs progress
|
// This job finished, increment the number of processed jobs progress.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
Status = LibraryScanJobStatus.Completed;
|
Status = LibraryScanJobStatus.Completed;
|
||||||
|
|
||||||
// call each linked child with the obtained payload
|
// Call each linked child with the obtained payload.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+73
-77
@@ -49,99 +49,95 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||||
await Task.Run(async () =>
|
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;
|
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(
|
||||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
LibraryId.Value,
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
shouldIncludeNavigationProperties: false,
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
shouldTrackEntities: false,
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
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
|
// Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size.
|
||||||
Result<int> getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
while (true)
|
||||||
if (getFilesToHashCountResult.IsFailure)
|
{
|
||||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
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,.
|
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||||
// in which case the file reads run in parallel.
|
if (getFilesToHashPageResult.IsFailure)
|
||||||
bool shouldParallelizeReads = false;
|
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||||
if (totalFilesToHash > 0)
|
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(
|
// Check if enough time has passed since last update.
|
||||||
LibraryId.Value,
|
DateTime now = DateTime.UtcNow;
|
||||||
shouldIncludeNavigationProperties: false,
|
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||||
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.
|
// Increment the number of processed elements progress.
|
||||||
DateTime now = DateTime.UtcNow;
|
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
if (publishJobProgressResult.IsFailure)
|
||||||
{
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
// Increment the number of processed elements progress.
|
lastUpdateTime = now;
|
||||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
}
|
||||||
if (publishJobProgressResult.IsFailure)
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
|
||||||
lastUpdateTime = now;
|
|
||||||
}
|
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Write the computed hashes back to the staging results.
|
// Write the computed hashes back to the staging results.
|
||||||
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||||
if (updateHashesResult.IsFailure)
|
if (updateHashesResult.IsFailure)
|
||||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||||
|
|
||||||
lastPath = filesToHashPage[^1].Path;
|
lastPath = filesToHashPage[^1].Path;
|
||||||
}
|
}
|
||||||
|
|
||||||
// This job finished, increment the number of processed jobs progress.
|
// This job finished, increment the number of processed jobs progress.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
Status = LibraryScanJobStatus.Completed;
|
Status = LibraryScanJobStatus.Completed;
|
||||||
|
|
||||||
// Call each linked child with the obtained payload.
|
// Call each linked child with the obtained payload.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+27
-31
@@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
{
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||||
Status = LibraryScanJobStatus.Running;
|
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||||
// 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.
|
// 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);
|
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||||
|
|
||||||
IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider
|
IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider
|
||||||
.GetServices<IMediaLibraryScanMetadataEnricher>()
|
.GetServices<IMediaLibraryScanMetadataEnricher>()
|
||||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||||
if (metadataEnricher is null)
|
if (metadataEnricher is null)
|
||||||
throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'.");
|
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.
|
// Increment the number of completed jobs progress.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
Status = LibraryScanJobStatus.Completed;
|
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.
|
// 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)
|
if (Children.Count == 0)
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// Call each linked child with the obtained payload.
|
// Call each linked child with the obtained payload.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+97
-101
@@ -54,124 +54,120 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
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;
|
Result<UserSettingsEntity?> getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
if (getUserSettingsResult.IsFailure)
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
_logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings.");
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
else
|
||||||
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);
|
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
|
||||||
if (getUserSettingsResult.IsFailure)
|
shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false;
|
||||||
_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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
|
// 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
|
// 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.
|
// 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 metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb);
|
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||||
string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]);
|
string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]);
|
||||||
|
|
||||||
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
|
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
|
||||||
{
|
{
|
||||||
Result<Updated> resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (resetMetadataResult.IsFailure)
|
if (resetMetadataResult.IsFailure)
|
||||||
throw new InvalidOperationException(resetMetadataResult.FirstError.Description);
|
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.
|
// 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)
|
if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint)
|
||||||
{
|
{
|
||||||
Result<Updated> resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (resetPathTemplateMetadataResult.IsFailure)
|
if (resetPathTemplateMetadataResult.IsFailure)
|
||||||
throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description);
|
throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
|
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
|
||||||
{
|
{
|
||||||
Result<Updated> resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Updated> resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (resetArtworkResult.IsFailure)
|
if (resetArtworkResult.IsFailure)
|
||||||
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
|
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
|
// 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
|
// 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.
|
// 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.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||||
library.PathTemplateFingerprint = pathTemplateFingerprint;
|
library.PathTemplateFingerprint = pathTemplateFingerprint;
|
||||||
library.UpdatedOnUtc = DateTime.UtcNow;
|
library.UpdatedOnUtc = DateTime.UtcNow;
|
||||||
library.UpdatedBy = Guid.NewGuid();
|
library.UpdatedBy = Guid.NewGuid();
|
||||||
|
|
||||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (saveChangesResult.IsFailure)
|
if (saveChangesResult.IsFailure)
|
||||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||||
|
|
||||||
// Increment the number of processed elements progress.
|
// Increment the number of processed elements progress.
|
||||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||||
if (publishJobProgressResult.IsFailure)
|
if (publishJobProgressResult.IsFailure)
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
|
||||||
// Increment the number of completed jobs progress.
|
// Increment the number of completed jobs progress.
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
Status = LibraryScanJobStatus.Completed;
|
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.
|
// 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)
|
if (Children.Count == 0)
|
||||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
// Call each linked child with the obtained payload.
|
// Call each linked child with the obtained payload.
|
||||||
foreach (IMediaLibraryScanJob child in Children)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+80
-84
@@ -48,104 +48,100 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||||
await Task.Run(async () =>
|
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;
|
Result<Updated> resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
if (resetEnrichmentStateResult.IsFailure)
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
}
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
|
||||||
|
|
||||||
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.
|
// Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata.
|
||||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
Result<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
if (getPathsResult.IsFailure)
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
|
||||||
|
|
||||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
Result<Success> materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
if (materializeItemsResult.IsFailure)
|
||||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
throw new InvalidOperationException(materializeItemsResult.FirstError.Description);
|
||||||
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> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
if (saveChangesResult.IsFailure)
|
||||||
if (publishJobProgressResult.IsFailure)
|
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||||
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.
|
// 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<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
Result<Deleted> clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
if (getDeletedPathsResult.IsFailure)
|
if (clearStagedDataResult.IsFailure)
|
||||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
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.
|
// Increment the number of processed elements progress.
|
||||||
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||||
if (getChangedPathsResult.IsFailure)
|
if (publishJobProgressResult.IsFailure)
|
||||||
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
|
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.
|
// Increment the number of completed jobs progress.
|
||||||
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
if (applySnapshotSwapResult.IsFailure)
|
Status = LibraryScanJobStatus.Completed;
|
||||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
// 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.
|
// Call each linked child with the obtained payload.
|
||||||
if (getChangedPathsResult.Value.Count > 0)
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
{
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+87
-91
@@ -75,111 +75,107 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
// 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);
|
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)
|
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
|
Status = LibraryScanJobStatus.Running;
|
||||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||||
await Task.Run(async () =>
|
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;
|
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
if (getFingerprintsResult.IsFailure)
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
fingerprintsByPath = getFingerprintsResult.Value;
|
||||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
}
|
||||||
|
|
||||||
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.
|
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
int processedContentLocations = 0;
|
||||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
|
||||||
|
|
||||||
// Convert it to a domain object.
|
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||||
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.
|
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
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);
|
publishJobProgressResult = await PublishJobProgressAsync(
|
||||||
if (getFingerprintsResult.IsFailure)
|
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
if (publishJobProgressResult.IsFailure)
|
||||||
fingerprintsByPath = getFingerprintsResult.Value;
|
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||||
|
lastHeartbeat = now;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Set the initial progress of the scan job.
|
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
if (stagingBatch.Count > 0)
|
||||||
if (publishJobProgressResult.IsFailure)
|
{
|
||||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
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);
|
// This job finished, increment the number of processed jobs progress.
|
||||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||||
int processedContentLocations = 0;
|
Status = LibraryScanJobStatus.Completed;
|
||||||
|
|
||||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
// Call each linked child with the obtained payload.
|
||||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
foreach (IMediaLibraryScanJob child in Children)
|
||||||
|
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||||
// 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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
|
|||||||
+23
-2
@@ -46,11 +46,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
|
|||||||
if (cancellationToken.IsCancellationRequested)
|
if (cancellationToken.IsCancellationRequested)
|
||||||
return;
|
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)));
|
DebounceDispatcher debouncer = _debouncers.GetOrAdd(mediaLibraryScanCompositeId, _ => new DebounceDispatcher(TimeSpan.FromMilliseconds(50)));
|
||||||
await debouncer.DebounceAsync(async () =>
|
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)
|
if (cancellationToken.IsCancellationRequested)
|
||||||
return;
|
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>
|
/// <summary>
|
||||||
/// Disposes the debouncer that was used in a scan identified by <paramref name="mediaLibraryScanCompositeId"/>, that is now completed.
|
/// Disposes the debouncer that was used in a scan identified by <paramref name="mediaLibraryScanCompositeId"/>, that is now completed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
+7
-6
@@ -1,25 +1,26 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
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.Services.Queue;
|
||||||
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using System.Threading.Channels;
|
using System.Threading.Channels;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
|
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
|
||||||
{
|
{
|
||||||
private readonly Channel<IMediaLibraryScanJob> _channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
|
private readonly Channel<MediaLibraryScanCompositeId> _channel = Channel.CreateUnbounded<MediaLibraryScanCompositeId>();
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public ChannelWriter<IMediaLibraryScanJob> Writer => _channel.Writer;
|
public ChannelWriter<MediaLibraryScanCompositeId> Writer => _channel.Writer;
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </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>
|
/// </summary>
|
||||||
internal class FileHashService : IFileHashService
|
internal class FileHashService : IFileHashService
|
||||||
{
|
{
|
||||||
private const int SAMPLE_COUNT = 6; // number of sample points for hash computation
|
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 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 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();
|
private static readonly ulong s_emptyFileHash = ComputeEmptyHash();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -37,10 +37,11 @@ internal class FileHashService : IFileHashService
|
|||||||
object listLock = new();
|
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.
|
// 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()
|
ParallelOptions parallelOptions = new()
|
||||||
{
|
{
|
||||||
CancellationToken = cancellationToken,
|
CancellationToken = cancellationToken,
|
||||||
MaxDegreeOfParallelism = shouldParallelizeReads ? Environment.ProcessorCount : 1
|
MaxDegreeOfParallelism = shouldParallelizeReads ? Math.Max(1, Environment.ProcessorCount - 1) : 1
|
||||||
};
|
};
|
||||||
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
|
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ public class ScanLibrariesEndpointSummary : Summary<ScanLibrariesEndpoint, Empty
|
|||||||
public ScanLibrariesEndpointSummary()
|
public ScanLibrariesEndpointSummary()
|
||||||
{
|
{
|
||||||
Summary = "Triggers the scan of all media libraries.";
|
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.",
|
Response(200, "The media libraries scan was successfully started.",
|
||||||
example: new MediaLibraryScanResponse[] {
|
example: new MediaLibraryScanResponse[] {
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, ScanLibra
|
|||||||
public ScanLibraryEndpointSummary()
|
public ScanLibraryEndpointSummary()
|
||||||
{
|
{
|
||||||
Summary = "Triggers the scan of a media library.";
|
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(
|
ExampleRequest = new ScanLibraryRequest(
|
||||||
Id: Guid.NewGuid()
|
Id: Guid.NewGuid()
|
||||||
|
|||||||
+1
-1
@@ -41,7 +41,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Cancels the running scans of all the media libraries.
|
/// Cancels the running and queued scans of all the media libraries.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request">The request object.</param>
|
/// <param name="request">The request object.</param>
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</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()
|
public CancelLibrariesScanEndpointSummary()
|
||||||
{
|
{
|
||||||
Summary = "Cancels the scan of all the media libraries.";
|
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));
|
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>
|
/// <summary>
|
||||||
/// Cancels a running scan of a media library.
|
/// Cancels a running or queued scan of a media library.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request">The request containing the Ids of the media library and of the scan to cancel.</param>
|
/// <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>
|
/// <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()
|
public CancelLibraryScanEndpointSummary()
|
||||||
{
|
{
|
||||||
Summary = "Cancels the scan of a media library.";
|
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.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.");
|
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()
|
public GetRunningLibraryScansEndpointSummary()
|
||||||
{
|
{
|
||||||
Summary = "Retrieves the running media library scans.";
|
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));
|
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">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>إلغاء الفحص</value>
|
<value>إلغاء الفحص</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>جارٍ الإلغاء</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>كتاب هزلي</value>
|
<value>كتاب هزلي</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>برنامج إذاعي</value>
|
<value>برنامج إذاعي</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>في قائمة الانتظار</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>ريمكس</value>
|
<value>ريمكس</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Scan Abbrechen</value>
|
<value>Scan Abbrechen</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Wird abgebrochen</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Comic-Heft</value>
|
<value>Comic-Heft</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Radiosendung</value>
|
<value>Radiosendung</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>In Warteschlange</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Neuabmischung</value>
|
<value>Neuabmischung</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Cancel Scan</value>
|
<value>Cancel Scan</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Cancelling</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Comic Book</value>
|
<value>Comic Book</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Radio Show</value>
|
<value>Radio Show</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>Queued</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remix</value>
|
<value>Remix</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Cancelar Escaneo</value>
|
<value>Cancelar Escaneo</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Cancelando</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Cómic</value>
|
<value>Cómic</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Programa de Radio</value>
|
<value>Programa de Radio</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>En cola</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remezcla</value>
|
<value>Remezcla</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Annuler Le Scan</value>
|
<value>Annuler Le Scan</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Annulation en cours</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Bande Dessinée</value>
|
<value>Bande Dessinée</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Émission Radio</value>
|
<value>Émission Radio</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>En file d'attente</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remixage</value>
|
<value>Remixage</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Annulla Scansione</value>
|
<value>Annulla Scansione</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Annullamento in corso</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Fumetto</value>
|
<value>Fumetto</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Programma Radiofonico</value>
|
<value>Programma Radiofonico</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>In coda</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remissaggio</value>
|
<value>Remissaggio</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>スキャンを中止</value>
|
<value>スキャンを中止</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>キャンセル中</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>漫画</value>
|
<value>漫画</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>ラジオ番組</value>
|
<value>ラジオ番組</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>待機中</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>リミックス</value>
|
<value>リミックス</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Cancel Scan</value>
|
<value>Cancel Scan</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Cancelling</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Comic Book</value>
|
<value>Comic Book</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Radio Show</value>
|
<value>Radio Show</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>Queued</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remix</value>
|
<value>Remix</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Anulează Scanarea</value>
|
<value>Anulează Scanarea</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Se anulează</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Bandă Desenată</value>
|
<value>Bandă Desenată</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Emisiune Radio</value>
|
<value>Emisiune Radio</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>În așteptare</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Remix</value>
|
<value>Remix</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>Скасувати Сканування</value>
|
<value>Скасувати Сканування</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>Скасування</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>Комікс</value>
|
<value>Комікс</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>Радіопередача</value>
|
<value>Радіопередача</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>У черзі</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>Ремікс</value>
|
<value>Ремікс</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -141,6 +141,9 @@
|
|||||||
<data name="CancelScan" xml:space="preserve">
|
<data name="CancelScan" xml:space="preserve">
|
||||||
<value>取消扫描</value>
|
<value>取消扫描</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Cancelling" xml:space="preserve">
|
||||||
|
<value>正在取消</value>
|
||||||
|
</data>
|
||||||
<data name="ComicBook" xml:space="preserve">
|
<data name="ComicBook" xml:space="preserve">
|
||||||
<value>漫画</value>
|
<value>漫画</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -249,6 +252,9 @@
|
|||||||
<data name="RadioShow" xml:space="preserve">
|
<data name="RadioShow" xml:space="preserve">
|
||||||
<value>广播节目</value>
|
<value>广播节目</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Queued" xml:space="preserve">
|
||||||
|
<value>排队中</value>
|
||||||
|
</data>
|
||||||
<data name="Remix" xml:space="preserve">
|
<data name="Remix" xml:space="preserve">
|
||||||
<value>混音版</value>
|
<value>混音版</value>
|
||||||
</data>
|
</data>
|
||||||
|
|||||||
@@ -168,7 +168,8 @@
|
|||||||
const jsLocalizedLibraryScanStatuses = {
|
const jsLocalizedLibraryScanStatuses = {
|
||||||
Completed: '@_localizer["Completed"]',
|
Completed: '@_localizer["Completed"]',
|
||||||
Failed: '@_localizer["Failed"]',
|
Failed: '@_localizer["Failed"]',
|
||||||
Canceled: '@_localizer["Canceled"]'
|
Canceled: '@_localizer["Canceled"]',
|
||||||
|
Cancelling: '@_localizer["Cancelling"]'
|
||||||
};
|
};
|
||||||
const jsLocalizedLibraryScanJobsStatuses = {
|
const jsLocalizedLibraryScanJobsStatuses = {
|
||||||
DiscoveringFiles: '@_localizer["DiscoveringFiles"]',
|
DiscoveringFiles: '@_localizer["DiscoveringFiles"]',
|
||||||
@@ -178,7 +179,8 @@
|
|||||||
SavingScanData: '@_localizer["SavingScanData"]',
|
SavingScanData: '@_localizer["SavingScanData"]',
|
||||||
InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]',
|
InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]',
|
||||||
EnrichingMetadata: '@_localizer["EnrichingMetadata"]',
|
EnrichingMetadata: '@_localizer["EnrichingMetadata"]',
|
||||||
ResolvingArtwork: '@_localizer["ResolvingArtwork"]'
|
ResolvingArtwork: '@_localizer["ResolvingArtwork"]',
|
||||||
|
Queued: '@_localizer["Queued"]'
|
||||||
};
|
};
|
||||||
const jsLocalizedLibraryTypes = {
|
const jsLocalizedLibraryTypes = {
|
||||||
Book: '@_localizer["Book"]',
|
Book: '@_localizer["Book"]',
|
||||||
@@ -307,12 +309,17 @@
|
|||||||
|
|
||||||
row.setAttribute('data-scan-id', scan.scanId);
|
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');
|
statusSpan.classList.remove('hidden');
|
||||||
|
|
||||||
scanProgress.classList.remove('hidden');
|
scanProgress.classList.toggle('hidden', isQueued);
|
||||||
totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`;
|
if (!isQueued) {
|
||||||
jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`;
|
totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`;
|
||||||
|
jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`;
|
||||||
|
}
|
||||||
|
|
||||||
scanIcon.classList.add('hidden');
|
scanIcon.classList.add('hidden');
|
||||||
cancelScanIcon.classList.remove('hidden');
|
cancelScanIcon.classList.remove('hidden');
|
||||||
@@ -369,6 +376,12 @@
|
|||||||
scanIcon.classList.add('hidden');
|
scanIcon.classList.add('hidden');
|
||||||
cancelScanIcon.classList.remove('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;
|
const scanId = scan.scanId;
|
||||||
await signalRConnection.invoke('SubscribeToScan', scanId);
|
await signalRConnection.invoke('SubscribeToScan', scanId);
|
||||||
}
|
}
|
||||||
@@ -401,6 +414,12 @@
|
|||||||
scanIcon.classList.add('hidden');
|
scanIcon.classList.add('hidden');
|
||||||
cancelScanIcon.classList.remove('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;
|
const scanId = success.scanId;
|
||||||
await signalRConnection.invoke('SubscribeToScan', scanId);
|
await signalRConnection.invoke('SubscribeToScan', scanId);
|
||||||
}
|
}
|
||||||
@@ -410,29 +429,20 @@
|
|||||||
// On cancel all libraries scan button click.
|
// On cancel all libraries scan button click.
|
||||||
const handleCancelLibrariesScanClick = async function(e) {
|
const handleCancelLibrariesScanClick = async function(e) {
|
||||||
await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARIES_SCAN)', {});
|
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]');
|
const rows = document.querySelectorAll('tr[data-scan-id]');
|
||||||
|
|
||||||
rows.forEach(row => {
|
rows.forEach(row => {
|
||||||
// Remove the scan Id, its no longer being scanned.
|
|
||||||
row.removeAttribute('data-scan-id');
|
|
||||||
|
|
||||||
const statusSpan = row.querySelector('.scan-job-status');
|
const statusSpan = row.querySelector('.scan-job-status');
|
||||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`;
|
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`;
|
||||||
const scanProgress = row.querySelector('.scan-progress');
|
statusSpan.classList.remove('hidden');
|
||||||
scanProgress.classList.add('hidden');
|
|
||||||
|
|
||||||
// Show scan status icon.
|
|
||||||
const completedIdon = row.querySelector('img[src*="yellow.png"]');
|
|
||||||
completedIdon.classList.remove('hidden');
|
|
||||||
|
|
||||||
// Toggle scan action icons.
|
// Toggle scan action icons.
|
||||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
|
||||||
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||||
scanIcon.classList.remove('hidden');
|
|
||||||
cancelScanIcon.classList.add('hidden');
|
cancelScanIcon.classList.add('hidden');
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -441,6 +451,7 @@
|
|||||||
const handleCancelLibraryScanClick = async function(e) {
|
const handleCancelLibraryScanClick = async function(e) {
|
||||||
if (e.target.matches('img[src*="stop.svg"]')) {
|
if (e.target.matches('img[src*="stop.svg"]')) {
|
||||||
const row = e.target.closest('tr');
|
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) })';
|
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARY_SCAN, new { libraryId = default(Guid), scanId = default(Guid) })';
|
||||||
|
|
||||||
@@ -460,29 +471,18 @@
|
|||||||
).join('/');
|
).join('/');
|
||||||
|
|
||||||
await callApiPostAsync(finalUrl);
|
await callApiPostAsync(finalUrl);
|
||||||
|
|
||||||
// Remove the scan Id, its no longer being scanned.
|
|
||||||
row.removeAttribute('data-scan-id');
|
|
||||||
|
|
||||||
const statusSpan = row.querySelector('.scan-job-status');
|
// The cancellation is only applied once the server confirms it, so the scan keeps its Id and is shown as being cancelled meanwhile.
|
||||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`;
|
// The server might have confirmed it already, in which case the row no longer carries the Id and is left as it is.
|
||||||
const scanProgress = row.querySelector('.scan-progress');
|
if (row.getAttribute('data-scan-id') === scanId) {
|
||||||
scanProgress.classList.add('hidden');
|
const statusSpan = row.querySelector('.scan-job-status');
|
||||||
|
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`;
|
||||||
|
statusSpan.classList.remove('hidden');
|
||||||
|
|
||||||
// Show scan status icon.
|
// Toggle scan action icons.
|
||||||
const completedIdon = row.querySelector('img[src*="yellow.png"]');
|
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||||
completedIdon.classList.remove('hidden');
|
cancelScanIcon.classList.add('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';
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -502,17 +502,21 @@
|
|||||||
const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`);
|
const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`);
|
||||||
rows.forEach(row => {
|
rows.forEach(row => {
|
||||||
// Update status text.
|
// Update status text.
|
||||||
|
const currentOperation = progress.currentJobProgress.currentOperation;
|
||||||
|
const isQueued = currentOperation === 'Queued';
|
||||||
const statusSpan = row.querySelector('.scan-job-status');
|
const statusSpan = row.querySelector('.scan-job-status');
|
||||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[progress.currentJobProgress.currentOperation];
|
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[currentOperation] ?? currentOperation;
|
||||||
statusSpan.classList.remove('hidden');
|
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 scanProgress = row.querySelector('.scan-progress');
|
||||||
const totalProgressDiv = row.querySelector('.scan-progress-total > div');
|
const totalProgressDiv = row.querySelector('.scan-progress-total > div');
|
||||||
const jobProgressDiv = row.querySelector('.scan-progress-job > div');
|
const jobProgressDiv = row.querySelector('.scan-progress-job > div');
|
||||||
scanProgress.classList.remove('hidden');
|
scanProgress.classList.toggle('hidden', isQueued);
|
||||||
totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`;
|
if (!isQueued) {
|
||||||
jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`;
|
totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`;
|
||||||
|
jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`;
|
||||||
|
}
|
||||||
|
|
||||||
// Toggle scan action icons.
|
// Toggle scan action icons.
|
||||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
||||||
@@ -576,10 +580,38 @@
|
|||||||
btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block';
|
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.
|
// Subscribe to events.
|
||||||
signalRConnection.on("libraryScanProgressUpdateEvent", progressHandler);
|
signalRConnection.on("libraryScanProgressUpdateEvent", progressHandler);
|
||||||
signalRConnection.on("libraryScanFinishedEvent", completionHandler);
|
signalRConnection.on("libraryScanFinishedEvent", completionHandler);
|
||||||
signalRConnection.on("libraryScanFailedEvent", failureHandler);
|
signalRConnection.on("libraryScanFailedEvent", failureHandler);
|
||||||
|
signalRConnection.on("libraryScanCancelledEvent", cancelledHandler);
|
||||||
signalRConnection.onclose(onClose);
|
signalRConnection.onclose(onClose);
|
||||||
signalRConnection.onreconnecting(onReconnecting);
|
signalRConnection.onreconnecting(onReconnecting);
|
||||||
signalRConnection.onreconnected(onReconnected);
|
signalRConnection.onreconnected(onReconnected);
|
||||||
@@ -588,6 +620,7 @@
|
|||||||
signalRConnection.off("libraryScanProgressUpdateEvent", progressHandler);
|
signalRConnection.off("libraryScanProgressUpdateEvent", progressHandler);
|
||||||
signalRConnection.off("libraryScanFinishedEvent", completionHandler);
|
signalRConnection.off("libraryScanFinishedEvent", completionHandler);
|
||||||
signalRConnection.off("libraryScanFailedEvent", failureHandler);
|
signalRConnection.off("libraryScanFailedEvent", failureHandler);
|
||||||
|
signalRConnection.off("libraryScanCancelledEvent", cancelledHandler);
|
||||||
signalRConnection.off("close", onClose);
|
signalRConnection.off("close", onClose);
|
||||||
signalRConnection.off("reconnecting", onReconnecting);
|
signalRConnection.off("reconnecting", onReconnecting);
|
||||||
signalRConnection.off("reconnected", onReconnected);
|
signalRConnection.off("reconnected", onReconnected);
|
||||||
|
|||||||
+6
@@ -2,8 +2,10 @@
|
|||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
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.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -17,6 +19,7 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedCo
|
|||||||
public class LibraryScanQueuedDomainEventFixture
|
public class LibraryScanQueuedDomainEventFixture
|
||||||
{
|
{
|
||||||
private readonly ScanIdFixture _scanIdFixture = new();
|
private readonly ScanIdFixture _scanIdFixture = new();
|
||||||
|
private readonly UserIdFixture _userIdFixture = new();
|
||||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -24,18 +27,21 @@ public class LibraryScanQueuedDomainEventFixture
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id">Optional. The Id of the domain event.</param>
|
/// <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="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="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>
|
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
|
||||||
/// <returns>The created <see cref="LibraryScanQueuedDomainEvent"/>.</returns>
|
/// <returns>The created <see cref="LibraryScanQueuedDomainEvent"/>.</returns>
|
||||||
public LibraryScanQueuedDomainEvent Create(
|
public LibraryScanQueuedDomainEvent Create(
|
||||||
Guid? id = null,
|
Guid? id = null,
|
||||||
ScanId? scanId = null,
|
ScanId? scanId = null,
|
||||||
|
UserId? userId = null,
|
||||||
LibraryId? libraryId = null,
|
LibraryId? libraryId = null,
|
||||||
DateTime? occurredOnUtc = null)
|
DateTime? occurredOnUtc = null)
|
||||||
{
|
{
|
||||||
return new LibraryScanQueuedDomainEvent(
|
return new LibraryScanQueuedDomainEvent(
|
||||||
id ?? Guid.NewGuid(),
|
id ?? Guid.NewGuid(),
|
||||||
scanId ?? _scanIdFixture.Create(),
|
scanId ?? _scanIdFixture.Create(),
|
||||||
|
userId ?? _userIdFixture.Create(),
|
||||||
libraryId ?? _libraryIdFixture.Create(),
|
libraryId ?? _libraryIdFixture.Create(),
|
||||||
occurredOnUtc ?? DateTime.UtcNow);
|
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>();
|
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||||
_userId = Guid.NewGuid();
|
_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);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||||
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
||||||
@@ -62,15 +62,15 @@ public class CancelLibrariesScanCommandHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllRunningScans()
|
public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllActiveScans()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans =
|
List<LibraryScanEntity> activeScans =
|
||||||
[
|
[
|
||||||
_libraryScanEntityFixture.Create(userId: _userId),
|
_libraryScanEntityFixture.Create(userId: _userId),
|
||||||
_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
|
// Act
|
||||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||||
@@ -83,17 +83,36 @@ public class CancelLibrariesScanCommandHandlerTests
|
|||||||
_mockDomainEventsQueue.Received(2).Enqueue(Arg.Any<LibraryScanCancelledDomainEvent>());
|
_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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyCancelScansOwnedByTheUser()
|
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyCancelScansOwnedByTheUser()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid otherUserId = Guid.NewGuid();
|
Guid otherUserId = Guid.NewGuid();
|
||||||
List<LibraryScanEntity> runningScans =
|
List<LibraryScanEntity> activeScans =
|
||||||
[
|
[
|
||||||
_libraryScanEntityFixture.Create(userId: _userId),
|
_libraryScanEntityFixture.Create(userId: _userId),
|
||||||
_libraryScanEntityFixture.Create(userId: otherUserId)
|
_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);
|
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -117,16 +136,16 @@ public class CancelLibrariesScanCommandHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
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>());
|
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>())
|
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>())
|
||||||
.Returns(Error.Failure(description: "Failed to get running scans"));
|
.Returns(Error.Failure(description: "Failed to get active scans"));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||||
@@ -141,8 +160,8 @@ public class CancelLibrariesScanCommandHandlerTests
|
|||||||
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
|
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId)];
|
List<LibraryScanEntity> activeScans = [_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));
|
||||||
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(Error.Failure(description: "Failed to update library scan"));
|
.Returns(Error.Failure(description: "Failed to update library scan"));
|
||||||
|
|
||||||
@@ -155,18 +174,18 @@ public class CancelLibrariesScanCommandHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError()
|
public async Task HandleAsync_WhenScanIsInATerminalState_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)];
|
List<LibraryScanEntity> activeScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)];
|
||||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(activeScans));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
Result<Success> result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
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 _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>());
|
||||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-3
@@ -58,7 +58,7 @@ public class CancelLibraryScanCommandHandlerTests
|
|||||||
_mockValidator = Substitute.For<IValidator<CancelLibraryScanCommand>>();
|
_mockValidator = Substitute.For<IValidator<CancelLibraryScanCommand>>();
|
||||||
_userId = Guid.NewGuid();
|
_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);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(true);
|
.Returns(true);
|
||||||
@@ -89,6 +89,28 @@ public class CancelLibraryScanCommandHandlerTests
|
|||||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibraryScanCancelledDomainEvent>());
|
_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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenScanDoesNotExist_ShouldReturnNotFoundError()
|
public async Task HandleAsync_WhenScanDoesNotExist_ShouldReturnNotFoundError()
|
||||||
{
|
{
|
||||||
@@ -163,7 +185,7 @@ public class CancelLibraryScanCommandHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError()
|
public async Task HandleAsync_WhenScanIsInATerminalState_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create();
|
CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create();
|
||||||
@@ -176,7 +198,7 @@ public class CancelLibraryScanCommandHandlerTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
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 _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>());
|
||||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(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.Repositories.MediaLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Core.MediaLibrary.Management.Events;
|
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
using Lumina.Domain.Common.Exceptions;
|
using Lumina.Domain.Common.Exceptions;
|
||||||
using Lumina.Domain.Common.Primitives;
|
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.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
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.Cancellation;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||||
@@ -35,7 +35,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
|||||||
private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository;
|
private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository;
|
||||||
private readonly ILibraryScanSnapshotRepository _mockLibraryScanSnapshotRepository;
|
private readonly ILibraryScanSnapshotRepository _mockLibraryScanSnapshotRepository;
|
||||||
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
|
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
|
||||||
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
|
private readonly IMediaLibraryScanProgressNotifier _mockMediaLibraryScanProgressNotifier;
|
||||||
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
|
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
|
||||||
private readonly LibraryScanCancelledDomainEventHandler _sut;
|
private readonly LibraryScanCancelledDomainEventHandler _sut;
|
||||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||||
@@ -55,17 +55,19 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
|||||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository);
|
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository);
|
||||||
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockLibraryScanSnapshotRepository);
|
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockLibraryScanSnapshotRepository);
|
||||||
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
||||||
_mockMediaLibrariesScanProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
_mockMediaLibraryScanProgressNotifier = Substitute.For<IMediaLibraryScanProgressNotifier>();
|
||||||
_mockMediaLibrariesScanCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
_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);
|
_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>())
|
_mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(Result.Deleted);
|
.Returns(Result.Deleted);
|
||||||
_mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
_mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(Result.Success);
|
.Returns(Result.Success);
|
||||||
|
|
||||||
_sut = new LibraryScanCancelledDomainEventHandler(_mockMediaLibraryScanningService, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibrariesScanProgressTracker, _mockUnitOfWork);
|
_sut = new LibraryScanCancelledDomainEventHandler(_mockMediaLibraryScanningService, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibraryScanProgressNotifier, _mockUnitOfWork);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -84,12 +86,46 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_mockMediaLibraryScanningService.Received(1).CancelScan(Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == scan.Id));
|
_mockMediaLibraryScanningService.Received(1).CancelScan(Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == scan.Id));
|
||||||
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
|
await _mockMediaLibraryScanProgressNotifier.Received(1).SendLibraryScanCancelledEventAsync(
|
||||||
_mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
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 _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, domainEvent.ScanId.Value, CancellationToken.None);
|
||||||
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, 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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
|
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
|
||||||
{
|
{
|
||||||
@@ -105,6 +141,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(error, exception.EventualConsistencyError);
|
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 _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(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
|
||||||
Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError);
|
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>());
|
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,6 +183,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(error, exception.EventualConsistencyError);
|
Assert.Equal(error, exception.EventualConsistencyError);
|
||||||
|
await _mockMediaLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanCancelledEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
|
||||||
_mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
|
_mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||||
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), 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>());
|
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
|||||||
+40
-65
@@ -1,24 +1,18 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#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.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.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.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.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Channels;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
|
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
|
||||||
@@ -29,109 +23,90 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
|
|||||||
[ExcludeFromCodeCoverage]
|
[ExcludeFromCodeCoverage]
|
||||||
public class LibraryScanQueuedDomainEventHandlerTests
|
public class LibraryScanQueuedDomainEventHandlerTests
|
||||||
{
|
{
|
||||||
private readonly IUnitOfWork _mockUnitOfWork;
|
private readonly IMediaLibrariesScanQueue _mockScanQueue;
|
||||||
private readonly ILibraryScanRepository _mockLibraryScanRepository;
|
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||||
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
|
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
||||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
|
||||||
private readonly LibraryScanQueuedDomainEventHandler _sut;
|
private readonly LibraryScanQueuedDomainEventHandler _sut;
|
||||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
|
||||||
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
||||||
|
private readonly Channel<MediaLibraryScanCompositeId> _channel;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandlerTests"/> class.
|
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandlerTests"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public LibraryScanQueuedDomainEventHandlerTests()
|
public LibraryScanQueuedDomainEventHandlerTests()
|
||||||
{
|
{
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_channel = Channel.CreateUnbounded<MediaLibraryScanCompositeId>();
|
||||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
_mockScanQueue = Substitute.For<IMediaLibrariesScanQueue>();
|
||||||
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
|
_mockScanQueue.Writer.Returns(_channel.Writer);
|
||||||
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
|
_mockScanQueue.Reader.Returns(_channel.Reader);
|
||||||
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||||
|
|
||||||
// default stubs: the scanning service starts the scan successfully
|
// Default stubs: the queued scan progress is initialized successfully.
|
||||||
_mockMediaLibraryScanningService.StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
|
_mockProgressTracker.InitializeQueuedScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>())
|
||||||
.Returns(Result.Success);
|
.Returns(Result.Created);
|
||||||
|
|
||||||
_sut = new LibraryScanQueuedDomainEventHandler(_mockMediaLibraryScanningService, _mockDomainEventsQueue, _mockUnitOfWork);
|
_sut = new LibraryScanQueuedDomainEventHandler(_mockScanQueue, _mockCancellationTracker, _mockProgressTracker);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenScanExists_ShouldStartTheScan()
|
public async Task HandleAsync_WhenCalled_ShouldRegisterTheScanForCancellation()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
|
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
|
// Act
|
||||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
_mockCancellationTracker.Received(1).RegisterScan(
|
||||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == scan.Id),
|
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId == domainEvent.UserId));
|
||||||
scan.Library.LibraryType,
|
|
||||||
Arg.Any<CancellationToken>());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
|
public async Task HandleAsync_WhenCalled_ShouldInitializeTheQueuedScanProgress()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
|
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
|
// Act
|
||||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(error, exception.EventualConsistencyError);
|
_mockProgressTracker.Received(1).InitializeQueuedScanProgress(
|
||||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
domainEvent.LibraryId,
|
||||||
|
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == domainEvent.ScanId && compositeId.UserId == domainEvent.UserId));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
|
public async Task HandleAsync_WhenCalled_ShouldWriteTheCompositeScanIdToTheQueue()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
|
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
|
||||||
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
|
||||||
.Returns(Result<LibraryScanEntity?>.Success(null));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError);
|
Assert.True(_channel.Reader.TryRead(out MediaLibraryScanCompositeId? enqueuedScanId));
|
||||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any<LibraryScan>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
Assert.Equal(domainEvent.ScanId, enqueuedScanId!.ScanId);
|
||||||
|
Assert.Equal(domainEvent.UserId, enqueuedScanId.UserId);
|
||||||
|
Assert.False(_channel.Reader.TryRead(out _));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException()
|
public async Task HandleAsync_WhenCalled_ShouldNotStartProcessingTheScan()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
|
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
|
// Act
|
||||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(error, exception.EventualConsistencyError);
|
// Queuing a scan only registers it and reports it as waiting: the scan processor prepares and starts it later, one scan at a time.
|
||||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
_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.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
using Lumina.Domain.Common.Primitives;
|
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.Services.Progress;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Fixtures.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>();
|
_mockMediaLibrariesScanProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||||
_userId = Guid.NewGuid();
|
_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);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||||
_mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>())
|
_mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>())
|
||||||
@@ -72,15 +73,15 @@ public class GetRunningLibraryScansQueryHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllRunningScans()
|
public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllActiveScans()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans =
|
List<LibraryScanEntity> activeScans =
|
||||||
[
|
[
|
||||||
_libraryScanEntityFixture.Create(userId: _userId),
|
_libraryScanEntityFixture.Create(userId: _userId),
|
||||||
_libraryScanEntityFixture.Create(userId: Guid.NewGuid())
|
_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
|
// Act
|
||||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
||||||
@@ -94,12 +95,12 @@ public class GetRunningLibraryScansQueryHandlerTests
|
|||||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnProgressOnlyForScansOwnedByTheUser()
|
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnProgressOnlyForScansOwnedByTheUser()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans =
|
List<LibraryScanEntity> activeScans =
|
||||||
[
|
[
|
||||||
_libraryScanEntityFixture.Create(userId: _userId),
|
_libraryScanEntityFixture.Create(userId: _userId),
|
||||||
_libraryScanEntityFixture.Create(userId: Guid.NewGuid())
|
_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);
|
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -110,6 +111,32 @@ public class GetRunningLibraryScansQueryHandlerTests
|
|||||||
Assert.Single(result.Value);
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
|
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
|
||||||
{
|
{
|
||||||
@@ -122,15 +149,15 @@ public class GetRunningLibraryScansQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
|
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
|
||||||
await _mockLibraryScanRepository.DidNotReceive().GetRunningScansAsync(Arg.Any<CancellationToken>());
|
await _mockLibraryScanRepository.DidNotReceive().GetActiveScansAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetActiveScansFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>())
|
_mockLibraryScanRepository.GetActiveScansAsync(Arg.Any<CancellationToken>())
|
||||||
.Returns(Error.Failure(description: "Failed to get running scans"));
|
.Returns(Error.Failure(description: "Failed to get active scans"));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
||||||
@@ -140,18 +167,29 @@ public class GetRunningLibraryScansQueryHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGettingScanProgressFails_ShouldReturnError()
|
public async Task HandleAsync_WhenAnActiveScanHasNoProgress_ShouldSkipThatScan()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
List<LibraryScanEntity> runningScans = [_libraryScanEntityFixture.Create(userId: _userId)];
|
List<LibraryScanEntity> activeScans =
|
||||||
_mockLibraryScanRepository.GetRunningScansAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<LibraryScanEntity>>(runningScans));
|
[
|
||||||
|
_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>())
|
_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
|
// Act
|
||||||
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
Result<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.False(result.IsFailure);
|
||||||
|
Assert.Single(result.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-6
@@ -123,22 +123,25 @@ public class LibraryScanRepositoryTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetRunningScansAsync_WhenCalled_ShouldReturnOnlyRunningScans()
|
public async Task GetActiveScansAsync_WhenCalled_ShouldReturnPendingAndRunningScansOnly()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running);
|
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running);
|
||||||
LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed);
|
|
||||||
LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
|
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();
|
await _mockContext.SaveChangesAsync();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetRunningScansAsync(CancellationToken.None);
|
Result<IEnumerable<LibraryScanEntity>> result = await _sut.GetActiveScansAsync(CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.False(result.IsFailure);
|
Assert.False(result.IsFailure);
|
||||||
LibraryScanEntity retrievedScan = Assert.Single(result.Value);
|
Assert.Equal(2, result.Value.Count());
|
||||||
Assert.Equal(runningScan.Id, retrievedScan.Id);
|
Assert.Contains(result.Value, libraryScan => libraryScan.Id == runningScan.Id);
|
||||||
|
Assert.Contains(result.Value, libraryScan => libraryScan.Id == pendingScan.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -18,12 +18,12 @@ public class ErrorsTests
|
|||||||
{
|
{
|
||||||
// Assert
|
// Assert
|
||||||
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
|
// 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.LibraryScanIdCannotBeEmpty, ErrorType.Validation);
|
||||||
AssertError(DomainErrors.LibraryScanning.CanOnlyStartPendingScans, ErrorType.Forbidden);
|
AssertError(DomainErrors.LibraryScanning.CanOnlyStartPendingScans, ErrorType.Forbidden);
|
||||||
AssertError(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, ErrorType.Forbidden);
|
AssertError(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, ErrorType.Forbidden);
|
||||||
AssertError(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, ErrorType.Forbidden);
|
AssertError(DomainErrors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, ErrorType.Forbidden);
|
||||||
AssertError(DomainErrors.LibraryScanning.CanOnlyFailRunningScans, ErrorType.Forbidden);
|
AssertError(DomainErrors.LibraryScanning.CanOnlyFailPendingOrRunningScans, ErrorType.Forbidden);
|
||||||
AssertError(DomainErrors.LibraryScanning.ScanIdCannotBeEmpty, ErrorType.Validation);
|
AssertError(DomainErrors.LibraryScanning.ScanIdCannotBeEmpty, ErrorType.Validation);
|
||||||
AssertError(DomainErrors.LibraryScanning.LibraryScanAlreadyExists, ErrorType.Conflict);
|
AssertError(DomainErrors.LibraryScanning.LibraryScanAlreadyExists, ErrorType.Conflict);
|
||||||
AssertError(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, ErrorType.Forbidden);
|
AssertError(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, ErrorType.Forbidden);
|
||||||
@@ -35,6 +35,7 @@ public class ErrorsTests
|
|||||||
AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, ErrorType.Validation);
|
AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, ErrorType.Validation);
|
||||||
AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, ErrorType.Validation);
|
AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, ErrorType.Validation);
|
||||||
AssertError(DomainErrors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, ErrorType.Validation);
|
AssertError(DomainErrors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, ErrorType.Validation);
|
||||||
|
AssertError(DomainErrors.LibraryScanning.NoScannerForLibraryType, ErrorType.Unexpected);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
+79
-4
@@ -11,7 +11,6 @@ using NSubstitute;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Linq;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -55,11 +54,11 @@ public class MusicLibraryTypeScannerTests
|
|||||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
List<IMediaLibraryScanJob> rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)];
|
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
IMediaLibraryScanJob rootJob = Assert.Single(rootJobs);
|
|
||||||
Assert.Same(discoveryJob, rootJob);
|
Assert.Same(discoveryJob, rootJob);
|
||||||
|
Assert.IsAssignableFrom<IMusicFileSystemDiscoveryJob>(rootJob);
|
||||||
Assert.Contains(diffJob, discoveryJob.Children);
|
Assert.Contains(diffJob, discoveryJob.Children);
|
||||||
Assert.Contains(discoveryJob, diffJob.Parents);
|
Assert.Contains(discoveryJob, diffJob.Parents);
|
||||||
Assert.Contains(hashJob, diffJob.Children);
|
Assert.Contains(hashJob, diffJob.Children);
|
||||||
@@ -79,6 +78,61 @@ public class MusicLibraryTypeScannerTests
|
|||||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
_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]
|
[Fact]
|
||||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
||||||
{
|
{
|
||||||
@@ -95,7 +149,7 @@ public class MusicLibraryTypeScannerTests
|
|||||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_ = sut.CreateScanJobsForLibrary(libraryId).ToList();
|
_ = sut.CreateScanJobsForLibrary(libraryId);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_mockJobFactory.Received(1).CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
_mockJobFactory.Received(1).CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||||
@@ -108,6 +162,27 @@ public class MusicLibraryTypeScannerTests
|
|||||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
_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
|
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||||
{
|
{
|
||||||
TestScanJob job = new()
|
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.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
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.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -19,6 +21,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
|
|||||||
public class LibraryScanQueuedDomainEventTests
|
public class LibraryScanQueuedDomainEventTests
|
||||||
{
|
{
|
||||||
private readonly ScanIdFixture _scanIdFixture = new();
|
private readonly ScanIdFixture _scanIdFixture = new();
|
||||||
|
private readonly UserIdFixture _userIdFixture = new();
|
||||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||||
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
||||||
|
|
||||||
@@ -28,15 +31,17 @@ public class LibraryScanQueuedDomainEventTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
Guid id = Guid.NewGuid();
|
Guid id = Guid.NewGuid();
|
||||||
ScanId scanId = _scanIdFixture.Create();
|
ScanId scanId = _scanIdFixture.Create();
|
||||||
|
UserId userId = _userIdFixture.Create();
|
||||||
LibraryId libraryId = _libraryIdFixture.Create();
|
LibraryId libraryId = _libraryIdFixture.Create();
|
||||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc);
|
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, userId, libraryId, occurredOnUtc);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Equal(id, domainEvent.Id);
|
Assert.Equal(id, domainEvent.Id);
|
||||||
Assert.Equal(scanId, domainEvent.ScanId);
|
Assert.Equal(scanId, domainEvent.ScanId);
|
||||||
|
Assert.Equal(userId, domainEvent.UserId);
|
||||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||||
|
|||||||
+29
-26
@@ -96,6 +96,7 @@ public class LibraryScanTests
|
|||||||
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
||||||
LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType<LibraryScanQueuedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
|
LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType<LibraryScanQueuedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
|
||||||
Assert.Equal(scan.Id, queuedEvent.ScanId);
|
Assert.Equal(scan.Id, queuedEvent.ScanId);
|
||||||
|
Assert.Equal(scan.UserId, queuedEvent.UserId);
|
||||||
Assert.Equal(scan.LibraryId, queuedEvent.LibraryId);
|
Assert.Equal(scan.LibraryId, queuedEvent.LibraryId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,10 +150,10 @@ public class LibraryScanTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(LibraryScanJobStatus.Running)] // cannot start an already running scan
|
[InlineData(LibraryScanJobStatus.Running)] // Cannot start an already running scan.
|
||||||
[InlineData(LibraryScanJobStatus.Completed)] // cannot start a completed scan
|
[InlineData(LibraryScanJobStatus.Completed)] // Cannot start a completed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Canceled)] // cannot start a canceled scan
|
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot start a canceled scan.
|
||||||
[InlineData(LibraryScanJobStatus.Failed)] // cannot start a failed scan
|
[InlineData(LibraryScanJobStatus.Failed)] // Cannot start a failed scan.
|
||||||
public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status)
|
public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
@@ -200,10 +201,10 @@ public class LibraryScanTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(LibraryScanJobStatus.Pending)] // cannot complete a pending scan
|
[InlineData(LibraryScanJobStatus.Pending)] // Cannot complete a pending scan.
|
||||||
[InlineData(LibraryScanJobStatus.Completed)] // cannot complete an already completed scan
|
[InlineData(LibraryScanJobStatus.Completed)] // Cannot complete an already completed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Canceled)] // cannot complete a canceled scan
|
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot complete a canceled scan.
|
||||||
[InlineData(LibraryScanJobStatus.Failed)] // cannot complete a failed scan
|
[InlineData(LibraryScanJobStatus.Failed)] // Cannot complete a failed scan.
|
||||||
public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
|
public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
@@ -218,11 +219,13 @@ public class LibraryScanTests
|
|||||||
Assert.Equal(status, scan.Status);
|
Assert.Equal(status, scan.Status);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void CancelScan_WhenRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent()
|
[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
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Success> result = scan.CancelScan();
|
Result<Success> result = scan.CancelScan();
|
||||||
@@ -237,11 +240,10 @@ public class LibraryScanTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(LibraryScanJobStatus.Pending)] // cannot cancel a pending scan
|
[InlineData(LibraryScanJobStatus.Completed)] // Cannot cancel a completed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Completed)] // cannot cancel a completed scan
|
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot cancel an already canceled scan.
|
||||||
[InlineData(LibraryScanJobStatus.Canceled)] // cannot cancel an already canceled scan
|
[InlineData(LibraryScanJobStatus.Failed)] // Cannot cancel a failed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Failed)] // cannot cancel a failed scan
|
public void CancelScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
|
||||||
public void CancelScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
|
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||||
@@ -251,16 +253,18 @@ public class LibraryScanTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError);
|
Assert.Equal(Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError);
|
||||||
Assert.Equal(status, scan.Status);
|
Assert.Equal(status, scan.Status);
|
||||||
Assert.Empty(scan.GetDomainEvents());
|
Assert.Empty(scan.GetDomainEvents());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void FailScan_WhenRunning_ShouldTransitionToFailed()
|
[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
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Success> result = scan.FailScan();
|
Result<Success> result = scan.FailScan();
|
||||||
@@ -272,11 +276,10 @@ public class LibraryScanTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(LibraryScanJobStatus.Pending)] // cannot fail a pending scan
|
[InlineData(LibraryScanJobStatus.Completed)] // Cannot fail a completed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Completed)] // cannot fail a completed scan
|
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot fail a canceled scan.
|
||||||
[InlineData(LibraryScanJobStatus.Canceled)] // cannot fail a canceled scan
|
[InlineData(LibraryScanJobStatus.Failed)] // Cannot fail an already failed scan.
|
||||||
[InlineData(LibraryScanJobStatus.Failed)] // cannot fail an already failed scan
|
public void FailScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
|
||||||
public void FailScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
|
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||||
@@ -286,7 +289,7 @@ public class LibraryScanTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.LibraryScanning.CanOnlyFailRunningScans, result.FirstError);
|
Assert.Equal(Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans, result.FirstError);
|
||||||
Assert.Equal(status, scan.Status);
|
Assert.Equal(status, scan.Status);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+140
-59
@@ -1,4 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
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.Cancellation;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
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.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.Services.Scanners;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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;
|
||||||
|
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.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Channels;
|
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -33,7 +33,6 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
|
|||||||
[ExcludeFromCodeCoverage]
|
[ExcludeFromCodeCoverage]
|
||||||
public class MediaLibraryScanningServiceTests
|
public class MediaLibraryScanningServiceTests
|
||||||
{
|
{
|
||||||
private readonly IMediaLibrariesScanQueue _mockScanQueue;
|
|
||||||
private readonly IMediaLibraryScannerFactory _mockScannerFactory;
|
private readonly IMediaLibraryScannerFactory _mockScannerFactory;
|
||||||
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||||
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
||||||
@@ -42,85 +41,168 @@ public class MediaLibraryScanningServiceTests
|
|||||||
private readonly LibraryScanFixture _libraryScanFixture = new();
|
private readonly LibraryScanFixture _libraryScanFixture = new();
|
||||||
private readonly ScanIdFixture _scanIdFixture = new();
|
private readonly ScanIdFixture _scanIdFixture = new();
|
||||||
private readonly UserIdFixture _userIdFixture = new();
|
private readonly UserIdFixture _userIdFixture = new();
|
||||||
private readonly Channel<IMediaLibraryScanJob> _channel;
|
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||||
|
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningServiceTests"/> class.
|
/// Initializes a new instance of the <see cref="MediaLibraryScanningServiceTests"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public MediaLibraryScanningServiceTests()
|
public MediaLibraryScanningServiceTests()
|
||||||
{
|
{
|
||||||
_channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
|
|
||||||
_mockScanQueue = Substitute.For<IMediaLibrariesScanQueue>();
|
|
||||||
_mockScanQueue.Writer.Returns(_channel.Writer);
|
|
||||||
_mockScanQueue.Reader.Returns(_channel.Reader);
|
|
||||||
_mockScannerFactory = Substitute.For<IMediaLibraryScannerFactory>();
|
_mockScannerFactory = Substitute.For<IMediaLibraryScannerFactory>();
|
||||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>()).Returns(CancellationToken.None);
|
|
||||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
_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>();
|
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||||
_sut = new MediaLibraryScanningService(_mockScanQueue, _mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher);
|
_sut = new MediaLibraryScanningService(_mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishEventsAndEnqueueJobs()
|
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldReturnTheDiscoveryRootJob()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create();
|
LibraryScan scan = _libraryScanFixture.Create();
|
||||||
IMediaLibraryScanJob job = CreateJob(children: []);
|
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||||
IMediaTypeScanner scanner = CreateScanner([job]);
|
RegisterScanner(LibraryType.Book, rootJob);
|
||||||
|
|
||||||
// Act
|
// 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
|
||||||
Assert.False(result.IsFailure);
|
Assert.False(result.IsFailure);
|
||||||
Assert.Equal(Result.Success, result.Value);
|
Assert.Same(rootJob, result.Value);
|
||||||
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
|
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]
|
[Fact]
|
||||||
public async Task StartScanAsync_WhenScanCannotStart_ShouldReturnErrorAndNotEnqueueJobs()
|
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishTheStartedEvent()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
LibraryScan scan = _libraryScanFixture.Create();
|
||||||
|
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||||
|
|
||||||
// Act
|
// 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
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError);
|
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
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>());
|
_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]
|
[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
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create();
|
LibraryScan scan = _libraryScanFixture.Create();
|
||||||
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(_ => throw new NotImplementedException());
|
Error error = Error.Failure(description: "Failed to initialize the media library scan progress");
|
||||||
_mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner);
|
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
|
||||||
|
.Returns(error);
|
||||||
|
|
||||||
// Act
|
// 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
|
||||||
Assert.False(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Result.Success, result.Value);
|
Assert.Equal(error, result.FirstError);
|
||||||
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||||
Assert.False(_channel.Reader.TryRead(out _));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -129,17 +211,16 @@ public class MediaLibraryScanningServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
LibraryScan scan = _libraryScanFixture.Create();
|
LibraryScan scan = _libraryScanFixture.Create();
|
||||||
IMediaLibraryScanJob sharedChild = CreateJob(children: []);
|
IMediaLibraryScanJob sharedChild = CreateJob(children: []);
|
||||||
IMediaLibraryScanJob firstRoot = CreateJob(children: [sharedChild]);
|
IMediaLibraryScanJob firstChild = CreateJob(children: [sharedChild]);
|
||||||
IMediaLibraryScanJob secondRoot = CreateJob(children: [sharedChild]);
|
IMediaLibraryScanJob secondChild = CreateJob(children: [sharedChild]);
|
||||||
IMediaTypeScanner scanner = CreateScanner([firstRoot, secondRoot]);
|
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [firstChild, secondChild]);
|
||||||
|
RegisterScanner(LibraryType.Book, rootJob);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Success> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.False(result.IsFailure);
|
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), totalJobs: 4);
|
||||||
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), totalJobs: 3);
|
|
||||||
Assert.Equal(2, CountEnqueuedJobs());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -180,15 +261,16 @@ public class MediaLibraryScanningServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </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>
|
/// <returns>The created mocked scanner.</returns>
|
||||||
private IMediaTypeScanner CreateScanner(List<IMediaLibraryScanJob> jobs)
|
private IMediaTypeScanner RegisterScanner(LibraryType libraryType, IMediaLibraryScanDiscoveryJob rootJob)
|
||||||
{
|
{
|
||||||
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
||||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(jobs);
|
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(rootJob);
|
||||||
_mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner);
|
_mockScannerFactory.CreateLibraryScanner(libraryType).Returns(Result.From(scanner));
|
||||||
return scanner;
|
return scanner;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,14 +287,13 @@ public class MediaLibraryScanningServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <returns>The number of enqueued scan jobs.</returns>
|
/// <param name="job">The job whose scan properties are asserted.</param>
|
||||||
private int CountEnqueuedJobs()
|
/// <param name="scan">The media library scan that owns the job.</param>
|
||||||
|
private static void AssertScanProperties(IMediaLibraryScanJob job, LibraryScan scan)
|
||||||
{
|
{
|
||||||
int count = 0;
|
Assert.Equal(scan.Id, job.ScanId);
|
||||||
while (_channel.Reader.TryRead(out _))
|
Assert.Equal(scan.UserId, job.UserId);
|
||||||
count++;
|
|
||||||
return count;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+47
-2
@@ -23,6 +23,51 @@ public class MediaLibrariesScanProgressTrackerTests
|
|||||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = 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]
|
[Fact]
|
||||||
public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs()
|
public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs()
|
||||||
{
|
{
|
||||||
@@ -46,14 +91,14 @@ public class MediaLibrariesScanProgressTrackerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void InitializeScanProgress_WhenTotalJobsIsNotPositive_ShouldReturnError()
|
public void InitializeScanProgress_WhenTotalJobsIsNegative_ShouldReturnError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
LibraryId libraryId = _libraryIdFixture.Create();
|
LibraryId libraryId = _libraryIdFixture.Create();
|
||||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 0);
|
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: -1);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
|
|||||||
+94
-66
@@ -1,4 +1,6 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#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.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.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.
|
/// Contains unit tests for the <see cref="MediaLibraryScannerFactory"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[ExcludeFromCodeCoverage]
|
[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]
|
[Fact]
|
||||||
public void CreateLibraryScanner_WhenLibraryTypeIsBook_ShouldReturnBookLibraryTypeScanner()
|
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
|
// Act
|
||||||
IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Book);
|
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Book);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Same(expectedScanner, scanner);
|
Assert.False(result.IsFailure);
|
||||||
|
Assert.Same(_mockBookLibraryTypeScanner, result.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner()
|
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
|
// Act
|
||||||
IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music);
|
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Music);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.Same(expectedScanner, scanner);
|
Assert.False(result.IsFailure);
|
||||||
|
Assert.Same(_mockMusicLibraryTypeScanner, result.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(LibraryType.EBook)] // eBook scanner is not implemented
|
[InlineData(LibraryType.EBook)] // EBook scanner is not implemented.
|
||||||
[InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented
|
[InlineData(LibraryType.ComicBook)] // Comic book scanner is not implemented.
|
||||||
[InlineData(LibraryType.Magazine)] // magazine scanner is not implemented
|
[InlineData(LibraryType.Magazine)] // Magazine scanner is not implemented.
|
||||||
[InlineData(LibraryType.Newspaper)] // newspaper scanner is not implemented
|
[InlineData(LibraryType.Newspaper)] // Newspaper scanner is not implemented.
|
||||||
[InlineData(LibraryType.Manga)] // manga scanner is not implemented
|
[InlineData(LibraryType.Manga)] // Manga scanner is not implemented.
|
||||||
[InlineData(LibraryType.GraphicNovel)] // graphic novel scanner is not implemented
|
[InlineData(LibraryType.GraphicNovel)] // Graphic novel scanner is not implemented.
|
||||||
[InlineData(LibraryType.AcademicPaper)] // academic paper scanner is not implemented
|
[InlineData(LibraryType.AcademicPaper)] // Academic paper scanner is not implemented.
|
||||||
[InlineData(LibraryType.SheetMusic)] // sheet music scanner is not implemented
|
[InlineData(LibraryType.SheetMusic)] // Sheet music scanner is not implemented.
|
||||||
[InlineData(LibraryType.Movie)] // movie scanner is not implemented
|
[InlineData(LibraryType.Movie)] // Movie scanner is not implemented.
|
||||||
[InlineData(LibraryType.TvShow)] // TV show scanner is not implemented
|
[InlineData(LibraryType.TvShow)] // TV show scanner is not implemented.
|
||||||
[InlineData(LibraryType.Documentary)] // documentary scanner is not implemented
|
[InlineData(LibraryType.Documentary)] // Documentary scanner is not implemented.
|
||||||
[InlineData(LibraryType.Anime)] // anime scanner is not implemented
|
[InlineData(LibraryType.Anime)] // Anime scanner is not implemented.
|
||||||
[InlineData(LibraryType.ConcertVideo)] // concert video scanner is not implemented
|
[InlineData(LibraryType.ConcertVideo)] // Concert video scanner is not implemented.
|
||||||
[InlineData(LibraryType.TutorialVideo)] // tutorial 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.HomeVideo)] // Home video scanner is not implemented.
|
||||||
[InlineData(LibraryType.YouTubeVideo)] // YouTube 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.MusicVideo)] // Music video scanner is not implemented.
|
||||||
[InlineData(LibraryType.LiveRecordingVideo)] // live recording 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.InterviewVideo)] // Interview video scanner is not implemented.
|
||||||
[InlineData(LibraryType.CoverSongVideo)] // cover song 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.PodcastVideo)] // Podcast video scanner is not implemented.
|
||||||
[InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented
|
[InlineData(LibraryType.Audiobook)] // Audiobook scanner is not implemented.
|
||||||
[InlineData(LibraryType.LiveRecordingAudio)] // live recording audio 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.InterviewAudio)] // Interview audio scanner is not implemented.
|
||||||
[InlineData(LibraryType.CoverSongAudio)] // cover song 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.Remix)] // Remix scanner is not implemented.
|
||||||
[InlineData(LibraryType.SoundEffect)] // sound effect scanner is not implemented
|
[InlineData(LibraryType.SoundEffect)] // Sound effect scanner is not implemented.
|
||||||
[InlineData(LibraryType.PodcastAudio)] // podcast audio scanner is not implemented
|
[InlineData(LibraryType.PodcastAudio)] // Podcast audio scanner is not implemented.
|
||||||
[InlineData(LibraryType.Photo)] // photo scanner is not implemented
|
[InlineData(LibraryType.Photo)] // Photo scanner is not implemented.
|
||||||
[InlineData(LibraryType.Playlist)] // playlist scanner is not implemented
|
[InlineData(LibraryType.Playlist)] // Playlist scanner is not implemented.
|
||||||
[InlineData(LibraryType.Collection)] // collection scanner is not implemented
|
[InlineData(LibraryType.Collection)] // Collection scanner is not implemented.
|
||||||
[InlineData(LibraryType.Subtitles)] // subtitles scanner is not implemented
|
[InlineData(LibraryType.Subtitles)] // Subtitles scanner is not implemented.
|
||||||
[InlineData(LibraryType.Lyrics)] // lyrics scanner is not implemented
|
[InlineData(LibraryType.Lyrics)] // Lyrics scanner is not implemented.
|
||||||
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldThrowNotImplementedException(LibraryType libraryType)
|
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldReturnNoScannerError(LibraryType libraryType)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Act
|
||||||
ServiceCollection services = new();
|
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(libraryType);
|
||||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
MediaLibraryScannerFactory sut = new(serviceProvider);
|
|
||||||
|
|
||||||
// Act & Assert
|
// Assert
|
||||||
Assert.Throws<NotImplementedException>(() => sut.CreateLibraryScanner(libraryType));
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||||
|
Assert.IsType<NotImplementedError>(result.FirstError);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldThrowArgumentOutOfRangeException()
|
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldNotThrow()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Act
|
||||||
ServiceCollection services = new();
|
Exception? exception = Record.Exception(() => _sut.CreateLibraryScanner(LibraryType.Movie));
|
||||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
|
||||||
MediaLibraryScannerFactory sut = new(serviceProvider);
|
|
||||||
|
|
||||||
// Act & Assert
|
// Assert
|
||||||
Assert.Throws<ArgumentOutOfRangeException>(() => sut.CreateLibraryScanner((LibraryType)999));
|
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);
|
Assert.False(result.Value.CurrentJobProgress.HasValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Fact]
|
||||||
[InlineData(0)] // total jobs must be positive
|
public void Create_WhenTotalJobsIsZeroAndStatusIsPending_ShouldCreateQueuedProgress()
|
||||||
[InlineData(-1)] // total jobs must be positive
|
|
||||||
public void Create_WhenTotalJobsIsNotPositive_ShouldReturnError(int totalJobs)
|
|
||||||
{
|
{
|
||||||
// Act
|
// Act
|
||||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||||
@@ -80,10 +78,52 @@ public class MediaLibraryScanProgressTests
|
|||||||
_userIdFixture.Create(),
|
_userIdFixture.Create(),
|
||||||
_libraryIdFixture.Create(),
|
_libraryIdFixture.Create(),
|
||||||
completedJobs: 0,
|
completedJobs: 0,
|
||||||
totalJobs: totalJobs,
|
totalJobs: 0,
|
||||||
LibraryScanJobStatus.Pending,
|
LibraryScanJobStatus.Pending,
|
||||||
Optional<MediaLibraryScanJobProgress>.None());
|
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
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
||||||
|
|||||||
+76
-4
@@ -11,7 +11,6 @@ using NSubstitute;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Linq;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -54,11 +53,11 @@ public class BookLibraryTypeScannerTests
|
|||||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
List<IMediaLibraryScanJob> rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)];
|
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
IMediaLibraryScanJob rootJob = Assert.Single(rootJobs);
|
|
||||||
Assert.Same(discoveryJob, rootJob);
|
Assert.Same(discoveryJob, rootJob);
|
||||||
|
Assert.IsAssignableFrom<IBooksFileSystemDiscoveryJob>(rootJob);
|
||||||
Assert.Contains(diffJob, discoveryJob.Children);
|
Assert.Contains(diffJob, discoveryJob.Children);
|
||||||
Assert.Contains(discoveryJob, diffJob.Parents);
|
Assert.Contains(discoveryJob, diffJob.Parents);
|
||||||
Assert.Contains(hashJob, diffJob.Children);
|
Assert.Contains(hashJob, diffJob.Children);
|
||||||
@@ -75,6 +74,58 @@ public class BookLibraryTypeScannerTests
|
|||||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
_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]
|
[Fact]
|
||||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
||||||
{
|
{
|
||||||
@@ -90,7 +141,7 @@ public class BookLibraryTypeScannerTests
|
|||||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_ = sut.CreateScanJobsForLibrary(libraryId).ToList();
|
_ = sut.CreateScanJobsForLibrary(libraryId);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_mockJobFactory.Received(1).CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
_mockJobFactory.Received(1).CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||||
@@ -102,6 +153,27 @@ public class BookLibraryTypeScannerTests
|
|||||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
_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
|
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||||
{
|
{
|
||||||
TestScanJob job = new()
|
TestScanJob job = new()
|
||||||
|
|||||||
+56
@@ -201,6 +201,62 @@ public class DebouncedMediaLibraryScanProgressNotifierTests
|
|||||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
_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]
|
[Fact]
|
||||||
public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer()
|
public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer()
|
||||||
{
|
{
|
||||||
|
|||||||
+37
-16
@@ -1,7 +1,7 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#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 Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||||
using NSubstitute;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -16,37 +16,58 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.
|
|||||||
public class MediaLibrariesScanQueueTests
|
public class MediaLibrariesScanQueueTests
|
||||||
{
|
{
|
||||||
private readonly MediaLibrariesScanQueue _sut = new();
|
private readonly MediaLibrariesScanQueue _sut = new();
|
||||||
|
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Writer_WhenJobIsWritten_ShouldAllowReadingItFromReader()
|
public async Task Writer_WhenScanIsWritten_ShouldAllowReadingItFromReader()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
IMediaLibraryScanJob job = Substitute.For<IMediaLibraryScanJob>();
|
MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
bool writeResult = _sut.Writer.TryWrite(job);
|
bool writeResult = _sut.Writer.TryWrite(scanId);
|
||||||
IMediaLibraryScanJob readJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
MediaLibraryScanCompositeId readScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(writeResult);
|
Assert.True(writeResult);
|
||||||
Assert.Same(job, readJob);
|
Assert.Equal(scanId, readScanId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Writer_WhenMultipleJobsAreWritten_ShouldReadThemInFifoOrder()
|
public async Task Writer_WhenMultipleScansAreWritten_ShouldReadThemInFifoOrder()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
IMediaLibraryScanJob firstJob = Substitute.For<IMediaLibraryScanJob>();
|
MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||||
IMediaLibraryScanJob secondJob = Substitute.For<IMediaLibraryScanJob>();
|
MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||||
|
MediaLibraryScanCompositeId thirdScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_sut.Writer.TryWrite(firstJob);
|
_sut.Writer.TryWrite(firstScanId);
|
||||||
_sut.Writer.TryWrite(secondJob);
|
_sut.Writer.TryWrite(secondScanId);
|
||||||
IMediaLibraryScanJob firstReadJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
_sut.Writer.TryWrite(thirdScanId);
|
||||||
IMediaLibraryScanJob secondReadJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
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
|
||||||
Assert.Same(firstJob, firstReadJob);
|
// The scan processor relies on the queue order: scans must run in the order in which they were queued.
|
||||||
Assert.Same(secondJob, secondReadJob);
|
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