mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03:11:10 +00:00
Serializes media library scans through a scan queue
Replaces the job queue with a scan queue that executes one media library scan at a time, in the order in which the scans were queued, so several libraries requested at once no longer run one complete job chain each on the thread pool shared with the web server. Keeps queued scans Pending and cancellable, reports them as queued, and cancels the executing scan and the queued ones when the user cancels all scans. A media library type without a scanner now fails its own scan instead of leaving it stuck Pending, without stopping the scans queued behind it. Makes the file system discovery job the only top level job of a scan graph, so awaiting it completes the whole scan, and leaves one logical processor free for the rest of the process while discovery and hashing read files in parallel. Removes the per job Task.Run wrappers, links the scan cancellation with the host shutdown token in the scan processor, updates the ADR amendments, API documentation, manual, web client and tests, and normalizes the comments of the touched files.
This commit is contained in:
1 parent
b0c24a1722
commit
8ff5149b6e
85 files changed
+2559
-1394
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user