mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 01:01: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());
|
||||
|
||||
@@ -96,6 +96,9 @@ internal sealed class LibraryRepository : ILibraryRepository
|
||||
.Include(library => library.PathTemplateParts)
|
||||
.AsSplitQuery()
|
||||
.Where(library => library.IsEnabled && !library.IsLocked)
|
||||
// The scan queue executes the scans in this order, so it must be deterministic and match the order shown to the user.
|
||||
.OrderBy(library => library.Title)
|
||||
.ThenBy(library => library.Id)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -83,16 +83,17 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// Gets the media library scans that have a <see cref="LibraryScanJobStatus.Pending"/> or a
|
||||
/// <see cref="LibraryScanJobStatus.Running"/> status, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryScanEntity"/>, or an error.</returns>
|
||||
public async Task<Result<IEnumerable<LibraryScanEntity>>> GetRunningScansAsync(CancellationToken cancellationToken)
|
||||
public async Task<Result<IEnumerable<LibraryScanEntity>>> GetActiveScansAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryScans
|
||||
.Include(library => library.Library)
|
||||
.AsSplitQuery()
|
||||
.Where(library => library.Status == LibraryScanJobStatus.Running)
|
||||
.Where(library => library.Status == LibraryScanJobStatus.Pending || library.Status == LibraryScanJobStatus.Running)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,8 @@ public static partial class Errors
|
||||
public static Error LibraryScanIdCannotBeEmpty => Error.Validation(description: nameof(LibraryScanIdCannotBeEmpty));
|
||||
public static Error CanOnlyStartPendingScans => Error.Forbidden(description: nameof(CanOnlyStartPendingScans));
|
||||
public static Error CanOnlyCompleteRunningScans => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScans));
|
||||
public static Error CanOnlyCancelRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelRunningScans));
|
||||
public static Error CanOnlyFailRunningScans => Error.Forbidden(description: nameof(CanOnlyFailRunningScans));
|
||||
public static Error CanOnlyCancelPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelPendingOrRunningScans));
|
||||
public static Error CanOnlyFailPendingOrRunningScans => Error.Forbidden(description: nameof(CanOnlyFailPendingOrRunningScans));
|
||||
public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty));
|
||||
public static Error LibraryScanAlreadyExists => Error.Conflict(description: nameof(LibraryScanAlreadyExists));
|
||||
public static Error LibraryAlreadyBeingScanned => Error.Forbidden(description: nameof(LibraryAlreadyBeingScanned));
|
||||
@@ -27,5 +27,6 @@ public static partial class Errors
|
||||
public static Error CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount => Error.Validation(description: nameof(CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount));
|
||||
public static Error CompletedScanJobsCountCantExceedTotalScanJobsCount => Error.Validation(description: nameof(CompletedScanJobsCountCantExceedTotalScanJobsCount));
|
||||
public static Error ScanJobCurrentOperationCannotBeEmpty => Error.Validation(description: nameof(ScanJobCurrentOperationCannotBeEmpty));
|
||||
public static Error NoScannerForLibraryType => Error.NotImplemented(description: nameof(NoScannerForLibraryType));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -8,6 +8,6 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering music file system items.
|
||||
/// </summary>
|
||||
public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob
|
||||
{
|
||||
}
|
||||
+5
-6
@@ -3,7 +3,6 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibrary
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
@@ -30,11 +29,11 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
{
|
||||
// Declare the list of jobs that this scanner requires.
|
||||
IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||
@@ -75,7 +74,7 @@ internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
|
||||
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
|
||||
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
||||
|
||||
// Return the top level jobs that will be triggered when the scan will be started.
|
||||
yield return fileSystemDiscoveryJob;
|
||||
// The file system discovery job is the only top level job: no scanning can happen before the files are discovered.
|
||||
return fileSystemDiscoveryJob;
|
||||
}
|
||||
}
|
||||
+3
@@ -2,6 +2,7 @@
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
@@ -13,12 +14,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="ScanId">The unique identifier of the queued media library scan.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that initiated the queued media library scan.</param>
|
||||
/// <param name="LibraryId">The unique identifier of the library whose scan was queued.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record LibraryScanQueuedDomainEvent(
|
||||
Guid Id,
|
||||
ScanId ScanId,
|
||||
UserId UserId,
|
||||
LibraryId LibraryId,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+9
-7
@@ -90,11 +90,11 @@ public class LibraryScan : AggregateRoot<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> QueueScan()
|
||||
{
|
||||
// there must be no active scan for this library in the past 30 days
|
||||
// There must be no active scan for this library in the past 30 days.
|
||||
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
|
||||
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
|
||||
|
||||
_domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow));
|
||||
_domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, UserId, LibraryId, DateTime.UtcNow));
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public class LibraryScan : AggregateRoot<ScanId>
|
||||
else
|
||||
return Errors.LibraryScanning.CanOnlyStartPendingScans;
|
||||
|
||||
// there must be no active scan for this library in the past 30 days
|
||||
// There must be no active scan for this library in the past 30 days.
|
||||
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
|
||||
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
|
||||
|
||||
@@ -139,10 +139,11 @@ public class LibraryScan : AggregateRoot<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> CancelScan()
|
||||
{
|
||||
if (Status == LibraryScanJobStatus.Running)
|
||||
// A scan that is waiting in the scan queue can be cancelled just as well as one that is already executing.
|
||||
if (Status == LibraryScanJobStatus.Pending || Status == LibraryScanJobStatus.Running)
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
else
|
||||
return Errors.LibraryScanning.CanOnlyCancelRunningScans;
|
||||
return Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans;
|
||||
|
||||
_domainEvents.Add(new LibraryScanCancelledDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow));
|
||||
|
||||
@@ -155,10 +156,11 @@ public class LibraryScan : AggregateRoot<ScanId>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> FailScan()
|
||||
{
|
||||
if (Status == LibraryScanJobStatus.Running)
|
||||
// A scan can fail before it starts executing, for example when its media library type has no scanner yet.
|
||||
if (Status == LibraryScanJobStatus.Pending || Status == LibraryScanJobStatus.Running)
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
else
|
||||
return Errors.LibraryScanning.CanOnlyFailRunningScans;
|
||||
return Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans;
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
+7
-3
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -13,13 +14,16 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
public interface IMediaLibraryScanningService
|
||||
{
|
||||
/// <summary>
|
||||
/// Starts <paramref name="scan"/>.
|
||||
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||
/// </summary>
|
||||
/// <param name="scan">The media library scan to start.</param>
|
||||
/// <param name="libraryType">The type of the media library to be scanned.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the file system discovery job, which is the only top level job of the
|
||||
/// media library scan job graph and whose execution completes the entire scan, or an error.
|
||||
/// </returns>
|
||||
Task<Result<IMediaLibraryScanDiscoveryJob>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Cancels <paramref name="scan"/>.
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job that discovers the file system items of a media library.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is always the only top level job of a media library scan: a scan cannot process anything before the files are discovered.
|
||||
/// </remarks>
|
||||
public interface IMediaLibraryScanDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+37
-45
@@ -1,10 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
@@ -22,7 +22,6 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// </summary>
|
||||
internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||
private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
@@ -31,19 +30,16 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing media libraries scan jobs.</param>
|
||||
/// <param name="mediaLibraryScannerFactory">Injected factory for creating media library scanners.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
|
||||
public MediaLibraryScanningService(
|
||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||
IMediaLibraryScannerFactory mediaLibraryScannerFactory,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
||||
IDomainEventPublisher domainEventPublisher)
|
||||
{
|
||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||
_mediaLibraryScannerFactory = mediaLibraryScannerFactory;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
@@ -51,51 +47,48 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <paramref name="scan"/>.
|
||||
/// Starts <paramref name="scan"/> and prepares its job graph.
|
||||
/// </summary>
|
||||
/// <param name="scan">The media library scan to start.</param>
|
||||
/// <param name="libraryType">The type of the media library to be scanned.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken)
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the file system discovery job, which is the only top level job of the
|
||||
/// media library scan job graph and whose execution completes the entire scan, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<IMediaLibraryScanDiscoveryJob>> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken)
|
||||
{
|
||||
// mark the scan itself as started
|
||||
// Resolve the scanner before changing any state, so that a media library type without a scanner fails its own scan,
|
||||
// without leaving it started and without affecting the other scans that are queued behind it.
|
||||
Result<IMediaTypeScanner> getScannerResult = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType);
|
||||
if (getScannerResult.IsFailure)
|
||||
return getScannerResult.Errors;
|
||||
|
||||
// Build the job graph before the scan starts, so that its jobs already carry the scan identity when they report their progress,
|
||||
// and so that the total number of jobs is known for the progress tracking.
|
||||
IMediaLibraryScanDiscoveryJob rootJob = getScannerResult.Value.CreateScanJobsForLibrary(scan.LibraryId);
|
||||
SetScanPropertiesForJobChain(rootJob, scan.Id, scan.UserId);
|
||||
int totalJobs = CountTotalJobs(rootJob);
|
||||
|
||||
// Mark the scan itself as started.
|
||||
Result<Success> startScanResult = scan.StartScan();
|
||||
if (startScanResult.IsFailure)
|
||||
return startScanResult.Errors;
|
||||
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId);
|
||||
|
||||
// Register the scan in the tracker for cancellation tokens.
|
||||
_mediaLibrariesScanCancellationTracker.RegisterScan(compositeId);
|
||||
|
||||
// Initialize the progress of the scan before publishing its events, so that the handlers of the started event can already report it.
|
||||
Result<Created> initializeScanProgressResult = _mediaLibrariesScanProgressTracker.InitializeScanProgress(scan.LibraryId, compositeId, totalJobs);
|
||||
if (initializeScanProgressResult.IsFailure)
|
||||
return initializeScanProgressResult.Errors;
|
||||
|
||||
foreach (IDomainEvent domainEvent in scan.GetDomainEvents())
|
||||
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// register the scan in the tracker for cancellation tokens
|
||||
_mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId));
|
||||
|
||||
try
|
||||
{
|
||||
// link the user's cancellation token with the scan's token
|
||||
using CancellationTokenSource linkedSource = CancellationTokenSource
|
||||
.CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId)));
|
||||
|
||||
// get a media library scanner for the provided media library type
|
||||
IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType);
|
||||
// get the list of scan jobs for the retrieved scanner. It is impotant to enumerate them here, because deferred execuction would destroy any graph relationships
|
||||
// and properties we might set before putting the jobs on the in-memory queue.
|
||||
List<IMediaLibraryScanJob> jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId)];
|
||||
|
||||
// count total jobs in the chain by traversing the job graph
|
||||
int totalJobs = CountTotalJobs(jobs);
|
||||
_mediaLibrariesScanProgressTracker.InitializeScanProgress(scan.LibraryId, MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId), totalJobs);
|
||||
|
||||
// enqueue the jobs on the channel from where they will be processed
|
||||
foreach (IMediaLibraryScanJob job in jobs)
|
||||
{
|
||||
// set the Id of the scan and of the user initiating the scan to all jobs in the scan job graph
|
||||
SetScanPropertiesForJobChain(job, scan.Id, scan.UserId);
|
||||
await _mediaLibrariesScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (NotImplementedException) { }
|
||||
return Result.Success;
|
||||
return Result.From<IMediaLibraryScanDiscoveryJob>(rootJob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -105,7 +98,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> CancelScan(LibraryScan scan)
|
||||
{
|
||||
// trigger the process that cancels the jobs of the scan
|
||||
// Trigger the process that cancels the jobs of the scan.
|
||||
_mediaLibrariesScanCancellationTracker.CancelScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId));
|
||||
return Result.Success;
|
||||
}
|
||||
@@ -120,21 +113,20 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
|
||||
{
|
||||
job.ScanId = scanId;
|
||||
job.UserId = userId;
|
||||
// recursively set properties for all children
|
||||
// Recursively set properties for all children.
|
||||
foreach (IMediaLibraryScanJob childJob in job.Children)
|
||||
SetScanPropertiesForJobChain(childJob, scanId, userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the total number of unique media library scan jobs in a list of root jobs.
|
||||
/// Counts the total number of unique media library scan jobs in the job graph that starts at <paramref name="rootJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="rootJobs">A list of root media library scan jobs to traverse.</param>
|
||||
/// <param name="rootJob">The file system discovery job, which is the only top level job of the scan job graph.</param>
|
||||
/// <returns>The total count of unique media library scan jobs.</returns>
|
||||
private static int CountTotalJobs(List<IMediaLibraryScanJob> rootJobs)
|
||||
private static int CountTotalJobs(IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
HashSet<IMediaLibraryScanJob> uniqueJobs = [];
|
||||
foreach (IMediaLibraryScanJob job in rootJobs)
|
||||
TraverseJobGraph(job, uniqueJobs);
|
||||
TraverseJobGraph(rootJob, uniqueJobs);
|
||||
return uniqueJobs.Count;
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -11,6 +11,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// </summary>
|
||||
public interface IMediaLibrariesScanProgressTracker
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The object representing the unique identifier of the media library being scanned.</param>
|
||||
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Created> InitializeQueuedScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the the progress tracking of a media library scan.
|
||||
/// </summary>
|
||||
|
||||
+30
@@ -16,6 +16,36 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr
|
||||
{
|
||||
private readonly ConcurrentDictionary<MediaLibraryScanCompositeId, MediaLibraryScanProgress> _scanProgresses = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the progress tracking of a media library scan that is waiting in the scan queue, before its jobs are prepared.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The object representing the unique identifier of the media library being scanned.</param>
|
||||
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Created> InitializeQueuedScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId)
|
||||
{
|
||||
// The total number of jobs is only known once the scan starts, because the job graph is prepared at that point.
|
||||
Result<MediaLibraryScanJobProgress> createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Queued");
|
||||
if (createLibraryScanJobProgressResult.IsFailure)
|
||||
return createLibraryScanJobProgressResult.Errors;
|
||||
|
||||
Result<MediaLibraryScanProgress> createScanProgressResult = MediaLibraryScanProgress.Create(
|
||||
mediaLibraryScanCompositeId.ScanId,
|
||||
mediaLibraryScanCompositeId.UserId,
|
||||
libraryId,
|
||||
completedJobs: 0,
|
||||
totalJobs: 0,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.Some(createLibraryScanJobProgressResult.Value)
|
||||
);
|
||||
if (createScanProgressResult.IsFailure)
|
||||
return createScanProgressResult.Errors;
|
||||
|
||||
_scanProgresses[mediaLibraryScanCompositeId] = createScanProgressResult.Value;
|
||||
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the the progress tracking of a media library scan.
|
||||
/// </summary>
|
||||
|
||||
+7
-6
@@ -1,22 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System.Threading.Channels;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Interface for the message queue for handling the media library scans that are waiting to execute.
|
||||
/// Only one media library scan is executed at a time, so the queue guarantees that scans run consecutively.
|
||||
/// </summary>
|
||||
public interface IMediaLibrariesScanQueue
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelWriter<IMediaLibraryScanJob> Writer { get; }
|
||||
ChannelWriter<MediaLibraryScanCompositeId> Writer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelReader<IMediaLibraryScanJob> Reader { get; }
|
||||
ChannelReader<MediaLibraryScanCompositeId> Reader { get; }
|
||||
}
|
||||
+5
-2
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
#endregion
|
||||
|
||||
@@ -13,6 +14,8 @@ internal interface IMediaLibraryScannerFactory
|
||||
/// Creates a media library scanner based on the provided library type.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
|
||||
/// <returns>A media library scanner for the specified media library type.</returns>
|
||||
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a media library scanner for the specified media library type, or an error.
|
||||
/// </returns>
|
||||
Result<IMediaTypeScanner> CreateLibraryScanner(LibraryType libraryType);
|
||||
}
|
||||
+3
-4
@@ -2,7 +2,6 @@
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
@@ -18,9 +17,9 @@ public interface IMediaTypeScanner
|
||||
LibraryType SupportedLibraryType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId);
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId);
|
||||
}
|
||||
+11
-41
@@ -1,7 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
@@ -28,49 +30,17 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
|
||||
/// Creates a media library scanner for the specified library type.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>A media library scanner for the specified library type.</returns>
|
||||
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a media library scanner for the specified media library type, or an error.
|
||||
/// </returns>
|
||||
public Result<IMediaTypeScanner> CreateLibraryScanner(LibraryType libraryType)
|
||||
{
|
||||
return libraryType switch
|
||||
{
|
||||
// Implemented scanners.
|
||||
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
|
||||
LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."),
|
||||
LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."),
|
||||
LibraryType.Magazine => throw new NotImplementedException("Magazine scanner is not implemented."),
|
||||
LibraryType.Newspaper => throw new NotImplementedException("Newspaper scanner is not implemented."),
|
||||
LibraryType.Manga => throw new NotImplementedException("Manga scanner is not implemented."),
|
||||
LibraryType.GraphicNovel => throw new NotImplementedException("GraphicNovel scanner is not implemented."),
|
||||
LibraryType.AcademicPaper => throw new NotImplementedException("AcademicPaper scanner is not implemented."),
|
||||
LibraryType.SheetMusic => throw new NotImplementedException("SheetMusic scanner is not implemented."),
|
||||
LibraryType.Movie => throw new NotImplementedException("Movie scanner is not implemented."),
|
||||
LibraryType.TvShow => throw new NotImplementedException("TvShow scanner is not implemented."),
|
||||
LibraryType.Documentary => throw new NotImplementedException("Documentary scanner is not implemented."),
|
||||
LibraryType.Anime => throw new NotImplementedException("Anime scanner is not implemented."),
|
||||
LibraryType.ConcertVideo => throw new NotImplementedException("ConcertVideo scanner is not implemented."),
|
||||
LibraryType.TutorialVideo => throw new NotImplementedException("TutorialVideo scanner is not implemented."),
|
||||
LibraryType.HomeVideo => throw new NotImplementedException("HomeVideo scanner is not implemented."),
|
||||
LibraryType.YouTubeVideo => throw new NotImplementedException("YouTubeVideo scanner is not implemented."),
|
||||
LibraryType.MusicVideo => throw new NotImplementedException("MusicVideo scanner is not implemented."),
|
||||
LibraryType.LiveRecordingVideo => throw new NotImplementedException("LiveRecordingVideo scanner is not implemented."),
|
||||
LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."),
|
||||
LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."),
|
||||
LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."),
|
||||
LibraryType.Music => _serviceProvider.GetRequiredService<IMusicLibraryTypeScanner>(),
|
||||
LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."),
|
||||
LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."),
|
||||
LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."),
|
||||
LibraryType.CoverSongAudio => throw new NotImplementedException("CoverSongAudio scanner is not implemented."),
|
||||
LibraryType.Remix => throw new NotImplementedException("Remix scanner is not implemented."),
|
||||
LibraryType.SoundEffect => throw new NotImplementedException("SoundEffect scanner is not implemented."),
|
||||
LibraryType.PodcastAudio => throw new NotImplementedException("PodcastAudio scanner is not implemented."),
|
||||
LibraryType.Photo => throw new NotImplementedException("Photo scanner is not implemented."),
|
||||
LibraryType.Playlist => throw new NotImplementedException("Playlist scanner is not implemented."),
|
||||
LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."),
|
||||
LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."),
|
||||
LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."),
|
||||
// Catch-all for unknown or unsupported types.
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.")
|
||||
LibraryType.Book => Result.From<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IBookLibraryTypeScanner>()),
|
||||
LibraryType.Music => Result.From<IMediaTypeScanner>(_serviceProvider.GetRequiredService<IMusicLibraryTypeScanner>()),
|
||||
// Every other media library type is modeled, but has no scanner yet, so scanning it is reported as unsupported.
|
||||
_ => Errors.LibraryScanning.NoScannerForLibraryType
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -107,7 +107,8 @@ public sealed class MediaLibraryScanProgress : ValueObject
|
||||
LibraryScanJobStatus status,
|
||||
Optional<MediaLibraryScanJobProgress> currentJobProgress)
|
||||
{
|
||||
if (totalJobs <= 0)
|
||||
// A scan waiting in the scan queue has no jobs prepared yet, so its total number of jobs is only known once it starts.
|
||||
if (totalJobs < 0 || (totalJobs == 0 && status != LibraryScanJobStatus.Pending))
|
||||
return Errors.LibraryScanning.TotalScanJobsCountMustBePositive;
|
||||
if (completedJobs < 0)
|
||||
return Errors.LibraryScanning.CompletedScanJobsCountMustBePositive;
|
||||
|
||||
+1
-1
@@ -5,6 +5,6 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering books file system items.
|
||||
/// </summary>
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanDiscoveryJob
|
||||
{
|
||||
}
|
||||
+8
-9
@@ -3,7 +3,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||
@@ -30,19 +29,19 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// Creates the media library scan job graph for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
/// <returns>The file system discovery job, which is the only top level job of the media library scan job graph.</returns>
|
||||
public IMediaLibraryScanDiscoveryJob CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
{
|
||||
// declare the list of jobs that this scanner requires
|
||||
// Declare the list of jobs that this scanner requires.
|
||||
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
|
||||
// establish the hierarchical relationships between jobs
|
||||
// Establish the hierarchical relationships between jobs.
|
||||
fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
|
||||
mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
|
||||
|
||||
@@ -52,7 +51,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
|
||||
mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob);
|
||||
|
||||
// the enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration
|
||||
// The enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration
|
||||
// invalidation job invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, the
|
||||
// metadata enrichment job enriches the metadata and links the media contributors, and the artwork enrichment job resolves the artwork.
|
||||
// The artwork enrichment job is always the last job in the directed acyclic job graph, running after the metadata enrichment job, so that
|
||||
@@ -70,7 +69,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
|
||||
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
|
||||
|
||||
// return the top level jobs that will be triggered when the scan will be started
|
||||
yield return fileSystemDiscoveryJob;
|
||||
// The file system discovery job is the only top level job: no scanning can happen before the files are discovered.
|
||||
return fileSystemDiscoveryJob;
|
||||
}
|
||||
}
|
||||
@@ -112,7 +112,7 @@ public static class InfrastructureLayerServices
|
||||
// Media library scanning.
|
||||
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
||||
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
||||
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
|
||||
services.AddHostedService<MediaLibraryScanProcessorJob>();
|
||||
|
||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMusicFileSystemDiscoveryJob, MusicFileSystemDiscoveryJob>();
|
||||
|
||||
+90
-94
@@ -70,115 +70,111 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
|
||||
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
|
||||
// Convert it to a domain object.
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan.
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
|
||||
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsFailure)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
}
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
// Convert it to a domain object.
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan.
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||
if (shouldParallelizeReads)
|
||||
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
|
||||
|
||||
// Get the files for each of the media library content locations.
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fileProviderService,
|
||||
directoryProviderService,
|
||||
fingerprintsByPath is not null,
|
||||
shouldParallelizeReads,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
unitOfWork.LibraryScanStagingResultsRepository,
|
||||
unitOfWork.DirectoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsFailure)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
publishJobProgressResult = await PublishJobProgressAsync(
|
||||
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||
if (shouldParallelizeReads)
|
||||
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
|
||||
|
||||
// Get the files for each of the media library content locations.
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fileProviderService,
|
||||
directoryProviderService,
|
||||
fingerprintsByPath is not null,
|
||||
shouldParallelizeReads,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
unitOfWork.LibraryScanStagingResultsRepository,
|
||||
unitOfWork.DirectoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgressAsync(
|
||||
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+76
-80
@@ -67,86 +67,58 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository, both to verify that it exists and to know its content locations.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default.
|
||||
ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService<ILibraryPathTemplateService>()!;
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
Result<LibraryPathTemplate> pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts);
|
||||
if (pathTemplateResult.IsFailure)
|
||||
throw new InvalidOperationException(pathTemplateResult.FirstError.Description);
|
||||
LibraryPathTemplate pathTemplate = pathTemplateResult.Value;
|
||||
|
||||
// The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items.
|
||||
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
IReadOnlyList<string> paths = getPathsResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedItems = 0;
|
||||
|
||||
List<MusicLibraryScanItemMetadataEntity> metadataBatch = [];
|
||||
foreach (string path in paths)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository, both to verify that it exists and to know its content locations.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default.
|
||||
ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService<ILibraryPathTemplateService>()!;
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
Result<LibraryPathTemplate> pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts);
|
||||
if (pathTemplateResult.IsFailure)
|
||||
throw new InvalidOperationException(pathTemplateResult.FirstError.Description);
|
||||
LibraryPathTemplate pathTemplate = pathTemplateResult.Value;
|
||||
|
||||
// The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items.
|
||||
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
IReadOnlyList<string> paths = getPathsResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedItems = 0;
|
||||
|
||||
List<MusicLibraryScanItemMetadataEntity> metadataBatch = [];
|
||||
foreach (string path in paths)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService));
|
||||
if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE)
|
||||
{
|
||||
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
|
||||
metadataBatch.Clear();
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
}
|
||||
processedItems++;
|
||||
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush any remaining extracted metadata items that did not reach the batch size.
|
||||
if (metadataBatch.Count > 0)
|
||||
metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService));
|
||||
if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE)
|
||||
{
|
||||
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
@@ -154,16 +126,40 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
|
||||
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
|
||||
metadataBatch.Clear();
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
}
|
||||
processedItems++;
|
||||
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Flush any remaining extracted metadata items that did not reach the batch size.
|
||||
if (metadataBatch.Count > 0)
|
||||
{
|
||||
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveBatchResult.IsFailure)
|
||||
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+27
-31
@@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Load the media library, whose type determines the artwork enricher to use.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
// Load the media library, whose type determines the artwork enricher to use.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
|
||||
IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanArtworkEnricher>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (artworkEnricher is null)
|
||||
throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'.");
|
||||
IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanArtworkEnricher>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (artworkEnricher is null)
|
||||
throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'.");
|
||||
|
||||
await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
|
||||
await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+27
-31
@@ -45,47 +45,43 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
// Set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// mark the staging results against the media library scan snapshot of the previous scan
|
||||
Result<Updated> markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (markChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||
// Mark the staging results against the media library scan snapshot of the previous scan.
|
||||
Result<Updated> markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (markChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+73
-77
@@ -49,99 +49,95 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Count the files that need hashing, for progress reporting purposes.
|
||||
Result<int> getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashCountResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
||||
int totalFilesToHash = getFilesToHashCountResult.Value;
|
||||
|
||||
// Get the library only when there are files to hash, and only the scalar values needed to know whether its content is stored on a solid state drive.
|
||||
// in which case the file reads run in parallel.
|
||||
bool shouldParallelizeReads = false;
|
||||
if (totalFilesToHash > 0)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(
|
||||
LibraryId.Value,
|
||||
shouldIncludeNavigationProperties: false,
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
shouldParallelizeReads = getLibraryResult.Value.IsContentOnSsd;
|
||||
}
|
||||
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedFilesCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// count the files that need hashing, for progress reporting purposes
|
||||
Result<int> getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashCountResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
||||
int totalFilesToHash = getFilesToHashCountResult.Value;
|
||||
// Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size.
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the library only when there are files to hash, and only the scalar values needed to know whether its content is stored on a solid state drive,.
|
||||
// in which case the file reads run in parallel.
|
||||
bool shouldParallelizeReads = false;
|
||||
if (totalFilesToHash > 0)
|
||||
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFileDto> filesToHashPage = getFilesToHashPageResult.Value;
|
||||
if (filesToHashPage.Count == 0)
|
||||
break;
|
||||
|
||||
// Hash the files of the current page in parallel, invoking the progress callback before each file.
|
||||
List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () =>
|
||||
{
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(
|
||||
LibraryId.Value,
|
||||
shouldIncludeNavigationProperties: false,
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
shouldParallelizeReads = getLibraryResult.Value.IsContentOnSsd;
|
||||
}
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedFilesCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size.
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFileDto> filesToHashPage = getFilesToHashPageResult.Value;
|
||||
if (filesToHashPage.Count == 0)
|
||||
break;
|
||||
|
||||
// Hash the files of the current page in parallel, invoking the progress callback before each file.
|
||||
List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () =>
|
||||
// Check if enough time has passed since last update.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// Check if enough time has passed since last update.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Write the computed hashes back to the staging results.
|
||||
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||
if (updateHashesResult.IsFailure)
|
||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||
// Write the computed hashes back to the staging results.
|
||||
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||
if (updateHashesResult.IsFailure)
|
||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||
|
||||
lastPath = filesToHashPage[^1].Path;
|
||||
}
|
||||
lastPath = filesToHashPage[^1].Path;
|
||||
}
|
||||
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+27
-31
@@ -47,48 +47,44 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Load the media library, whose type determines the metadata enricher to use.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
// Load the media library, whose type determines the metadata enricher to use.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
|
||||
IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanMetadataEnricher>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (metadataEnricher is null)
|
||||
throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'.");
|
||||
IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanMetadataEnricher>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (metadataEnricher is null)
|
||||
throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'.");
|
||||
|
||||
await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
|
||||
await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+97
-101
@@ -54,124 +54,120 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
|
||||
// are compared against the current provider configuration to detect whether it changed since the last scan.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The type of the media library determines the materializer whose enrichment state is invalidated.
|
||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType);
|
||||
if (materializer is null)
|
||||
throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'.");
|
||||
|
||||
// Load the provider configurations of the media library, whose fingerprint is compared against the stored one.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
|
||||
|
||||
// Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing.
|
||||
bool shouldAggregateMetadataWhenMissing = false;
|
||||
bool shouldAggregateArtworkWhenMissing = false;
|
||||
if (unitOfWork.UserSettingsRepository is not null)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
|
||||
// are compared against the current provider configuration to detect whether it changed since the last scan.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The type of the media library determines the materializer whose enrichment state is invalidated.
|
||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType);
|
||||
if (materializer is null)
|
||||
throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'.");
|
||||
|
||||
// Load the provider configurations of the media library, whose fingerprint is compared against the stored one.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
|
||||
|
||||
// Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing.
|
||||
bool shouldAggregateMetadataWhenMissing = false;
|
||||
bool shouldAggregateArtworkWhenMissing = false;
|
||||
if (unitOfWork.UserSettingsRepository is not null)
|
||||
Result<UserSettingsEntity?> getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserSettingsResult.IsFailure)
|
||||
_logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings.");
|
||||
else
|
||||
{
|
||||
Result<UserSettingsEntity?> getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserSettingsResult.IsFailure)
|
||||
_logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings.");
|
||||
else
|
||||
{
|
||||
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
|
||||
shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false;
|
||||
}
|
||||
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
|
||||
shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
|
||||
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
|
||||
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||
string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]);
|
||||
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
|
||||
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
|
||||
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||
string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]);
|
||||
|
||||
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
|
||||
{
|
||||
Result<Updated> resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetMetadataResult.IsFailure)
|
||||
throw new InvalidOperationException(resetMetadataResult.FirstError.Description);
|
||||
}
|
||||
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
|
||||
{
|
||||
Result<Updated> resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetMetadataResult.IsFailure)
|
||||
throw new InvalidOperationException(resetMetadataResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well.
|
||||
if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint)
|
||||
{
|
||||
Result<Updated> resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetPathTemplateMetadataResult.IsFailure)
|
||||
throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description);
|
||||
}
|
||||
// A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well.
|
||||
if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint)
|
||||
{
|
||||
Result<Updated> resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetPathTemplateMetadataResult.IsFailure)
|
||||
throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description);
|
||||
}
|
||||
|
||||
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
|
||||
{
|
||||
Result<Updated> resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetArtworkResult.IsFailure)
|
||||
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
|
||||
}
|
||||
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
|
||||
{
|
||||
Result<Updated> resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetArtworkResult.IsFailure)
|
||||
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
|
||||
// The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
|
||||
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed.
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
library.PathTemplateFingerprint = pathTemplateFingerprint;
|
||||
library.UpdatedOnUtc = DateTime.UtcNow;
|
||||
library.UpdatedBy = Guid.NewGuid();
|
||||
// Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
|
||||
// The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
|
||||
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed.
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
library.PathTemplateFingerprint = pathTemplateFingerprint;
|
||||
library.UpdatedOnUtc = DateTime.UtcNow;
|
||||
library.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+80
-84
@@ -48,104 +48,100 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Load the media library, whose type determines the materializer used to create the media library items.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
|
||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (materializer is null)
|
||||
throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'.");
|
||||
|
||||
// Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them.
|
||||
Result<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getDeletedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
||||
|
||||
// Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched.
|
||||
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getChangedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
|
||||
|
||||
// Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan.
|
||||
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (applySnapshotSwapResult.IsFailure)
|
||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||
|
||||
// Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow.
|
||||
if (getChangedPathsResult.Value.Count > 0)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<Updated> resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetEnrichmentStateResult.IsFailure)
|
||||
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
|
||||
}
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
// Raise a deletion event for every media library scan snapshot item that is no longer present on disk.
|
||||
foreach (string deletedPath in getDeletedPathsResult.Value)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Load the media library, whose type determines the materializer used to create the media library items.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryType libraryType = getLibraryResult.Value.LibraryType;
|
||||
// Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata.
|
||||
Result<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
|
||||
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanItemMaterializer>()
|
||||
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
|
||||
if (materializer is null)
|
||||
throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'.");
|
||||
Result<Success> materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (materializeItemsResult.IsFailure)
|
||||
throw new InvalidOperationException(materializeItemsResult.FirstError.Description);
|
||||
|
||||
// Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them.
|
||||
Result<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getDeletedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
||||
// The staged data is only cleared once the materialized items are safely stored, so a failed save can be retried from the same staged data.
|
||||
Result<Deleted> clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (clearStagedDataResult.IsFailure)
|
||||
throw new InvalidOperationException(clearStagedDataResult.FirstError.Description);
|
||||
|
||||
// Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched.
|
||||
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getChangedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan.
|
||||
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (applySnapshotSwapResult.IsFailure)
|
||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow.
|
||||
if (getChangedPathsResult.Value.Count > 0)
|
||||
{
|
||||
Result<Updated> resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resetEnrichmentStateResult.IsFailure)
|
||||
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// Raise a deletion event for every media library scan snapshot item that is no longer present on disk.
|
||||
foreach (string deletedPath in getDeletedPathsResult.Value)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata.
|
||||
Result<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
|
||||
Result<Success> materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (materializeItemsResult.IsFailure)
|
||||
throw new InvalidOperationException(materializeItemsResult.FirstError.Description);
|
||||
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// The staged data is only cleared once the materialized items are safely stored, so a failed save can be retried from the same staged data.
|
||||
Result<Deleted> clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (clearStagedDataResult.IsFailure)
|
||||
throw new InvalidOperationException(clearStagedDataResult.FirstError.Description);
|
||||
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Increment the number of completed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+87
-91
@@ -75,111 +75,107 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
|
||||
// Convert it to a domain object.
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan.
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsFailure)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
}
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// Get the library from the repository.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
// Convert it to a domain object.
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan.
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||
if (shouldParallelizeReads)
|
||||
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
|
||||
|
||||
// Get the files for each of the media library content locations.
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fingerprintsByPath is not null,
|
||||
shouldParallelizeReads,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
unitOfWork.LibraryScanStagingResultsRepository,
|
||||
unitOfWork.DirectoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsFailure)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
publishJobProgressResult = await PublishJobProgressAsync(
|
||||
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
|
||||
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
|
||||
if (shouldParallelizeReads)
|
||||
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
|
||||
|
||||
// Get the files for each of the media library content locations.
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fingerprintsByPath is not null,
|
||||
shouldParallelizeReads,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
unitOfWork.LibraryScanStagingResultsRepository,
|
||||
unitOfWork.DirectoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgressAsync(
|
||||
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// This job finished, increment the number of processed jobs progress.
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
|
||||
+23
-2
@@ -46,11 +46,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
// throttle network traffic to no more than 20 updates a second, any more are pointless from a progress report perspective
|
||||
// Throttle network traffic to no more than 20 updates a second, any more are pointless from a progress report perspective.
|
||||
DebounceDispatcher debouncer = _debouncers.GetOrAdd(mediaLibraryScanCompositeId, _ => new DebounceDispatcher(TimeSpan.FromMilliseconds(50)));
|
||||
await debouncer.DebounceAsync(async () =>
|
||||
{
|
||||
// the token might be canceled after initial check but before debounced execution starts
|
||||
// The token might be canceled after initial check but before debounced execution starts.
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
@@ -105,6 +105,27 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the cancellation of a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that was cancelled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SendLibraryScanCancelledEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return;
|
||||
Result<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
|
||||
|
||||
CleanupDebouncer(mediaLibraryScanCompositeId);
|
||||
|
||||
if (!progressResult.IsFailure)
|
||||
{
|
||||
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
|
||||
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(
|
||||
"libraryScanCancelledEvent", progress with { Status = LibraryScanJobStatus.Canceled.ToString() }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the debouncer that was used in a scan identified by <paramref name="mediaLibraryScanCompositeId"/>, that is now completed.
|
||||
/// </summary>
|
||||
|
||||
+7
-6
@@ -1,25 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System.Threading.Channels;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Provides an in-memory message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Provides an in-memory message queue for handling the media library scans that are waiting to execute.
|
||||
/// </summary>
|
||||
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
|
||||
{
|
||||
private readonly Channel<IMediaLibraryScanJob> _channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
|
||||
private readonly Channel<MediaLibraryScanCompositeId> _channel = Channel.CreateUnbounded<MediaLibraryScanCompositeId>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the writer for the queue, allowing producers to enqueue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelWriter<IMediaLibraryScanJob> Writer => _channel.Writer;
|
||||
public ChannelWriter<MediaLibraryScanCompositeId> Writer => _channel.Writer;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue the scans that are waiting to execute.
|
||||
/// </summary>
|
||||
public ChannelReader<IMediaLibraryScanJob> Reader => _channel.Reader;
|
||||
public ChannelReader<MediaLibraryScanCompositeId> Reader => _channel.Reader;
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Background service for processing media library scan jobs from an in-memory message queue.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker)
|
||||
{
|
||||
_mediaScanQueue = mediaScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method called when the background service starts.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// continuously processes and executes media library scan jobs from the queue until the application shuts down
|
||||
// remark: since only top level scan jobs are placed on the bus, but they themselves trigger the execution of their children jobs, and so on,
|
||||
// their completion should not be awaited here due to some of them being long running tasks; therefor they are just fired synchronously
|
||||
// without being awaited, while still properly handling any exceptions they might throw in their asynchronous execution
|
||||
await foreach (IMediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// get the cancellation token that was associated with this library scan
|
||||
CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(mediaScanJob.ScanId, mediaScanJob.UserId));
|
||||
// create linked token to handle both scan cancellation and service shutdown
|
||||
CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, scanToken);
|
||||
mediaScanJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).FireAndForgetSafeAsync(() => linkedSource.Dispose());
|
||||
}
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that executes the queued media library scans one at a time, in the order in which they were queued.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanProcessorJob : BackgroundService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaLibrariesScanQueue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanProcessorJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProcessorJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibrariesScanQueue">Injected queue used for processing the media library scans that are waiting to execute.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
|
||||
/// <param name="logger">Injected service for logging.</param>
|
||||
public MediaLibraryScanProcessorJob(
|
||||
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IServiceScopeFactory serviceScopeFactory,
|
||||
ILogger<MediaLibraryScanProcessorJob> logger)
|
||||
{
|
||||
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method called when the background service starts.
|
||||
/// </summary>
|
||||
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
// The queue is only drained here, one scan at a time: only after the job graph of the current scan completes is the next scan dequeued,
|
||||
// so at most one media library scan executes at any moment, regardless of how many scans were queued at once.
|
||||
await foreach (MediaLibraryScanCompositeId compositeId in _mediaLibrariesScanQueue.Reader.ReadAllAsync(stoppingToken).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await ProcessScanAsync(compositeId, stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// A scan that fails must never stop the scans that are queued behind it, so its failure is logged and the queue keeps draining.
|
||||
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a single queued media library scan, from its preparation to the completion of its job graph.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">Model for tracking the queued media library scan.</param>
|
||||
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private async Task ProcessScanAsync(MediaLibraryScanCompositeId compositeId, CancellationToken stoppingToken)
|
||||
{
|
||||
// Get the token that cancels this scan, and do not start the scan at all when it was already cancelled while it was waiting for its turn.
|
||||
CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(compositeId);
|
||||
if (scanToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
// The scan must stop both when the user cancels it and when the application shuts down, so the two are linked into a single token
|
||||
// that is passed to everything the scan does. Disposing the source when the scan is over releases its registrations on both tokens.
|
||||
using CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, scanToken);
|
||||
|
||||
LibraryId? libraryId = null;
|
||||
|
||||
try
|
||||
{
|
||||
LibraryScan libraryScan;
|
||||
LibraryType libraryType;
|
||||
|
||||
// Resolve the scan in a short lived scope, so that its unit of work and its DbContext are released before the scan starts executing.
|
||||
await using (AsyncServiceScope readScope = _serviceScopeFactory.CreateAsyncScope())
|
||||
{
|
||||
IUnitOfWork unitOfWork = readScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
||||
Result<LibraryScanEntity?> getLibraryScanResult = await unitOfWork.LibraryScanRepository.GetByIdAsync(
|
||||
compositeId.ScanId.Value, shouldTrackEntities: false, cancellationToken: linkedSource.Token).ConfigureAwait(false);
|
||||
if (getLibraryScanResult.IsFailure)
|
||||
{
|
||||
_logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description);
|
||||
return;
|
||||
}
|
||||
|
||||
LibraryScanEntity? libraryScanEntity = getLibraryScanResult.Value;
|
||||
// A scan that is not pending any more was cancelled or failed while it was waiting for its turn.
|
||||
if (libraryScanEntity is null || libraryScanEntity.Status != LibraryScanJobStatus.Pending)
|
||||
return;
|
||||
|
||||
Result<LibraryScan> libraryScanDomainResult = libraryScanEntity.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
{
|
||||
await ReportScanFailureAsync(compositeId, LibraryId.Create(libraryScanEntity.LibraryId), new InvalidOperationException(libraryScanDomainResult.FirstError.Description), linkedSource.Token).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
libraryScan = libraryScanDomainResult.Value;
|
||||
libraryType = libraryScanEntity.Library.LibraryType;
|
||||
libraryId = libraryScan.LibraryId;
|
||||
}
|
||||
|
||||
IMediaLibraryScanDiscoveryJob rootJob;
|
||||
// The job graph is prepared in its own short lived scope: the jobs create their own scopes for their persistence work.
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using (AsyncServiceScope prepareScope = _serviceScopeFactory.CreateAsyncScope())
|
||||
{
|
||||
IMediaLibraryScanningService mediaLibraryScanningService = prepareScope.ServiceProvider.GetRequiredService<IMediaLibraryScanningService>();
|
||||
Result<IMediaLibraryScanDiscoveryJob> startScanResult = await mediaLibraryScanningService.StartScanAsync(libraryScan, libraryType, linkedSource.Token).ConfigureAwait(false);
|
||||
if (startScanResult.IsFailure)
|
||||
{
|
||||
// The failure is reported for this scan only, so the scans that are queued behind it are still processed.
|
||||
await ReportScanFailureAsync(compositeId, libraryScan.LibraryId, new InvalidOperationException(startScanResult.FirstError.Description), linkedSource.Token).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
rootJob = startScanResult.Value;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
|
||||
|
||||
// The file system discovery job is the only top level job of the scan job graph, and every job awaits its children, so awaiting it
|
||||
// completes the entire scan. The next queued scan is only dequeued once this call returns.
|
||||
await rootJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// The scan was cancelled, or the application is shutting down, and the cancellation handler already reported it. Either way, the queue moves on.
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// An unexpected preparation failure must still leave the scan failed instead of pending forever, and must not affect the scans queued behind it.
|
||||
// The failure is reported without a cancellation token, because the scan token may already be cancelled and the report must still be published.
|
||||
if (libraryId is null)
|
||||
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
|
||||
else
|
||||
await ReportScanFailureAsync(compositeId, libraryId, exception, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the failure of a single media library scan, without affecting the scans that are queued behind it.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">Model for tracking the failed media library scan.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan failed.</param>
|
||||
/// <param name="exception">The exception that describes the failure.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private async Task ReportScanFailureAsync(MediaLibraryScanCompositeId compositeId, LibraryId libraryId, Exception exception, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value);
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, libraryId, compositeId, exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@ namespace Lumina.Infrastructure.Core.Security;
|
||||
/// </summary>
|
||||
internal class FileHashService : IFileHashService
|
||||
{
|
||||
private const int SAMPLE_COUNT = 6; // number of sample points for hash computation
|
||||
private const ushort DEFAULT_BUFFER_SIZE = 65535; // buffer size (64KB - 1) for reading file chunks
|
||||
private static readonly ThreadLocal<XxHash64> s_threadLocalHasher = new(() => new XxHash64()); // thread-local hasher to avoid contention and pool management overhead during parallel processing
|
||||
private const int SAMPLE_COUNT = 6; // Number of sample points for hash computation.
|
||||
private const ushort DEFAULT_BUFFER_SIZE = 65535; // Buffer size (64KB - 1) for reading file chunks.
|
||||
private static readonly ThreadLocal<XxHash64> s_threadLocalHasher = new(() => new XxHash64()); // Thread-local hasher to avoid contention and pool management overhead during parallel processing.
|
||||
private static readonly ulong s_emptyFileHash = ComputeEmptyHash();
|
||||
|
||||
/// <summary>
|
||||
@@ -37,10 +37,11 @@ internal class FileHashService : IFileHashService
|
||||
object listLock = new();
|
||||
|
||||
// Solid state drives benefit from reading multiple files at once, while mechanical hard drives are faster with sequential reads because of their seek time.
|
||||
// One logical processor is deliberately left out of the scan, so that the rest of the process, the web server included, keeps a processor available to it.
|
||||
ParallelOptions parallelOptions = new()
|
||||
{
|
||||
CancellationToken = cancellationToken,
|
||||
MaxDegreeOfParallelism = shouldParallelizeReads ? Environment.ProcessorCount : 1
|
||||
MaxDegreeOfParallelism = shouldParallelizeReads ? Math.Max(1, Environment.ProcessorCount - 1) : 1
|
||||
};
|
||||
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
|
||||
{
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ public class ScanLibrariesEndpointSummary : Summary<ScanLibrariesEndpoint, Empty
|
||||
public ScanLibrariesEndpointSummary()
|
||||
{
|
||||
Summary = "Triggers the scan of all media libraries.";
|
||||
Description = "Starts the scanning process of all media libraries of a user, or all libraries, if the user is an Admin.";
|
||||
Description = "Queues the scanning process of all media libraries of a user, or all libraries if the user is an Admin. The scans run one at a time, in the order in which they were queued.";
|
||||
|
||||
Response(200, "The media libraries scan was successfully started.",
|
||||
example: new MediaLibraryScanResponse[] {
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, ScanLibra
|
||||
public ScanLibraryEndpointSummary()
|
||||
{
|
||||
Summary = "Triggers the scan of a media library.";
|
||||
Description = "Starts the scanning process of a media library of a user.";
|
||||
Description = "Queues the scanning process of a media library of a user. Queued scans run one at a time.";
|
||||
|
||||
ExampleRequest = new ScanLibraryRequest(
|
||||
Id: Guid.NewGuid()
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels the running scans of all the media libraries.
|
||||
/// Cancels the running and queued scans of all the media libraries.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ public class CancelLibrariesScanEndpointSummary : Summary<CancelLibrariesScanEnd
|
||||
public CancelLibrariesScanEndpointSummary()
|
||||
{
|
||||
Summary = "Cancels the scan of all the media libraries.";
|
||||
Description = "Cancels the running scans of all the media libraries.";
|
||||
Description = "Cancels the running and queued scans of all the media libraries.";
|
||||
|
||||
Response(200, "The scan of all media libraries is cancelled.", example: new SuccessResponse(true));
|
||||
}
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ public class CancelLibraryScanEndpoint : BaseEndpoint<CancelLibraryScanRequest,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels a running scan of a media library.
|
||||
/// Cancels a running or queued scan of a media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the media library and of the scan to cancel.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ public class CancelLibraryScanEndpointSummary : Summary<CancelLibraryScanEndpoin
|
||||
public CancelLibraryScanEndpointSummary()
|
||||
{
|
||||
Summary = "Cancels the scan of a media library.";
|
||||
Description = "Cancels a running scan of the media library identified by the route.";
|
||||
Description = "Cancels a running or queued scan of the media library identified by the route.";
|
||||
|
||||
RequestParam(r => r.LibraryId, "The unique identifier of the media library whose scan is cancelled. Required.");
|
||||
RequestParam(r => r.ScanId, "The Id of the scan to cancel. Required.");
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ public class GetRunningLibraryScansEndpointSummary : Summary<GetRunningLibrarySc
|
||||
public GetRunningLibraryScansEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves the running media library scans.";
|
||||
Description = "Retrieves the collection of ongoing media library scans.";
|
||||
Description = "Retrieves the collection of ongoing media library scans, including the scans waiting in the scan queue.";
|
||||
|
||||
Response(200, "The collection of ongoing media library scans is returned.", example: new SuccessResponse<LibraryScanProgressDto[]>(true, default));
|
||||
}
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>إلغاء الفحص</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>جارٍ الإلغاء</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>كتاب هزلي</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>برنامج إذاعي</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>في قائمة الانتظار</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>ريمكس</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Scan Abbrechen</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Wird abgebrochen</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic-Heft</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radiosendung</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>In Warteschlange</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Neuabmischung</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancel Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelling</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic Book</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radio Show</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>Queued</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancelar Escaneo</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelando</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Cómic</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Programa de Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>En cola</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remezcla</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Annuler Le Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Annulation en cours</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Bande Dessinée</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Émission Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>En file d'attente</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remixage</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Annulla Scansione</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Annullamento in corso</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Fumetto</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Programma Radiofonico</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>In coda</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remissaggio</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>スキャンを中止</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>キャンセル中</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>漫画</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>ラジオ番組</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>待機中</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>リミックス</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Cancel Scan</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Cancelling</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Comic Book</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Radio Show</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>Queued</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Anulează Scanarea</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Se anulează</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Bandă Desenată</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Emisiune Radio</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>În așteptare</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Remix</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>Скасувати Сканування</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>Скасування</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>Комікс</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>Радіопередача</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>У черзі</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>Ремікс</value>
|
||||
</data>
|
||||
|
||||
@@ -141,6 +141,9 @@
|
||||
<data name="CancelScan" xml:space="preserve">
|
||||
<value>取消扫描</value>
|
||||
</data>
|
||||
<data name="Cancelling" xml:space="preserve">
|
||||
<value>正在取消</value>
|
||||
</data>
|
||||
<data name="ComicBook" xml:space="preserve">
|
||||
<value>漫画</value>
|
||||
</data>
|
||||
@@ -249,6 +252,9 @@
|
||||
<data name="RadioShow" xml:space="preserve">
|
||||
<value>广播节目</value>
|
||||
</data>
|
||||
<data name="Queued" xml:space="preserve">
|
||||
<value>排队中</value>
|
||||
</data>
|
||||
<data name="Remix" xml:space="preserve">
|
||||
<value>混音版</value>
|
||||
</data>
|
||||
|
||||
@@ -168,7 +168,8 @@
|
||||
const jsLocalizedLibraryScanStatuses = {
|
||||
Completed: '@_localizer["Completed"]',
|
||||
Failed: '@_localizer["Failed"]',
|
||||
Canceled: '@_localizer["Canceled"]'
|
||||
Canceled: '@_localizer["Canceled"]',
|
||||
Cancelling: '@_localizer["Cancelling"]'
|
||||
};
|
||||
const jsLocalizedLibraryScanJobsStatuses = {
|
||||
DiscoveringFiles: '@_localizer["DiscoveringFiles"]',
|
||||
@@ -178,7 +179,8 @@
|
||||
SavingScanData: '@_localizer["SavingScanData"]',
|
||||
InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]',
|
||||
EnrichingMetadata: '@_localizer["EnrichingMetadata"]',
|
||||
ResolvingArtwork: '@_localizer["ResolvingArtwork"]'
|
||||
ResolvingArtwork: '@_localizer["ResolvingArtwork"]',
|
||||
Queued: '@_localizer["Queued"]'
|
||||
};
|
||||
const jsLocalizedLibraryTypes = {
|
||||
Book: '@_localizer["Book"]',
|
||||
@@ -307,12 +309,17 @@
|
||||
|
||||
row.setAttribute('data-scan-id', scan.scanId);
|
||||
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[scan.currentJobProgress.currentOperation];
|
||||
// A queued scan has no progress to show yet, so only its waiting state is displayed.
|
||||
const currentOperation = scan.currentJobProgress.currentOperation;
|
||||
const isQueued = currentOperation === 'Queued';
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[currentOperation] ?? currentOperation;
|
||||
statusSpan.classList.remove('hidden');
|
||||
|
||||
scanProgress.classList.remove('hidden');
|
||||
totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`;
|
||||
jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`;
|
||||
scanProgress.classList.toggle('hidden', isQueued);
|
||||
if (!isQueued) {
|
||||
totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`;
|
||||
jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`;
|
||||
}
|
||||
|
||||
scanIcon.classList.add('hidden');
|
||||
cancelScanIcon.classList.remove('hidden');
|
||||
@@ -369,6 +376,12 @@
|
||||
scanIcon.classList.add('hidden');
|
||||
cancelScanIcon.classList.remove('hidden');
|
||||
|
||||
// The scan is queued until its turn comes, so it has no progress to show yet.
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses['Queued'];
|
||||
statusSpan.classList.remove('hidden');
|
||||
row.querySelector('.scan-progress').classList.add('hidden');
|
||||
|
||||
const scanId = scan.scanId;
|
||||
await signalRConnection.invoke('SubscribeToScan', scanId);
|
||||
}
|
||||
@@ -401,6 +414,12 @@
|
||||
scanIcon.classList.add('hidden');
|
||||
cancelScanIcon.classList.remove('hidden');
|
||||
|
||||
// The scan is queued until its turn comes, so it has no progress to show yet.
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses['Queued'];
|
||||
statusSpan.classList.remove('hidden');
|
||||
row.querySelector('.scan-progress').classList.add('hidden');
|
||||
|
||||
const scanId = success.scanId;
|
||||
await signalRConnection.invoke('SubscribeToScan', scanId);
|
||||
}
|
||||
@@ -410,29 +429,20 @@
|
||||
// On cancel all libraries scan button click.
|
||||
const handleCancelLibrariesScanClick = async function(e) {
|
||||
await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARIES_SCAN)', {});
|
||||
btnCancelLibrariesScan.style.display = 'none';
|
||||
btnScanAllLibraries.style.display = 'block';
|
||||
|
||||
// Toggle icons for all active scan rows.
|
||||
// The cancellations are only applied once the server confirms each one, so the cancel button stays hidden meanwhile.
|
||||
btnCancelLibrariesScan.style.display = 'none';
|
||||
|
||||
// Ask all active scan rows to show that their cancellation is in progress.
|
||||
const rows = document.querySelectorAll('tr[data-scan-id]');
|
||||
|
||||
rows.forEach(row => {
|
||||
// Remove the scan Id, its no longer being scanned.
|
||||
row.removeAttribute('data-scan-id');
|
||||
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`;
|
||||
const scanProgress = row.querySelector('.scan-progress');
|
||||
scanProgress.classList.add('hidden');
|
||||
|
||||
// Show scan status icon.
|
||||
const completedIdon = row.querySelector('img[src*="yellow.png"]');
|
||||
completedIdon.classList.remove('hidden');
|
||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`;
|
||||
statusSpan.classList.remove('hidden');
|
||||
|
||||
// Toggle scan action icons.
|
||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
||||
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||
scanIcon.classList.remove('hidden');
|
||||
cancelScanIcon.classList.add('hidden');
|
||||
});
|
||||
};
|
||||
@@ -441,6 +451,7 @@
|
||||
const handleCancelLibraryScanClick = async function(e) {
|
||||
if (e.target.matches('img[src*="stop.svg"]')) {
|
||||
const row = e.target.closest('tr');
|
||||
const scanId = row.getAttribute('data-scan-id');
|
||||
|
||||
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARY_SCAN, new { libraryId = default(Guid), scanId = default(Guid) })';
|
||||
|
||||
@@ -460,29 +471,18 @@
|
||||
).join('/');
|
||||
|
||||
await callApiPostAsync(finalUrl);
|
||||
|
||||
// Remove the scan Id, its no longer being scanned.
|
||||
row.removeAttribute('data-scan-id');
|
||||
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`;
|
||||
const scanProgress = row.querySelector('.scan-progress');
|
||||
scanProgress.classList.add('hidden');
|
||||
// The cancellation is only applied once the server confirms it, so the scan keeps its Id and is shown as being cancelled meanwhile.
|
||||
// The server might have confirmed it already, in which case the row no longer carries the Id and is left as it is.
|
||||
if (row.getAttribute('data-scan-id') === scanId) {
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Cancelling']}.`;
|
||||
statusSpan.classList.remove('hidden');
|
||||
|
||||
// Show scan status icon.
|
||||
const completedIdon = row.querySelector('img[src*="yellow.png"]');
|
||||
completedIdon.classList.remove('hidden');
|
||||
|
||||
// Toggle scan action icons.
|
||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
||||
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||
scanIcon.classList.remove('hidden');
|
||||
cancelScanIcon.classList.add('hidden');
|
||||
|
||||
// Toggle scan action buttons.
|
||||
const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0;
|
||||
btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none';
|
||||
btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block';
|
||||
// Toggle scan action icons.
|
||||
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||
cancelScanIcon.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -502,17 +502,21 @@
|
||||
const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`);
|
||||
rows.forEach(row => {
|
||||
// Update status text.
|
||||
const currentOperation = progress.currentJobProgress.currentOperation;
|
||||
const isQueued = currentOperation === 'Queued';
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[progress.currentJobProgress.currentOperation];
|
||||
statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[currentOperation] ?? currentOperation;
|
||||
statusSpan.classList.remove('hidden');
|
||||
|
||||
// Update progress bars.
|
||||
// Update progress bars. A queued scan has no progress to show yet.
|
||||
const scanProgress = row.querySelector('.scan-progress');
|
||||
const totalProgressDiv = row.querySelector('.scan-progress-total > div');
|
||||
const jobProgressDiv = row.querySelector('.scan-progress-job > div');
|
||||
scanProgress.classList.remove('hidden');
|
||||
totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`;
|
||||
jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`;
|
||||
scanProgress.classList.toggle('hidden', isQueued);
|
||||
if (!isQueued) {
|
||||
totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`;
|
||||
jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`;
|
||||
}
|
||||
|
||||
// Toggle scan action icons.
|
||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
||||
@@ -576,10 +580,38 @@
|
||||
btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block';
|
||||
};
|
||||
|
||||
// Scan cancellation handler.
|
||||
const cancelledHandler = (progress) => {
|
||||
const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`);
|
||||
rows.forEach(row => {
|
||||
// Remove the scan Id, its no longer being scanned.
|
||||
row.removeAttribute('data-scan-id');
|
||||
|
||||
const statusSpan = row.querySelector('.scan-job-status');
|
||||
statusSpan.textContent = `${jsLocalizedLibraryScanStatuses[progress.status]}.`;
|
||||
const scanProgress = row.querySelector('.scan-progress');
|
||||
scanProgress.classList.add('hidden');
|
||||
|
||||
// Show scan status icon.
|
||||
const canceledIdon = row.querySelector('img[src*="yellow.png"]');
|
||||
canceledIdon.classList.remove('hidden');
|
||||
|
||||
// Toggle scan action icons.
|
||||
const scanIcon = row.querySelector('img[src*="trigger.svg"]');
|
||||
const cancelScanIcon = row.querySelector('img[src*="stop.svg"]');
|
||||
scanIcon.classList.remove('hidden');
|
||||
cancelScanIcon.classList.add('hidden');
|
||||
});
|
||||
const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0;
|
||||
btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none';
|
||||
btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block';
|
||||
};
|
||||
|
||||
// Subscribe to events.
|
||||
signalRConnection.on("libraryScanProgressUpdateEvent", progressHandler);
|
||||
signalRConnection.on("libraryScanFinishedEvent", completionHandler);
|
||||
signalRConnection.on("libraryScanFailedEvent", failureHandler);
|
||||
signalRConnection.on("libraryScanCancelledEvent", cancelledHandler);
|
||||
signalRConnection.onclose(onClose);
|
||||
signalRConnection.onreconnecting(onReconnecting);
|
||||
signalRConnection.onreconnected(onReconnected);
|
||||
@@ -588,6 +620,7 @@
|
||||
signalRConnection.off("libraryScanProgressUpdateEvent", progressHandler);
|
||||
signalRConnection.off("libraryScanFinishedEvent", completionHandler);
|
||||
signalRConnection.off("libraryScanFailedEvent", failureHandler);
|
||||
signalRConnection.off("libraryScanCancelledEvent", cancelledHandler);
|
||||
signalRConnection.off("close", onClose);
|
||||
signalRConnection.off("reconnecting", onReconnecting);
|
||||
signalRConnection.off("reconnected", onReconnected);
|
||||
|
||||
Reference in new issue
Block a user