diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs index b191d607..8d42f473 100644 --- a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs @@ -1,9 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; using System; using System.Collections.Generic; -using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,13 +17,8 @@ public interface IFileHashService /// Hashes by sampling chunks from them. /// /// The collection of files to hash. - /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. /// Callback to invoke during processing of elements. /// Cancellation token that can be used to stop the execution. - /// A collection of files that changed since last library scan, along with their hashes. - Task> HashFilesAsync( - List files, - Dictionary previousScanResults, - Func callback, - CancellationToken cancellationToken); + /// A collection of the hashed files, along with their hashes. + Task> HashFilesAsync(IReadOnlyCollection files, Func callback, CancellationToken cancellationToken); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs new file mode 100644 index 00000000..402da8d1 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a media library item was present in the media library scan snapshot of a previous scan, but it is no longer present on disk. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the library to which the deleted media library item belonged. +/// Model for tracking media library scans. +/// The path of the media library item that was deleted. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}; Path: {Path}")] +public record LibraryMediaItemDeletedDomainEvent( + Guid Id, + LibraryId LibraryId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, + string Path, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs index 9e4d143b..103ce5f8 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs @@ -15,10 +15,12 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// The unique identifier of the library whose scan has failed. /// Model for tracking media library scans. /// The date and time when the domain event occurred. +/// The optional descriptive message of the failure, used for diagnostic purposes. [DebuggerDisplay("Id: {Id}")] public record LibraryScanFailedDomainEvent( Guid Id, LibraryId LibraryId, MediaLibraryScanCompositeId MediaLibraryScanCompositeId, - DateTime OccurredOnUtc + DateTime OccurredOnUtc, + string? ErrorMessage = null ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs new file mode 100644 index 00000000..638c6827 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +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.Hooks; + +/// +/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph. +/// +public interface IScanJobRegistry +{ + /// + /// Gets the media library scan jobs registered for the provided . + /// + /// The name of the hook point at which the media library scan jobs were injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The collection of media library scan jobs registered at the provided hook point. + IEnumerable GetJobsForHook(string hookName, LibraryId libraryId); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs new file mode 100644 index 00000000..7dc27477 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs @@ -0,0 +1,32 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks; + +/// +/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected. +/// +public static class ScanJobHooks +{ + /// + /// The hook that runs after the file system discovery job, and before the scan diff job. + /// + public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery"; + + /// + /// The hook that runs after the scan diff job, and before the scan hash job. + /// + public const string AFTER_SCAN_DIFF = "AfterScanDiff"; + + /// + /// The hook that runs after the scan hash job, and before any metadata enrichment jobs. + /// + public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment"; + + /// + /// The hook that runs after any metadata enrichment jobs, and before the scan results save job. + /// + public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment"; + + /// + /// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph. + /// + public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave"; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs deleted file mode 100644 index a0cc2b9c..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for discovering file system items. -/// -public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs deleted file mode 100644 index 43c11e1b..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for comparing hashes. -/// -public interface IHashComparerJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs new file mode 100644 index 00000000..8586c427 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for computing the differences between the files on disk and the media library scan snapshot of the previous scan. +/// +public interface IMediaLibraryScanDiffJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs new file mode 100644 index 00000000..6cd58978 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for computing the content hashes of the files that changed since the previous scan. +/// +public interface IMediaLibraryScanHashJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs new file mode 100644 index 00000000..0eea3233 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for persisting the results of the current scan. This should always be the last job in the directed acyclic job graph. +/// +public interface IMediaLibraryScanResultsSaveJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs deleted file mode 100644 index e07b0c3c..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans. -/// -public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob -{ - -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs deleted file mode 100644 index f9f8228e..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph. -/// -public interface IRepositoryMetadataSaveJob : IMediaLibraryScanJob -{ - -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs deleted file mode 100644 index 46daf71b..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for filtering only files that have known book formats extensions. -/// -public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..75a3f6f5 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs @@ -0,0 +1,10 @@ +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for discovering books file system items. +/// +public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index d9faa1d5..5c02cdce 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using System.Collections.Generic; @@ -14,57 +15,81 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext internal class BookLibraryTypeScanner : IBookLibraryTypeScanner { private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory; + private readonly IScanJobRegistry _scanJobRegistry; - /// + /// + /// The media library type that this media library scanner supports. + /// public LibraryType SupportedType { get; } = LibraryType.Book; /// /// Initializes a new instance of the class. /// /// Injected factory for creating media library scan jobs. - public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory) + /// Injected registry of the media library scan jobs injected by plugins at the defined hook points. + public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry) { _mediaScanJobFactory = mediaScanJobFactory; + _scanJobRegistry = scanJobRegistry; } - /// - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb) + /// + /// Creates the media library scan jobs for the provided media library. + /// + /// The unique identifier of the media library for which to create the media library scan jobs. + /// Whether the library permits downloading data from the web, or not. + /// A collection of media library scan jobs. + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb) { // declare the list of jobs that this scanner requires - IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); - IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); - IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob(libraryId); - IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(libraryId); + IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId); IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId); - IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(libraryId); - // establish the hierarchical relationships between jobs - fileSystemDiscoveryJob.AddChild(booksFileExtensionsFilterJob); - repositoryMetadataDiscoveryJob.AddChild(hashComparerJob); - - booksFileExtensionsFilterJob.AddChild(hashComparerJob); - booksFileExtensionsFilterJob.AddParent(fileSystemDiscoveryJob); + // establish the hierarchical relationships between jobs, splicing the plugin jobs at the defined hook points + IMediaLibraryScanJob previousJob = fileSystemDiscoveryJob; + previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_FILE_SYSTEM_DISCOVERY, libraryId); + previousJob.AddChild(mediaLibraryScanDiffJob); + mediaLibraryScanDiffJob.AddParent(previousJob); - hashComparerJob.AddParent(booksFileExtensionsFilterJob); - hashComparerJob.AddParent(repositoryMetadataDiscoveryJob); + previousJob = SpliceJobsAtHook(mediaLibraryScanDiffJob, ScanJobHooks.AFTER_SCAN_DIFF, libraryId); + previousJob.AddChild(mediaLibraryScanHashJob); + mediaLibraryScanHashJob.AddParent(previousJob); - if (downloadMedatadaFromWeb) + previousJob = SpliceJobsAtHook(mediaLibraryScanHashJob, ScanJobHooks.BEFORE_METADATA_ENRICHMENT, libraryId); + if (downloadMetadataFromWeb) { - hashComparerJob.AddChild(goodReadsMetadataScrapJob); - goodReadsMetadataScrapJob.AddChild(repositoryMetadataSaveJob); - - goodReadsMetadataScrapJob.AddParent(hashComparerJob); - repositoryMetadataSaveJob.AddParent(goodReadsMetadataScrapJob); - } - else // TODO: perform some action with local files? - { - hashComparerJob.AddChild(repositoryMetadataSaveJob); - - repositoryMetadataSaveJob.AddParent(hashComparerJob); + previousJob.AddChild(goodReadsMetadataScrapJob); + goodReadsMetadataScrapJob.AddParent(previousJob); + previousJob = goodReadsMetadataScrapJob; } + previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_METADATA_ENRICHMENT, libraryId); + previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.BEFORE_SCAN_RESULTS_SAVE, libraryId); + previousJob.AddChild(mediaLibraryScanResultsSaveJob); + mediaLibraryScanResultsSaveJob.AddParent(previousJob); // return the top level jobs that will be triggered when the scan will be started yield return fileSystemDiscoveryJob; - yield return repositoryMetadataDiscoveryJob; + } + + /// + /// Splices the plugin jobs registered at the provided after the , and returns the last job of the extended chain. + /// + /// The job after which the plugin jobs are spliced. + /// The name of the hook point at which the plugin jobs are injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The last job of the extended chain, which can be used as the parent for the next job. + private IMediaLibraryScanJob SpliceJobsAtHook(IMediaLibraryScanJob previousJob, string hookName, LibraryId libraryId) + { + IMediaLibraryScanJob currentJob = previousJob; + foreach (IMediaLibraryScanJob pluginJob in _scanJobRegistry.GetJobsForHook(hookName, libraryId)) + { + currentJob.AddChild(pluginJob); + pluginJob.AddParent(currentJob); + currentJob = pluginJob; + } + return currentJob; } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 3866c9b1..078aa845 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; @@ -17,6 +18,7 @@ using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using Lumina.Infrastructure.Core.Authorization.Policies.Over18; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; @@ -24,6 +26,8 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Time; using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; #endregion @@ -66,13 +70,13 @@ public static class InfrastructureLayerServices services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); + services.AddSingleton(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary>())); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs deleted file mode 100644 index c8fb72a7..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ /dev/null @@ -1,238 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -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.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Infrastructure.Common.Errors; -using Mediator; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; - -/// -/// Media library scan job for discovering file system items. -/// -internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob -{ - private readonly IServiceScopeFactory _serviceScopeFactory; - - /// - /// Initializes a new instance of the class. - /// - /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. - /// - public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - // 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; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine("Started file system discovery scan job..."); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - - TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); - DateTime lastHeartbeat = DateTime.UtcNow; - long processedFiles = 0L; - int processedContentLocations = 0; - - // get the files for each of the media library content locations - List discoveredFiles = []; - foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) - { - cancellationToken.ThrowIfCancellationRequested(); - - foreach (FileInfo file in GetFiles(contentLocation.Path, true, cancellationToken)) - { - discoveredFiles.Add(file); - processedFiles++; - - // increment the number of processed elements progress in a high-frequency counter with low overhead check - if (processedFiles % 1000 == 0) - { - DateTime now = DateTime.UtcNow; - if (now - lastHeartbeat >= heartbeatInterval) - { - publishJobProgressResult = await PublishJobProgress( - publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - lastHeartbeat = now; - } - } - } - processedContentLocations++; - } - // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - sw.Stop(); - Console.WriteLine($"Ended file system discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {discoveredFiles.Count} files."); - - Status = LibraryScanJobStatus.Completed; - - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, discoveredFiles, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } - - /// - /// Gets all files under the specified directory. - /// - /// The path of the root directory from which to start collecting files. - /// Specifies whether hidden files and directories should be included. - /// Cancellation token that can be used to stop the execution. - /// - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details. - /// - /// The discovered collection of files. - [MethodImpl(MethodImplOptions.AggressiveOptimization)] - private static IEnumerable GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken) - { - Queue directoryStack = new(); - directoryStack.Enqueue(new DirectoryInfo(rootDirectoryPath)); - - EnumerationOptions enumerationOptions = new() - { - AttributesToSkip = includeHiddenElements ? FileAttributes.None : FileAttributes.Hidden, - IgnoreInaccessible = true, - RecurseSubdirectories = false - }; - // use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory - // and could result in stack overflow on deeply nested directories - while (directoryStack.Count > 0) - { - cancellationToken.ThrowIfCancellationRequested(); - DirectoryInfo currentDirectory = directoryStack.Dequeue(); - - // process files first - IEnumerable? files = null; - try - { - files = currentDirectory.EnumerateFiles("*", enumerationOptions); - } - catch (IOException ex) - { - Console.WriteLine(ex.Message); - } - - if (files is not null) - { - foreach (FileInfo file in files) - { - cancellationToken.ThrowIfCancellationRequested(); - yield return file; - } - } - - // process subdirectories - each new subdirectory is added to the same stack queue, for later processing - IEnumerable? subdirs = null; - try - { - subdirs = currentDirectory.EnumerateDirectories("*", enumerationOptions); - } - catch (IOException ex) - { - Console.WriteLine(ex.Message); - } - - if (subdirs is not null) - { - foreach (DirectoryInfo subdir in subdirs) - { - cancellationToken.ThrowIfCancellationRequested(); - directoryStack.Enqueue(subdir); - } - } - } - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); - if (scanJobProgressResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return Errors.LibraryScanning.FailedToCreateScanJobProgress; - } - - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs deleted file mode 100644 index 43478ace..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs +++ /dev/null @@ -1,197 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -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.Infrastructure.Models.MediaLibraryScanJobPayloads; -using Lumina.Application.Common.Infrastructure.Security; -using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Infrastructure.Common.Errors; -using Mediator; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; - -/// -/// Media library scan job for comparing hashes. -/// -internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob -{ - private readonly IServiceScopeFactory _serviceScopeFactory; - private Dictionary libraryScanResultEntities = []; - private List files = []; - - /// - /// Initializes a new instance of the class. - /// - /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. - /// - public HashComparerJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - // 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); - - // store the incoming payloads as they arrive from parent jobs - if (input is Dictionary libraryScanResultsPayload) - libraryScanResultEntities = libraryScanResultsPayload; - else if (input is List filesPayload) - files = filesPayload; - - // 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; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine("Started file hashing..."); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - IFileService fileService = asyncServiceScope.ServiceProvider.GetService()!; - IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job; total progress is going twice through the list of files, once to determine what needs to be hashed, second to actually hash - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, files.Count * 2, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - // pre-allocate with worst case scenario, to avoid memory copying and garbage collection - List filesToHash = new(files.Count); - - for (int i = 0; i < files.Count; i++) - { - cancellationToken.ThrowIfCancellationRequested(); - - FileInfo file = files[i]; - // fastest path - file does not exist in past scan, so it's a new file - if (!libraryScanResultEntities.TryGetValue(file.FullName, out LibraryScanResultEntity? previousScanFile)) - filesToHash.Add(file); - else if (file.Length != previousScanFile.FileSize) // next best comparison, check if file size or the last modified date changed - filesToHash.Add(file); // definitely changed - else if (file.LastWriteTimeUtc != previousScanFile.LastModified) // potential change - requires hash verification - filesToHash.Add(file); - - // remove any found items, to speed up subsequent lookups (if needed, all the remaining entries in this dictionary at the end of the scan are deleted filed) - libraryScanResultEntities.Remove(file.FullName); - - // 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 PublishJobProgress(publisher, compositeKey, i, files.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - - // update the last update time - lastUpdateTime = now; - } - } - int processedFilesCount = 0; - List processedFiles = await fileHashService.HashFilesAsync(filesToHash, libraryScanResultEntities, - async () => - { - // 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 PublishJobProgress( - publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), files.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - // update the last update time - lastUpdateTime = now; - } - }, cancellationToken); - - // this job finished, increment the number of processed jobs progress - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - sw.Stop(); - Console.WriteLine($"Ended file hashing in {sw.ElapsedMilliseconds}ms, hashed {processedFiles.Count} files."); - - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, processedFiles, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); - if (scanJobProgressResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return Errors.LibraryScanning.FailedToCreateScanJobProgress; - } - - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs similarity index 57% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 6ccb3243..e788d7b1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -1,21 +1,14 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -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.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -23,25 +16,31 @@ using System.Threading.Tasks; namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; /// -/// Media library scan job for retrieving persistence data from any eventual previous scans. +/// Media library scan job for computing the differences between the files on disk and the media library scan snapshot of the previous scan. /// -internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob +internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibraryScanDiffJob { private readonly IServiceScopeFactory _serviceScopeFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// - public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + public MediaLibraryScanDiffJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) { try @@ -52,62 +51,40 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep 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 + // processing that takes time, and would block the processing of scan jobs in the in-memory queue await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine("Started repo discovering..."); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + // 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()!; IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); - ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository(); + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job, it's a 1 step job - retrieving stuff from repository + // set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) - return; + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // get the results of the last scan of the media library - ErrorOr> getScanResultsResult = - await libraryScanResultRepository.GetPathMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getScanResultsResult.IsError) - return; + // mark the staging results against the media library scan snapshot of the previous scan + ErrorOr markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (markChangesResult.IsError) + throw new InvalidOperationException(markChangesResult.FirstError.Description); // increment the number of processed elements progress publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) - return; + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; - sw.Stop(); - Console.WriteLine($"Ended repository discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {getScanResultsResult.Value.Count} items."); + // call each linked child with the obtained payload foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, getScanResultsResult.Value, cancellationToken).ConfigureAwait(false); + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } } @@ -116,6 +93,11 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep Status = LibraryScanJobStatus.Canceled; throw; } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } } /// @@ -129,12 +111,9 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep /// An representing either a successful operation, or an error. private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData"); + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); if (scanJobProgressResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return Errors.LibraryScanning.FailedToCreateScanJobProgress; - } + return scanJobProgressResult.Errors; await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs new file mode 100644 index 00000000..9eb65c5d --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for computing the content hashes of the files that changed since the previous scan. +/// +internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibraryScanHashJob +{ + private const int HASHING_PAGE_SIZE = 1000; // the number of files that are hashed and written back in a single batch, keeping the peak memory bounded regardless of the library size + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + public MediaLibraryScanHashJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // 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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // count the files that need hashing, for progress reporting purposes + ErrorOr getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getFilesToHashCountResult.IsError) + throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); + int totalFilesToHash = getFilesToHashCountResult.Value; + + // set the initial progress of the scan job + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + 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(); + + ErrorOr> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getFilesToHashPageResult.IsError) + throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); + IReadOnlyList 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 hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, async () => + { + // 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 PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + }, cancellationToken).ConfigureAwait(false); + + // write the computed hashes back to the staging results + ErrorOr updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); + if (updateHashesResult.IsError) + throw new InvalidOperationException(updateHashesResult.FirstError.Description); + + lastPath = filesToHashPage[^1].Path; + } + + // this job finished, increment the number of processed jobs progress + await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents"); + if (scanJobProgressResult.IsError) + return scanJobProgressResult.Errors; + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs similarity index 52% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 36a47324..675d269d 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -1,20 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -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.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Threading; using System.Threading.Tasks; #endregion @@ -22,25 +17,31 @@ using System.Threading.Tasks; namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; /// -/// Media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph. +/// Media library scan job for persisting the results of the current scan. This should always be the last job in the directed acyclic job graph. /// -internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob +internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMediaLibraryScanResultsSaveJob { private readonly IServiceScopeFactory _serviceScopeFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// - public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory) + public MediaLibraryScanResultsSaveJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) { try @@ -51,54 +52,48 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito 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 + // processing that takes time, and would block the processing of scan jobs in the in-memory queue await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine("Started repository saving..."); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + // 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()!; IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + // set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) - return; + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - List ints = [1, 2, 3]; - foreach (int nr in ints) + // 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 + ErrorOr> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getDeletedPathsResult.IsError) + throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); + + // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan + ErrorOr applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); + if (applySnapshotSwapResult.IsError) + throw new InvalidOperationException(applySnapshotSwapResult.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) { - await Task.Delay(500); - // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; + cancellationToken.ThrowIfCancellationRequested(); + await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } + + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - sw.Stop(); - Console.WriteLine($"Ended repository saving scan job in {sw.ElapsedMilliseconds}ms, saved {ints.Count} items."); // this should always be the last job in the directed acyclic job graph, so no linked child to call further }, cancellationToken).ConfigureAwait(false); } @@ -108,6 +103,11 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito Status = LibraryScanJobStatus.Canceled; throw; } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } } /// @@ -123,13 +123,9 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito { ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData"); if (scanJobProgressResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return Errors.LibraryScanning.FailedToCreateScanJobProgress; - } + return scanJobProgressResult.Errors; - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return Result.Success; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs new file mode 100644 index 00000000..2ec45bda --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Helper for publishing the media library scan failure domain event, from within a media library scan job. +/// +internal static class ScanFailurePublisher +{ + /// + /// Publishes the media library scan failure domain event for the scan that the job is part of. + /// + /// Injected factory for creating scopes in which the publisher is resolved. + /// The unique identifier of the library whose scan has failed. + /// Model for tracking media library scans. + /// The exception that caused the failure. + /// Cancellation token that can be used to stop the execution. + public static async Task PublishAsync(IServiceScopeFactory serviceScopeFactory, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, Exception exception, CancellationToken cancellationToken) + { + // failure reporting is best-effort, a failure to report the failure must not crash the job processing + try + { + await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope(); + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false); + } + catch + { + // the failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs new file mode 100644 index 00000000..1f77daf0 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs; + +/// +/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph. +/// +internal sealed class ScanJobRegistry : IScanJobRegistry +{ + private readonly IServiceProvider _serviceProvider; + private readonly IReadOnlyDictionary> _jobsByHook; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider, used to resolve the registered plugin jobs. + /// The media library scan job types registered for each hook point, provided by the composition root of the plugin system. + public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary> jobsByHook) + { + _serviceProvider = serviceProvider; + _jobsByHook = jobsByHook; + } + + /// + /// Gets the media library scan jobs registered for the provided . + /// + /// The name of the hook point at which the media library scan jobs were injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The collection of media library scan jobs registered at the provided hook point. + public IEnumerable GetJobsForHook(string hookName, LibraryId libraryId) + { + // no plugin jobs are registered for this hook point, unless the plugin system provides them + if (!_jobsByHook.TryGetValue(hookName, out IReadOnlyList? jobTypes)) + yield break; + + foreach (Type jobType in jobTypes) + { + IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType); + pluginJob.LibraryId = libraryId; + yield return pluginJob; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs deleted file mode 100644 index ffdd71c4..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs +++ /dev/null @@ -1,195 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -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.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; -using Lumina.Infrastructure.Common.Errors; -using Mediator; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; - -/// -/// Media library scan job for filtering only files that have known book formats extensions. -/// -internal sealed class BooksFileExtensionsFilterJob : MediaLibraryScanJob, IBooksFileExtensionsFilterJob -{ - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly string[] _knownBookFileExtensions = - [ - ".pdf", ".epub", ".mobi", ".azw", ".azw3", - ".cbz", ".cbr", ".djvu", ".fb2", ".lit", - ".prc", ".txt", ".doc", ".docx", ".rtf" - ]; - - /// - /// Initializes a new instance of the class. - /// - /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. - /// - public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) - { - try - { - // 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) - { - if (input is List payload) - { - // 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; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine("Started book file filtering..."); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); - IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job - ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - - List bookFiles = new(payload.Count / 2); // pre-allocate with estimated capacity (boy, that's an optimistic view on books...) - for (int i = 0; i < payload.Count; i++) - { - cancellationToken.ThrowIfCancellationRequested(); - - FileInfo file = payload[i]; - - if (HasKnownBookExtension(file.Name.AsSpan())) - bookFiles.Add(file); - // check if enough time has passed since last update - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) - { - // update job progress report - publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, payload.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - // update the last update time - lastUpdateTime = now; - } - } - - // this job finished, increment the number of processed jobs progress - await publisher.Publish(new LibraryScanProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - sw.Stop(); - Console.WriteLine($"Ended book file filtering in {sw.ElapsedMilliseconds}ms, filtered {bookFiles.Count} files."); - Status = LibraryScanJobStatus.Completed; - - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, bookFiles, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - } - } - } - catch (OperationCanceledException) - { - Status = LibraryScanJobStatus.Canceled; - throw; - } - } - - /// - /// Checks if has a known book file extension or not. - /// - /// The file path to be checked. - /// if contains a known book file extension, otherwise. - public bool HasKnownBookExtension(ReadOnlySpan filePath) - { - // find the last dot in the path - int lastDotIndex = filePath.LastIndexOf('.'); - - // if no dot found or it's the last character, return false - if (lastDotIndex == -1) - return false; - - // get the extension part (including the dot) - ReadOnlySpan extension = filePath[lastDotIndex..]; - - // check against each known extension - foreach (string knownExt in _knownBookFileExtensions) - if (extension.SequenceEqual(knownExt.AsSpan())) - return true; - - return false; - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "FilteringBookFiles"); - if (scanJobProgressResult.IsError) - { - await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return Errors.LibraryScanning.FailedToCreateScanJobProgress; - } - - await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..549d94f9 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -0,0 +1,341 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +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.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Media library scan job for discovering book file system items. +/// +internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksFileSystemDiscoveryJob +{ + private const int STAGING_BATCH_SIZE = 1000; // the number of discovered files that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size + private static readonly HashSet s_bookExtensions = new( + [ + ".pdf", ".epub", ".mobi", ".azw", ".azw3", + ".cbz", ".cbr", ".djvu", ".fb2", ".lit", + ".prc", ".txt", ".doc", ".docx", ".rtf" + ], + StringComparer.OrdinalIgnoreCase + ); + private static readonly EnumerationOptions s_enumerationOptions = new() + { + AttributesToSkip = FileAttributes.None, // hidden files and directories are included in the discovery + IgnoreInaccessible = true, + RecurseSubdirectories = false + }; + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // 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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository(); + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsError ? getLibraryResult.FirstError.Description : "The media library was not found."); + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + 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? fingerprintsByPath = null; + if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) + { + ErrorOr> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getFingerprintsResult.IsError) + throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); + fingerprintsByPath = getFingerprintsResult.Value; + } + + // set the initial progress of the scan job + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedContentLocations = 0; + + List stagingBatch = []; + List fingerprintBatch = []; + + // 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, + fingerprintsByPath, + stagingBatch, + fingerprintBatch, + stagingResultsRepository, + 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 PublishJobProgress( + publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + 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) + { + ErrorOr insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsError) + throw new InvalidOperationException(insertResult.FirstError.Description); + } + if (fingerprintBatch.Count > 0) + { + ErrorOr upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsError) + throw new InvalidOperationException(upsertResult.FirstError.Description); + } + + // this job finished, increment the number of processed jobs progress + await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Discovers the book files of a content location of the media library, using a breadth-first traversal, and writes them in batches to the staging results. + /// + /// The path of the root directory from which to start collecting files. + /// Whether to skip the directories whose last write time has not changed since the last scan, or not. + /// The directory scan fingerprints of the library, mapped by the directory path. Can be when the fast skip is disabled. + /// The batch of discovered files that is written to the staging results when it reaches the batch size. + /// The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size. + /// The repository used to write the discovered files to the staging results. + /// The repository used to write the directory scan fingerprints to the storage medium. + /// Cancellation token that can be used to stop the execution. + /// + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private async Task DiscoverContentLocationAsync( + string rootDirectoryPath, + bool skipUnchangedDirectories, + Dictionary? fingerprintsByPath, + List stagingBatch, + List fingerprintBatch, + ILibraryScanStagingResultsRepository stagingResultsRepository, + IDirectoryScanFingerprintRepository directoryScanFingerprintRepository, + CancellationToken cancellationToken) + { + Queue directoryQueue = new(); + directoryQueue.Enqueue(new DirectoryInfo(rootDirectoryPath)); + + // use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory + // and could result in stack overflow on deeply nested directories + while (directoryQueue.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + DirectoryInfo currentDirectory = directoryQueue.Dequeue(); + + // when the fast skip is enabled, skip the whole subtree of a directory whose last write time has not changed since the last scan + if (skipUnchangedDirectories) + { + DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc; + if (fingerprintsByPath is not null && + fingerprintsByPath.TryGetValue(currentDirectory.FullName, out DirectoryScanFingerprintEntity? fingerprint) && + fingerprint.LastWriteTimeUtc == currentLastWriteTimeUtc) + continue; + + fingerprintBatch.Add(new DirectoryScanFingerprintEntity() + { + Id = Guid.NewGuid(), + LibraryId = LibraryId.Value, + Path = currentDirectory.FullName, + LastWriteTimeUtc = currentLastWriteTimeUtc + }); + // flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has + if (fingerprintBatch.Count >= STAGING_BATCH_SIZE) + { + ErrorOr upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertFingerprintsResult.IsError) + throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description); + fingerprintBatch.Clear(); + } + } + + // process the files of the current directory + IEnumerable? files = null; + try + { + files = currentDirectory.EnumerateFiles("*", s_enumerationOptions) + .Where(file => s_bookExtensions.Contains(file.Extension)); + } + catch (IOException ex) + { + Debug.WriteLine(ex.Message); + } + + if (files is not null) + { + try + { + foreach (FileInfo file in files) + { + cancellationToken.ThrowIfCancellationRequested(); + stagingBatch.Add(new LibraryScanStagingResultsEntity() + { + Id = Guid.NewGuid(), + LibraryScanId = ScanId.Value, + Path = file.FullName, + Size = file.Length, + Ticks = file.LastWriteTimeUtc.Ticks, + ContentHash = 0, + PreviousContentHash = 0, + NeedsRehash = true, + IsNew = true + }); + if (stagingBatch.Count >= STAGING_BATCH_SIZE) + { + ErrorOr insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsError) + throw new InvalidOperationException(insertBatchResult.FirstError.Description); + stagingBatch.Clear(); + } + } + } + catch (IOException ex) + { + // a file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped + Debug.WriteLine(ex.Message); + } + } + + // process the subdirectories - each new subdirectory is added to the same stack queue, for later processing + IEnumerable? subdirectories = null; + try + { + subdirectories = currentDirectory.EnumerateDirectories("*", s_enumerationOptions); + } + catch (IOException ex) + { + Debug.WriteLine(ex.Message); + } + + if (subdirectories is not null) + { + try + { + foreach (DirectoryInfo subdirectory in subdirectories) + { + cancellationToken.ThrowIfCancellationRequested(); + directoryQueue.Enqueue(subdirectory); + } + } + catch (IOException ex) + { + Debug.WriteLine(ex.Message); + } + } + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); + if (scanJobProgressResult.IsError) + return scanJobProgressResult.Errors; + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs index c9999f84..f0e2c15d 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -1,20 +1,18 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -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.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -26,21 +24,28 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Writt /// internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob { + private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of media library items that are enriched in a single batch, keeping the peak memory bounded regardless of the library size private readonly IServiceScopeFactory _serviceScopeFactory; /// /// Initializes a new instance of the class. /// /// - /// Injected factory for creating scopes in which services are requested. - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) { try @@ -50,67 +55,76 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead // 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) { - Status = LibraryScanJobStatus.Running; - Console.WriteLine("started goodreads metadata"); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) + // 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 () => { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } + 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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // set the initial progress of the scan job - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload"); - //ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } + // count the media library items that need their metadata enriched, which are the items that were new or changed in this scan + ErrorOr getItemsToEnrichCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getItemsToEnrichCountResult.IsError) + throw new InvalidOperationException(getItemsToEnrichCountResult.FirstError.Description); + int totalItemsToEnrich = getItemsToEnrichCountResult.Value; - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // set the initial progress of the scan job + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - List ints = Enumerable.Range(0, 20).ToList(); - foreach (int nr in ints) - { - await Task.Delay(100); - // increment the number of processed elements progress - scanJobProgressResult = MediaLibraryScanJobProgress.Create( - nr, 20, "GoodReadsMetadataDownload"); - //scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload"); - if (scanJobProgressResult.IsError) + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedItemsCount = 0; + string? lastPath = null; + + // process the media library items that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size + while (true) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; + cancellationToken.ThrowIfCancellationRequested(); + + ErrorOr> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getItemsToEnrichPageResult.IsError) + throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description); + IReadOnlyList itemsToEnrichPage = getItemsToEnrichPageResult.Value; + if (itemsToEnrichPage.Count == 0) + break; + + // TODO: retrieve the metadata of each media library item from GoodReads, and store it, once the real scraping is implemented + foreach (HashedFileSystemFile item in itemsToEnrichPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + // 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 PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedItemsCount), totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + lastPath = itemsToEnrichPage[^1].Path; } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - } - // this job finished, increment the number of processed jobs progress - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended goodreads metadata"); - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob child in Children) - await child.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + + // this job finished, increment the number of processed jobs progress + await publisher.Publish(new LibraryScanProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -118,5 +132,31 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead Status = LibraryScanJobStatus.Canceled; throw; } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "GoodReadsMetadataDownload"); + if (scanJobProgressResult.IsError) + return scanJobProgressResult.Errors; + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; } } diff --git a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs index e8f9d53f..757e40e1 100644 --- a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; using Lumina.Application.Common.Infrastructure.Security; -using Microsoft.Extensions.ObjectPool; using System; using System.Collections.Generic; using System.Diagnostics; @@ -22,70 +20,62 @@ 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 readonly ThreadLocal _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing - private static readonly ObjectPool s_hasherPool = new DefaultObjectPool(new DefaultPooledObjectPolicy()); // object pool for reusing hashers, to reduce GC pressure + private static readonly ThreadLocal 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(); /// - /// Hashes by sampling chunks from them. + /// Hashes by sampling chunks from them. /// - /// The collection of files to hash. - /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. + /// The collection of files to hash. /// Callback to invoke during processing of elements. /// Cancellation token that can be used to stop the execution. - /// A collection of files that changed since last library scan, along with their hashes. - public async Task> HashFilesAsync( - List files, - Dictionary previousScanResults, - Func callback, - CancellationToken cancellationToken) + /// A collection of the hashed files, along with their hashes. + public async Task> HashFilesAsync(IReadOnlyCollection inputFiles, Func callback, CancellationToken cancellationToken) { - List changedFiles = []; + List outputFiles = []; object listLock = new(); - int totalFiles = files.Count; // make use of all available processors ParallelOptions parallelOptions = new() { CancellationToken = cancellationToken, - MaxDegreeOfParallelism = Environment.ProcessorCount + MaxDegreeOfParallelism = Environment.ProcessorCount // TODO: make this configurable, such that parallelism can be turned off for mechanical hard drives }; - await Parallel.ForEachAsync(files, parallelOptions, async (file, cancellationToken) => + await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) => { cancellationToken.ThrowIfCancellationRequested(); try { // invoke the method that triggers progress reporting await callback().ConfigureAwait(false); - // if file has no contents, it needs no hashing - if (file.Length == 0) - return; - // buffer management with thread-local reuse - byte[] buffer = _threadLocalBuffer.Value ?? new byte[DEFAULT_BUFFER_SIZE]; - ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Length); + + ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Size); // get the file hash and check if it differs from the one stored on previous scan - ulong currentHash = ComputeFileHash(file.FullName, file.Length, bufferSize, buffer); - bool isChanged = !previousScanResults.TryGetValue(file.FullName, out LibraryScanResultEntity? previous) || previous.ContentHash != currentHash; + ulong currentHash = file.Size == 0 + ? s_emptyFileHash // precomputed constant: XxHash64 hash of zero-length input + : ComputeFileHash(file.Path, file.Size, bufferSize); - if (isChanged) // hash changed, file needs to be re-scanned - lock (listLock) - changedFiles.Add(new ChangedFileSystemFile(file, currentHash)); + // the decision of whether a file changed is already made before hashing, so all files that reach this point get their hash stored + lock (listLock) + outputFiles.Add(file with { CurrentHash = currentHash }); } catch (Exception ex) { - Debug.WriteLine($"Error processing {file.FullName}: {ex.Message}"); + Debug.WriteLine($"Error processing {file.Path}: {ex.Message}"); } }); - return changedFiles; + return outputFiles; } /// /// Computes content hash using memory-mapped sampling. /// + /// The path of the file to hash. + /// The size of the file, in bytes. /// Sample window size (automatically clamped to file size). - /// Reusable read buffer (thread-local allocation optimized). - private unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize, byte[] buffer) + private static unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize) { // create a memory-mapped file for efficient access to large files using MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); @@ -98,8 +88,11 @@ internal class FileHashService : IFileHashService { // get a direct pointer to the memory-mapped file, for faster access memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer); - // get a hasher from the pool to avoid allocations - XxHash64 hasher = s_hasherPool.Get(); + + // get the thread-local hasher and reset it before use; resetting at entry (rather than at exit) ensures + // the hasher is always in a clean state even if a previous call on this thread threw mid-computation + XxHash64 hasher = s_threadLocalHasher.Value!; + hasher.Reset(); // allocate hash result buffer on the stack, to avoid heap allocation Span hashSpan = stackalloc byte[sizeof(ulong)]; @@ -122,7 +115,7 @@ internal class FileHashService : IFileHashService return BitConverter.ToUInt64(hashSpan); } finally - { + { if (memoryPointer is not null) // always release the pointer, to prevent memory leaks memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer(); } @@ -145,7 +138,7 @@ internal class FileHashService : IFileHashService // for larger files, sample at strategic points: yield return 0; // beginning of the file yield return fileSize / 4; // quarter of the file - yield return fileSize / 2; // file of the file + yield return fileSize / 2; // half of the file yield return 3 * fileSize / 4; // three quarters of the file yield return Math.Max(0, fileSize - bufferSize); // end of the file (ensure we don't go past the end) @@ -154,4 +147,16 @@ internal class FileHashService : IFileHashService for (int i = 1; i <= SAMPLE_COUNT - 4; i++) yield return interval * i; } + + /// + /// Computes the hash for an empty file, which is a special case, since it has no content to sample. + /// + /// The hash value for an empty file. + private static ulong ComputeEmptyHash() + { + XxHash64 hasher = new(); + Span hashSpan = stackalloc byte[sizeof(ulong)]; + hasher.TryGetCurrentHash(hashSpan, out _); + return BitConverter.ToUInt64(hashSpan); + } } diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index ce6e8e39..167b3211 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -186,12 +186,12 @@ Filmreihe - - Buchdateien werden gefiltert... - Metadaten werden von GoodReads heruntergeladen... + + Berechne die Datei-Hashes... + Grafischer Roman @@ -252,9 +252,6 @@ Entfernen - - Vergangene Scan-Daten werden abgerufen... - Scandaten werden gespeichert... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 3903ded1..a04e2a83 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -186,12 +186,12 @@ Film Series - - Filtering book files... - Downloading metadata from GoodReads... + + Hashing file contents... + Graphic Novel @@ -252,9 +252,6 @@ Remove - - Retrieving past scan data... - Saving scan data... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 634313d9..ca26806a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -186,12 +186,12 @@ Saga Cinematográfica - - Filtrando archivos de libros... - Descargando metadatos de GoodReads... + + Calculando los hashes de los archivos... + Novela Gráfica @@ -252,9 +252,6 @@ Eliminar - - Recuperando datos de escaneos anteriores... - Guardando datos del escaneo... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 9c14201c..217d4007 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -186,12 +186,12 @@ Saga Cinématographique - - Filtrage des fichiers de livres... - Téléchargement des métadonnées depuis GoodReads... + + Calcul des hachages des fichiers... + Roman Graphique @@ -252,9 +252,6 @@ Supprimer - - Récupération des données de scan précédentes... - Sauvegarde des données de scan en cours... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index 9958003b..f44f35d0 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -186,12 +186,12 @@ Saga Cinematografica - - Filtraggio dei file di libri... - Scaricamento dei metadati da GoodReads... + + Calcolo degli hash dei file... + Romanzo Grafico @@ -252,9 +252,6 @@ Rimuovere - - Recupero dei dati di scansione precedenti... - Salvataggio dei dati di scansione... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index 966d7ae2..525c1e48 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -186,12 +186,12 @@ 映画シリーズ - - 書籍ファイルをフィルタリング中... - GoodReadsからメタデータをダウンロード中... + + ファイルのハッシュを計算中... + グラフィックノベル @@ -252,9 +252,6 @@ 削除 - - 過去のスキャンデータを取得中... - スキャンデータを保存中... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 3903ded1..a04e2a83 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -186,12 +186,12 @@ Film Series - - Filtering book files... - Downloading metadata from GoodReads... + + Hashing file contents... + Graphic Novel @@ -252,9 +252,6 @@ Remove - - Retrieving past scan data... - Saving scan data... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index e22f1e82..17941f34 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -186,12 +186,12 @@ Serie de Filme - - Se filtrează fișierele de tip carte... - Se descarcă metadate de pe GoodReads... + + Se calculează hash-urile fișierelor... + Roman Grafic @@ -252,9 +252,6 @@ Șterge - - Se preiau datele de scanare anterioare... - Se salvează datele de scanare... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index 8e6340a9..c6fde0d8 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -186,12 +186,12 @@ Киносерия - - Фильтрация файлов книг... - Загрузка метаданных из GoodReads... + + Вычисление хешей файлов... + Графический Роман @@ -252,9 +252,6 @@ Удалить - - Получение данных прошлых сканирований... - Сохранение данных сканирования... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 4f22d893..b19516a5 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -186,12 +186,12 @@ 电影系列 - - 正在过滤书籍文件... - 正在从GoodReads下载元数据... + + 正在计算文件哈希... + 图像小说 @@ -252,9 +252,6 @@ 删除 - - 正在检索过去的扫描数据... - 正在保存扫描数据... diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index 9eba8668..4247df20 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -169,11 +169,10 @@ }; const jsLocalizedLibraryScanJobsStatuses = { DiscoveringFiles: '@_localizer["DiscoveringFiles"]', - RetrievingPastScanData: '@_localizer["RetrievingPastScanData"]', ComparingFileHashes: '@_localizer["ComparingFileHashes"]', + HashingFileContents: '@_localizer["HashingFileContents"]', GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]', - SavingScanData: '@_localizer["SavingScanData"]', - FilteringBookFiles: '@_localizer["FilteringBookFiles"]' + SavingScanData: '@_localizer["SavingScanData"]' }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]',