mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 09:01:10 +00:00
Replaces the in-memory media library scan diff with a database-centric job pipeline
This commit is contained in:
1 parent
1dc3da3da1
commit
9905aa08f9
38 files changed
+1032
-987
No files matched your search
@@ -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 <paramref name="files"/> by sampling chunks from them.
|
||||
/// </summary>
|
||||
/// <param name="files">The collection of files to hash.</param>
|
||||
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
|
||||
/// <param name="callback">Callback to invoke during processing of elements.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
|
||||
Task<List<ChangedFileSystemFile>> HashFilesAsync(
|
||||
List<FileInfo> files,
|
||||
Dictionary<string, LibraryScanResultEntity> previousScanResults,
|
||||
Func<Task> callback,
|
||||
CancellationToken cancellationToken);
|
||||
/// <returns>A collection of the hashed files, along with their hashes.</returns>
|
||||
Task<List<HashedFileSystemFile>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFile> files, Func<Task> callback, CancellationToken cancellationToken);
|
||||
}
|
||||
+26
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="LibraryId">The unique identifier of the library to which the deleted media library item belonged.</param>
|
||||
/// <param name="MediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <param name="Path">The path of the media library item that was deleted.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Path: {Path}")]
|
||||
public record LibraryMediaItemDeletedDomainEvent(
|
||||
Guid Id,
|
||||
LibraryId LibraryId,
|
||||
MediaLibraryScanCompositeId MediaLibraryScanCompositeId,
|
||||
string Path,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+3
-1
@@ -15,10 +15,12 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// <param name="LibraryId">The unique identifier of the library whose scan has failed.</param>
|
||||
/// <param name="MediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
/// <param name="ErrorMessage">The optional descriptive message of the failure, used for diagnostic purposes.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record LibraryScanFailedDomainEvent(
|
||||
Guid Id,
|
||||
LibraryId LibraryId,
|
||||
MediaLibraryScanCompositeId MediaLibraryScanCompositeId,
|
||||
DateTime OccurredOnUtc
|
||||
DateTime OccurredOnUtc,
|
||||
string? ErrorMessage = null
|
||||
) : IDomainEvent;
|
||||
+21
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
|
||||
/// </summary>
|
||||
public interface IScanJobRegistry
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the media library scan jobs registered for the provided <paramref name="hookName"/>.
|
||||
/// </summary>
|
||||
/// <param name="hookName">The name of the hook point at which the media library scan jobs were injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The collection of media library scan jobs registered at the provided hook point.</returns>
|
||||
IEnumerable<IMediaLibraryScanJob> GetJobsForHook(string hookName, LibraryId libraryId);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected.
|
||||
/// </summary>
|
||||
public static class ScanJobHooks
|
||||
{
|
||||
/// <summary>
|
||||
/// The hook that runs after the file system discovery job, and before the scan diff job.
|
||||
/// </summary>
|
||||
public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after the scan diff job, and before the scan hash job.
|
||||
/// </summary>
|
||||
public const string AFTER_SCAN_DIFF = "AfterScanDiff";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after the scan hash job, and before any metadata enrichment jobs.
|
||||
/// </summary>
|
||||
public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after any metadata enrichment jobs, and before the scan results save job.
|
||||
/// </summary>
|
||||
public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave";
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
public interface IHashComparerJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanDiffJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for computing the content hashes of the files that changed since the previous scan.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanHashJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanResultsSaveJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans.
|
||||
/// </summary>
|
||||
public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IRepositoryMetadataSaveJob : IMediaLibraryScanJob
|
||||
{
|
||||
|
||||
}
|
||||
-13
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for filtering only files that have known book formats extensions.
|
||||
/// </summary>
|
||||
public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering books file system items.
|
||||
/// </summary>
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+55
-30
@@ -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;
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// The media library type that this media library scanner supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedType { get; } = LibraryType.Book;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookLibraryTypeScanner"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
|
||||
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
|
||||
/// <param name="scanJobRegistry">Injected registry of the media library scan jobs injected by plugins at the defined hook points.</param>
|
||||
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry)
|
||||
{
|
||||
_mediaScanJobFactory = mediaScanJobFactory;
|
||||
_scanJobRegistry = scanJobRegistry;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb)
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the library permits downloading data from the web, or not.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb)
|
||||
{
|
||||
// declare the list of jobs that this scanner requires
|
||||
IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IFileSystemDiscoveryJob>(libraryId);
|
||||
IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataDiscoveryJob>(libraryId);
|
||||
IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob<IBooksFileExtensionsFilterJob>(libraryId);
|
||||
IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob<IHashComparerJob>(libraryId);
|
||||
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<IGoodReadsMetadataScrapJob>(libraryId);
|
||||
IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataSaveJob>(libraryId);
|
||||
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splices the plugin jobs registered at the provided <paramref name="hookName"/> after the <paramref name="previousJob"/>, and returns the last job of the extended chain.
|
||||
/// </summary>
|
||||
/// <param name="previousJob">The job after which the plugin jobs are spliced.</param>
|
||||
/// <param name="hookName">The name of the hook point at which the plugin jobs are injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The last job of the extended chain, which can be used as the parent for the next job.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
||||
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
||||
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
|
||||
services.AddSingleton<IScanJobRegistry>(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary<string, IReadOnlyList<Type>>()));
|
||||
|
||||
services.AddTransient<IFileSystemDiscoveryJob, FileSystemDiscoveryJob>();
|
||||
services.AddTransient<IRepositoryMetadataDiscoveryJob, RepositoryMetadataDiscoveryJob>();
|
||||
services.AddTransient<IBooksFileExtensionsFilterJob, BooksFileExtensionsFilterJob>();
|
||||
services.AddTransient<IHashComparerJob, HashComparerJob>();
|
||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
|
||||
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
|
||||
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
|
||||
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
|
||||
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
|
||||
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
-238
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<Success> 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<FileInfo> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all files under the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details.
|
||||
/// </remarks>
|
||||
/// <returns>The discovered collection of files.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static IEnumerable<FileInfo> GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> 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<FileInfo>? 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<DirectoryInfo>? 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
-197
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private Dictionary<string, LibraryScanResultEntity> libraryScanResultEntities = [];
|
||||
private List<FileInfo> files = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HashComparerJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public HashComparerJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(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<string, LibraryScanResultEntity> libraryScanResultsPayload)
|
||||
libraryScanResultEntities = libraryScanResultsPayload;
|
||||
else if (input is List<FileInfo> 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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
IFileService fileService = asyncServiceScope.ServiceProvider.GetService<IFileService>()!;
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<Success> 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<FileInfo> 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<ChangedFileSystemFile> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
+33
-54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
|
||||
internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibraryScanDiffJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataDiscoveryJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanDiffJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanDiffJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository<ILibraryScanResultRepository>();
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<Success> 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<Dictionary<string, LibraryScanResultEntity>> 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,12 +111,9 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData");
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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);
|
||||
+164
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for computing the content hashes of the files that changed since the previous scan.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public MediaLibraryScanHashJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// count the files that need hashing, for progress reporting purposes
|
||||
ErrorOr<int> 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<Success> 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<IReadOnlyList<HashedFileSystemFile>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsError)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> 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<HashedFileSystemFile> 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
+47
-51
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob
|
||||
internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMediaLibraryScanResultsSaveJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataSaveJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanResultsSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<Success> 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<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> 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<IReadOnlyList<string>> 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,13 +123,9 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for publishing the media library scan failure domain event, from within a media library scan job.
|
||||
/// </summary>
|
||||
internal static class ScanFailurePublisher
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes the media library scan failure domain event for the scan that the job is part of.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which the publisher is resolved.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan has failed.</param>
|
||||
/// <param name="compositeKey">Model for tracking media library scans.</param>
|
||||
/// <param name="exception">The exception that caused the failure.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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<IPublisher>()!;
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
|
||||
/// </summary>
|
||||
internal sealed class ScanJobRegistry : IScanJobRegistry
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly IReadOnlyDictionary<string, IReadOnlyList<Type>> _jobsByHook;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanJobRegistry"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider, used to resolve the registered plugin jobs.</param>
|
||||
/// <param name="jobsByHook">The media library scan job types registered for each hook point, provided by the composition root of the plugin system.</param>
|
||||
public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary<string, IReadOnlyList<Type>> jobsByHook)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_jobsByHook = jobsByHook;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scan jobs registered for the provided <paramref name="hookName"/>.
|
||||
/// </summary>
|
||||
/// <param name="hookName">The name of the hook point at which the media library scan jobs were injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The collection of media library scan jobs registered at the provided hook point.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> 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<Type>? jobTypes))
|
||||
yield break;
|
||||
|
||||
foreach (Type jobType in jobTypes)
|
||||
{
|
||||
IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType);
|
||||
pluginJob.LibraryId = libraryId;
|
||||
yield return pluginJob;
|
||||
}
|
||||
}
|
||||
}
|
||||
-195
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for filtering only files that have known book formats extensions.
|
||||
/// </summary>
|
||||
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"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileExtensionsFilterJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(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<FileInfo> 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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
|
||||
List<FileInfo> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="filePath"/> has a known book file extension or not.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The file path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="filePath"/> contains a known book file extension, <see langword="false"/> otherwise.</returns>
|
||||
public bool HasKnownBookExtension(ReadOnlySpan<char> 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<char> extension = filePath[lastDotIndex..];
|
||||
|
||||
// check against each known extension
|
||||
foreach (string knownExt in _knownBookFileExtensions)
|
||||
if (extension.SequenceEqual(knownExt.AsSpan()))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
+341
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering book file system items.
|
||||
/// </summary>
|
||||
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<string> 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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<Library> 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<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
{
|
||||
ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Success> 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<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> 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<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsError)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
ErrorOr<Updated> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="skipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
|
||||
/// <param name="fingerprintsByPath">The directory scan fingerprints of the library, mapped by the directory path. Can be <see langword="null"/> when the fast skip is disabled.</param>
|
||||
/// <param name="stagingBatch">The batch of discovered files that is written to the staging results when it reaches the batch size.</param>
|
||||
/// <param name="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
|
||||
/// <param name="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
|
||||
/// <param name="directoryScanFingerprintRepository">The repository used to write the directory scan fingerprints to the storage medium.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private async Task DiscoverContentLocationAsync(
|
||||
string rootDirectoryPath,
|
||||
bool skipUnchangedDirectories,
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch,
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch,
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository,
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> 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<Updated> 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<FileInfo>? 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<Created> 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<DirectoryInfo>? 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
+101
-61
@@ -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
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GoodReadsMetadataScrapJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>();
|
||||
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> 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<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> 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<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload");
|
||||
//ErrorOr<MediaLibraryScanJobProgress> 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<int> 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<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> 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<IReadOnlyList<HashedFileSystemFile>> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getItemsToEnrichPageResult.IsError)
|
||||
throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<byte[]> _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing
|
||||
private static readonly ObjectPool<XxHash64> s_hasherPool = new DefaultObjectPool<XxHash64>(new DefaultPooledObjectPolicy<XxHash64>()); // object pool for reusing hashers, to reduce GC pressure
|
||||
private static readonly ThreadLocal<XxHash64> s_threadLocalHasher = new(() => new XxHash64()); // thread-local hasher to avoid contention and pool management overhead during parallel processing
|
||||
private static readonly ulong s_emptyFileHash = ComputeEmptyHash();
|
||||
|
||||
/// <summary>
|
||||
/// Hashes <paramref name="files"/> by sampling chunks from them.
|
||||
/// Hashes <paramref name="inputFiles"/> by sampling chunks from them.
|
||||
/// </summary>
|
||||
/// <param name="files">The collection of files to hash.</param>
|
||||
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
|
||||
/// <param name="inputFiles">The collection of files to hash.</param>
|
||||
/// <param name="callback">Callback to invoke during processing of elements.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
|
||||
public async Task<List<ChangedFileSystemFile>> HashFilesAsync(
|
||||
List<FileInfo> files,
|
||||
Dictionary<string, LibraryScanResultEntity> previousScanResults,
|
||||
Func<Task> callback,
|
||||
CancellationToken cancellationToken)
|
||||
/// <returns>A collection of the hashed files, along with their hashes.</returns>
|
||||
public async Task<List<HashedFileSystemFile>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFile> inputFiles, Func<Task> callback, CancellationToken cancellationToken)
|
||||
{
|
||||
List<ChangedFileSystemFile> changedFiles = [];
|
||||
List<HashedFileSystemFile> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes content hash using memory-mapped sampling.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path of the file to hash.</param>
|
||||
/// <param name="fileSize">The size of the file, in bytes.</param>
|
||||
/// <param name="bufferSize">Sample window size (automatically clamped to file size).</param>
|
||||
/// <param name="buffer">Reusable read buffer (thread-local allocation optimized).</param>
|
||||
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<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the hash for an empty file, which is a special case, since it has no content to sample.
|
||||
/// </summary>
|
||||
/// <returns>The hash value for an empty file.</returns>
|
||||
private static ulong ComputeEmptyHash()
|
||||
{
|
||||
XxHash64 hasher = new();
|
||||
Span<byte> hashSpan = stackalloc byte[sizeof(ulong)];
|
||||
hasher.TryGetCurrentHash(hashSpan, out _);
|
||||
return BitConverter.ToUInt64(hashSpan);
|
||||
}
|
||||
}
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Filmreihe</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Buchdateien werden gefiltert...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Metadaten werden von GoodReads heruntergeladen...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Berechne die Datei-Hashes...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Grafischer Roman</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Entfernen</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Vergangene Scan-Daten werden abgerufen...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Scandaten werden gespeichert...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Film Series</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtering book files...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Downloading metadata from GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Hashing file contents...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Graphic Novel</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Remove</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Retrieving past scan data...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Saving scan data...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinematográfica</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtrando archivos de libros...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Descargando metadatos de GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calculando los hashes de los archivos...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Novela Gráfica</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Eliminar</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Recuperando datos de escaneos anteriores...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Guardando datos del escaneo...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinématographique</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtrage des fichiers de livres...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Téléchargement des métadonnées depuis GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calcul des hachages des fichiers...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Roman Graphique</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Supprimer</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Récupération des données de scan précédentes...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Sauvegarde des données de scan en cours...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinematografica</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtraggio dei file di libri...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Scaricamento dei metadati da GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calcolo degli hash dei file...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Romanzo Grafico</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Rimuovere</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Recupero dei dati di scansione precedenti...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Salvataggio dei dati di scansione...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>映画シリーズ</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>書籍ファイルをフィルタリング中...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>GoodReadsからメタデータをダウンロード中...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>ファイルのハッシュを計算中...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>グラフィックノベル</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>削除</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>過去のスキャンデータを取得中...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>スキャンデータを保存中...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Film Series</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtering book files...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Downloading metadata from GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Hashing file contents...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Graphic Novel</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Remove</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Retrieving past scan data...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Saving scan data...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Serie de Filme</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Se filtrează fișierele de tip carte...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Se descarcă metadate de pe GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Se calculează hash-urile fișierelor...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Roman Grafic</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Șterge</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Se preiau datele de scanare anterioare...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Se salvează datele de scanare...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Киносерия</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Фильтрация файлов книг...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Загрузка метаданных из GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Вычисление хешей файлов...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Графический Роман</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Удалить</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Получение данных прошлых сканирований...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Сохранение данных сканирования...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>电影系列</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>正在过滤书籍文件...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>正在从GoodReads下载元数据...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>正在计算文件哈希...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>图像小说</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>正在检索过去的扫描数据...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>正在保存扫描数据...</value>
|
||||
</data>
|
||||
|
||||
@@ -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"]',
|
||||
|
||||
Reference in new issue
Block a user