mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 02: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
+2
-2
@@ -28,11 +28,11 @@ public interface ILibraryScanRepository : IRepository<LibraryScanEntity>,
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scans have a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Pending"/> or a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryScanEntity"/>, or an error.</returns>
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetRunningScansAsync(CancellationToken cancellationToken);
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetActiveScansAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still
|
||||
|
||||
+6
-6
@@ -64,18 +64,18 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Get the running library scans of the current user from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getRunningLibraryScansResult.IsFailure)
|
||||
return getRunningLibraryScansResult.Errors;
|
||||
// Get the scans of the current user that are either executing or still waiting in the scan queue, from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> getActiveLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getActiveLibraryScansResult.IsFailure)
|
||||
return getActiveLibraryScansResult.Errors;
|
||||
|
||||
// Filter the library scans to process.
|
||||
List<LibraryScanEntity> authorizedLibraryScans = [];
|
||||
// Admins can see all library scans.
|
||||
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
|
||||
authorizedLibraryScans.AddRange(getActiveLibraryScansResult.Value);
|
||||
else // For regular users, only take the library scans that belong to them.
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId));
|
||||
authorizedLibraryScans.AddRange(getActiveLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId));
|
||||
|
||||
// Convert persistence library scans to domain entities.
|
||||
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
||||
|
||||
+10
-7
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
@@ -11,7 +12,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using System.Threading;
|
||||
@@ -27,7 +27,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IMediaLibraryScanProgressNotifier _mediaLibraryScanProgressNotifier;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
@@ -35,17 +35,17 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="mediaLibraryScanProgressNotifier">Injected service for notifying media libraries scan progress changes to third parties.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanCancelledDomainEventHandler(
|
||||
IMediaLibraryScanningService mediaLibraryScanningService,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
||||
IMediaLibraryScanProgressNotifier mediaLibraryScanProgressNotifier,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
_mediaLibraryScanProgressNotifier = mediaLibraryScanProgressNotifier;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
@@ -73,10 +73,13 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
|
||||
if (cancelScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||
|
||||
// Release the scan processing resources.
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
||||
|
||||
// Report the cancellation to the clients and release the progress entry of the scan, so that they stop showing it as active.
|
||||
await _mediaLibraryScanProgressNotifier.SendLibraryScanCancelledEventAsync(compositeId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Release the scan processing resources.
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
|
||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
|
||||
// Cancelling the scan cancels its own token, so the cleanup must not observe it, otherwise the staged results of the cancelled scan would survive the cancellation.
|
||||
// A scan that was cancelled after its snapshot was applied has not materialized its items yet, so its snapshot entries are rolled back, allowing the next
|
||||
// scan to treat the files as new and extract their metadata again instead of skipping them as unchanged.
|
||||
|
||||
+27
-38
@@ -1,15 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -21,22 +16,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
/// </summary>
|
||||
public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibraryScanQueuedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="domainEventsQueue">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork)
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing the media library scans that are waiting to execute.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
public LibraryScanQueuedDomainEventHandler(
|
||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,26 +43,18 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get the library scan that was queued, from the repository.
|
||||
Result<LibraryScanEntity?> getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors);
|
||||
if (getLibraryScanResult.Value is null)
|
||||
throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound);
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId);
|
||||
|
||||
// Convert the repository entity to a domain entity.
|
||||
Result<LibraryScan> libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
// Register the scan for cancellation before it is queued, so that a cancellation that arrives while the scan is still
|
||||
// waiting for its turn is honored when the scan processor finally picks it up.
|
||||
_mediaLibrariesScanCancellationTracker.RegisterScan(compositeId);
|
||||
|
||||
// Start the media library scan.
|
||||
Result<Success> startScanResult = await _mediaLibraryScanningService.StartScanAsync(
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false);
|
||||
if (startScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
|
||||
// Report the scan as queued, so clients can show it while it waits for the scans ahead of it to finish.
|
||||
// This is only a display concern, so it must never prevent the scan from being queued.
|
||||
_ = _mediaLibrariesScanProgressTracker.InitializeQueuedScanProgress(domainEvent.LibraryId, compositeId);
|
||||
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(queuedDomainEvent);
|
||||
// Only the scan itself is queued, not its jobs. The scan processor prepares and executes the jobs of one scan at a time,
|
||||
// so the scans run consecutively, in the order in which they were queued.
|
||||
await _mediaLibrariesScanQueue.Writer.WriteAsync(compositeId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+7
@@ -31,4 +31,11 @@ public interface IMediaLibraryScanProgressNotifier
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that failed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the cancellation of a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that was cancelled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken);
|
||||
}
|
||||
+19
-19
@@ -65,33 +65,33 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Get the ongoing library scans from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getRunningScansResult.IsFailure)
|
||||
return getRunningScansResult.Errors;
|
||||
// Get the library scans that are executing or still waiting in the scan queue, from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> getActiveScansResult = await _unitOfWork.LibraryScanRepository.GetActiveScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getActiveScansResult.IsFailure)
|
||||
return getActiveScansResult.Errors;
|
||||
|
||||
// Filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own.
|
||||
LibraryScanEntity[] userRunningRepositoryLibraryScans = [];
|
||||
LibraryScanEntity[] userActiveRepositoryLibraryScans = [];
|
||||
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
|
||||
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
|
||||
userActiveRepositoryLibraryScans = [.. getActiveScansResult.Value];
|
||||
else
|
||||
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)];
|
||||
userActiveRepositoryLibraryScans = [.. getActiveScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)];
|
||||
|
||||
// For each of the filtered library scans, get their progress.
|
||||
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
||||
IEnumerable<Result<LibraryScan>> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> userRunningDomainLibraryScan in userRunningDomainLibraryScans)
|
||||
IEnumerable<Result<LibraryScan>> userActiveDomainLibraryScans = userActiveRepositoryLibraryScans.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> userActiveDomainLibraryScan in userActiveDomainLibraryScans)
|
||||
{
|
||||
if (userRunningDomainLibraryScan.IsFailure)
|
||||
return userRunningDomainLibraryScan.Errors;
|
||||
else
|
||||
{
|
||||
Result<MediaLibraryScanProgress> getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
|
||||
MediaLibraryScanCompositeId.Create(userRunningDomainLibraryScan.Value.Id, userRunningDomainLibraryScan.Value.UserId));
|
||||
if (getLibraryScanProgressResult.IsFailure)
|
||||
return getLibraryScanProgressResult.Errors;
|
||||
libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse());
|
||||
}
|
||||
if (userActiveDomainLibraryScan.IsFailure)
|
||||
return userActiveDomainLibraryScan.Errors;
|
||||
|
||||
Result<MediaLibraryScanProgress> getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
|
||||
MediaLibraryScanCompositeId.Create(userActiveDomainLibraryScan.Value.Id, userActiveDomainLibraryScan.Value.UserId));
|
||||
// A scan whose progress was already released has ended, so it is not reported as active any more.
|
||||
if (getLibraryScanProgressResult.IsFailure)
|
||||
continue;
|
||||
|
||||
libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse());
|
||||
}
|
||||
|
||||
return Result.From(libraryScanProgresses.AsEnumerable());
|
||||
|
||||
Reference in new issue
Block a user