Parallelizes discovery and hashing reads for SSD libraries

Uses parallel file system reads when the library content is on a solid state drive, and keeps sequential reads for mechanical drives. Discovery keeps bounded batching and sequential repository writes.
This commit is contained in:
BinaryAlley committed 2026-10-30 22:40:09 +02:00
1 parent 499647f7bb
commit 811addf8d4
5 files changed
+327 -133

No files matched your search

@@ -17,10 +17,11 @@ public interface IFileHashService
/// Hashes <paramref name="files"/> by sampling chunks from them. /// Hashes <paramref name="files"/> by sampling chunks from them.
/// </summary> /// </summary>
/// <param name="files">The collection of files to hash.</param> /// <param name="files">The collection of files to hash.</param>
/// <param name="shouldParallelizeReads">Whether the files should be read in parallel. Parallel reads benefit solid state drives, while mechanical hard drives are faster with sequential reads.</param>
/// <param name="callback">Callback to invoke during processing of elements.</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> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of the hashed files, along with their hashes.</returns> /// <returns>A collection of the hashed files, along with their hashes.</returns>
Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> files, Func<Task> callback, CancellationToken cancellationToken); Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> files, bool shouldParallelizeReads, Func<Task> callback, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Computes the content hash of the file stored at <paramref name="filePath"/>, by sampling chunks from it. /// Computes the content hash of the file stored at <paramref name="filePath"/>, by sampling chunks from it.
@@ -15,11 +15,13 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -41,6 +43,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
StringComparer.OrdinalIgnoreCase StringComparer.OrdinalIgnoreCase
); );
private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MusicFileSystemDiscoveryJob> _logger;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="MusicFileSystemDiscoveryJob"/> class. /// Initializes a new instance of the <see cref="MusicFileSystemDiscoveryJob"/> class.
@@ -49,9 +52,11 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
/// Injected factory for creating scopes in which services are requested. /// 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. /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </param> /// </param>
public MusicFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) /// <param name="logger">Injected logger for the media library scan job.</param>
public MusicFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory, ILogger<MusicFileSystemDiscoveryJob> logger)
{ {
_serviceScopeFactory = serviceScopeFactory; _serviceScopeFactory = serviceScopeFactory;
_logger = logger;
} }
/// <summary> /// <summary>
@@ -116,6 +121,11 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
List<LibraryScanStagingResultsEntity> stagingBatch = []; List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<DirectoryScanFingerprintEntity> fingerprintBatch = []; List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads)
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations. // Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{ {
@@ -126,6 +136,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
fileProviderService, fileProviderService,
directoryProviderService, directoryProviderService,
fingerprintsByPath is not null, fingerprintsByPath is not null,
shouldParallelizeReads,
fingerprintsByPath, fingerprintsByPath,
stagingBatch, stagingBatch,
fingerprintBatch, fingerprintBatch,
@@ -189,6 +200,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
/// <param name="fileProviderService">The service used to enumerate the files of a directory.</param> /// <param name="fileProviderService">The service used to enumerate the files of a directory.</param>
/// <param name="directoryProviderService">The service used to enumerate the subdirectories of a directory.</param> /// <param name="directoryProviderService">The service used to enumerate the subdirectories of a directory.</param>
/// <param name="shouldSkipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param> /// <param name="shouldSkipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
/// <param name="shouldParallelizeReads">Whether the file system reads should run in parallel, which benefits solid state drives.</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="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="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="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
@@ -204,6 +216,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
IFileProviderService fileProviderService, IFileProviderService fileProviderService,
IDirectoryProviderService directoryProviderService, IDirectoryProviderService directoryProviderService,
bool shouldSkipUnchangedDirectories, bool shouldSkipUnchangedDirectories,
bool shouldParallelizeReads,
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath, Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
List<LibraryScanStagingResultsEntity> stagingBatch, List<LibraryScanStagingResultsEntity> stagingBatch,
List<DirectoryScanFingerprintEntity> fingerprintBatch, List<DirectoryScanFingerprintEntity> fingerprintBatch,
@@ -258,40 +271,24 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
Result<IEnumerable<FileSystemPathId>> getFilesResult = fileProviderService.GetFilePaths(currentDirectory, true); Result<IEnumerable<FileSystemPathId>> getFilesResult = fileProviderService.GetFilePaths(currentDirectory, true);
if (getFilesResult.IsSuccess) if (getFilesResult.IsSuccess)
{ {
foreach (FileSystemPathId filePath in getFilesResult.Value) if (shouldParallelizeReads)
await StageFilesInParallelAsync(getFilesResult.Value, fileProviderService, stagingBatch, stagingResultsRepository, cancellationToken).ConfigureAwait(false);
else
{ {
cancellationToken.ThrowIfCancellationRequested(); foreach (FileSystemPathId filePath in getFilesResult.Value)
if (!s_audioExtensions.Contains(Path.GetExtension(filePath.Path)))
continue;
long size = 0;
Result<long?> getSizeResult = fileProviderService.GetSize(filePath);
if (getSizeResult.IsSuccess && getSizeResult.Value.HasValue)
size = getSizeResult.Value.Value;
long ticks = 0;
Result<Optional<DateTime>> getFileLastWriteTimeResult = fileProviderService.GetLastWriteTime(filePath);
if (getFileLastWriteTimeResult.IsSuccess && getFileLastWriteTimeResult.Value.HasValue)
ticks = getFileLastWriteTimeResult.Value.Value.Ticks;
stagingBatch.Add(new LibraryScanStagingResultsEntity()
{ {
Id = Guid.NewGuid(), cancellationToken.ThrowIfCancellationRequested();
LibraryScanId = ScanId.Value, if (!s_audioExtensions.Contains(Path.GetExtension(filePath.Path)))
Path = filePath.Path, continue;
Size = size,
Ticks = ticks, stagingBatch.Add(CreateStagingResult(filePath, fileProviderService));
ContentHash = 0, if (stagingBatch.Count >= STAGING_BATCH_SIZE)
PreviousContentHash = 0, {
NeedsRehash = true, Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
IsNew = true if (insertBatchResult.IsFailure)
}); throw new InvalidOperationException(insertBatchResult.FirstError.Description);
if (stagingBatch.Count >= STAGING_BATCH_SIZE) stagingBatch.Clear();
{ }
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
} }
} }
} }
@@ -309,6 +306,102 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
} }
} }
/// <summary>
/// Reads the metadata of <paramref name="filePaths"/> in parallel and writes the discovered music files in batches to the staging results.
/// </summary>
/// <param name="filePaths">The file paths of the current directory.</param>
/// <param name="fileProviderService">The service used to read the metadata of a file.</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="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task StageFilesInParallelAsync(
IEnumerable<FileSystemPathId> filePaths,
IFileProviderService fileProviderService,
List<LibraryScanStagingResultsEntity> stagingBatch,
ILibraryScanStagingResultsRepository stagingResultsRepository,
CancellationToken cancellationToken)
{
List<FileSystemPathId> filesToProcess = [.. filePaths.Where(filePath => s_audioExtensions.Contains(Path.GetExtension(filePath.Path)))];
LibraryScanStagingResultsEntity?[] discoveredFiles = new LibraryScanStagingResultsEntity?[filesToProcess.Count];
ParallelOptions parallelOptions = new()
{
CancellationToken = cancellationToken,
MaxDegreeOfParallelism = Environment.ProcessorCount
};
try
{
Parallel.For(0, filesToProcess.Count, parallelOptions, index =>
{
try
{
discoveredFiles[index] = CreateStagingResult(filesToProcess[index], fileProviderService);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file might become inaccessible between enumeration and processing, so it is skipped.
_logger.LogWarning(ex, "Failed to read the metadata of the music file '{Path}', so it is skipped for this scan.", filesToProcess[index].Path);
}
});
}
catch (AggregateException aggregateException)
{
// Parallel.For wraps the exceptions thrown by its body, so the real cause is rethrown here, to keep the reported scan failure meaningful.
AggregateException flattenedException = aggregateException.Flatten();
if (flattenedException.InnerExceptions.Count == 1)
ExceptionDispatchInfo.Capture(flattenedException.InnerExceptions[0]).Throw();
throw new AggregateException(string.Join("; ", flattenedException.InnerExceptions.Select(exception => exception.Message)), flattenedException.InnerExceptions);
}
// The repository is not thread-safe, so the discovered files are written sequentially, in bounded batches.
foreach (LibraryScanStagingResultsEntity? discoveredFile in discoveredFiles)
{
cancellationToken.ThrowIfCancellationRequested();
if (discoveredFile is null)
continue;
stagingBatch.Add(discoveredFile);
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
{
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
}
}
}
/// <summary>
/// Creates a staging result entity from a discovered music file.
/// </summary>
/// <param name="filePath">The discovered music file.</param>
/// <param name="fileProviderService">The service used to read the metadata of a file.</param>
/// <returns>The staging result entity of the file.</returns>
private LibraryScanStagingResultsEntity CreateStagingResult(FileSystemPathId filePath, IFileProviderService fileProviderService)
{
long size = 0;
Result<long?> getSizeResult = fileProviderService.GetSize(filePath);
if (getSizeResult.IsSuccess && getSizeResult.Value.HasValue)
size = getSizeResult.Value.Value;
long ticks = 0;
Result<Optional<DateTime>> getFileLastWriteTimeResult = fileProviderService.GetLastWriteTime(filePath);
if (getFileLastWriteTimeResult.IsSuccess && getFileLastWriteTimeResult.Value.HasValue)
ticks = getFileLastWriteTimeResult.Value.Value.Ticks;
return new LibraryScanStagingResultsEntity()
{
Id = Guid.NewGuid(),
LibraryScanId = ScanId.Value,
Path = filePath.Path,
Size = size,
Ticks = ticks,
ContentHash = 0,
PreviousContentHash = 0,
NeedsRehash = true,
IsNew = true
};
}
/// <summary> /// <summary>
/// Publishes a job progress update. /// Publishes a job progress update.
/// </summary> /// </summary>
@@ -1,19 +1,19 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives; 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.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
#endregion #endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
@@ -23,7 +23,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// </summary> /// </summary>
internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibraryScanHashJob 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 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; private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary> /// <summary>
@@ -49,9 +49,9 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
{ {
try try
{ {
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) // 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); int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// only execute this job's payload when it has no parents, or when all the parents finished their execution // Only execute this job's payload when it has no parents, or when all the parents finished their execution.
if (Parents.Count == 0 || parentsCompleted == Parents.Count) 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 // 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
@@ -59,7 +59,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
await Task.Run(async () => await Task.Run(async () =>
{ {
Status = LibraryScanJobStatus.Running; Status = LibraryScanJobStatus.Running;
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-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(); await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!; IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
@@ -74,7 +74,22 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
int totalFilesToHash = getFilesToHashCountResult.Value; int totalFilesToHash = getFilesToHashCountResult.Value;
// set the initial progress of the scan job // Get the library only when there are files to hash, and only the scalar values needed to know whether its content is stored on a solid state drive,.
// in which case the file reads run in parallel.
bool shouldParallelizeReads = false;
if (totalFilesToHash > 0)
{
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(
LibraryId.Value,
shouldIncludeNavigationProperties: false,
shouldTrackEntities: false,
cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
shouldParallelizeReads = getLibraryResult.Value.IsContentOnSsd;
}
// Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false); Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure) if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -84,7 +99,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
int processedFilesCount = 0; int processedFilesCount = 0;
string? lastPath = null; string? lastPath = null;
// process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size // Process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size.
while (true) while (true)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@@ -96,14 +111,14 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
if (filesToHashPage.Count == 0) if (filesToHashPage.Count == 0)
break; break;
// hash the files of the current page in parallel, invoking the progress callback before each file // Hash the files of the current page in parallel, invoking the progress callback before each file.
List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, async () => List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () =>
{ {
// check if enough time has passed since last update // Check if enough time has passed since last update.
DateTime now = DateTime.UtcNow; DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{ {
// increment the number of processed elements progress // Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false); publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure) if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -111,7 +126,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
} }
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
// write the computed hashes back to the staging results // Write the computed hashes back to the staging results.
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
if (updateHashesResult.IsFailure) if (updateHashesResult.IsFailure)
throw new InvalidOperationException(updateHashesResult.FirstError.Description); throw new InvalidOperationException(updateHashesResult.FirstError.Description);
@@ -119,11 +134,11 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
lastPath = filesToHashPage[^1].Path; lastPath = filesToHashPage[^1].Path;
} }
// this job finished, increment the number of processed jobs progress // This job finished, increment the number of processed jobs progress.
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed; Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload // Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children) foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
@@ -1,25 +1,26 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -31,7 +32,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Writt
/// </summary> /// </summary>
internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksFileSystemDiscoveryJob 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 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( private static readonly HashSet<string> s_bookExtensions = new(
[ [
".pdf", ".epub", ".mobi", ".azw", ".azw3", ".pdf", ".epub", ".mobi", ".azw", ".azw3",
@@ -42,11 +43,12 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
); );
private static readonly EnumerationOptions s_enumerationOptions = new() private static readonly EnumerationOptions s_enumerationOptions = new()
{ {
AttributesToSkip = FileAttributes.None, // hidden files and directories are included in the discovery AttributesToSkip = FileAttributes.None, // Hidden files and directories are included in the discovery.
IgnoreInaccessible = true, IgnoreInaccessible = true,
RecurseSubdirectories = false RecurseSubdirectories = false
}; };
private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<BooksFileSystemDiscoveryJob> _logger;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJob"/> class. /// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJob"/> class.
@@ -55,9 +57,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
/// Injected factory for creating scopes in which services are requested. /// 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. /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </param> /// </param>
public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) /// <param name="logger">Injected logger for the media library scan job.</param>
public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory, ILogger<BooksFileSystemDiscoveryJob> logger)
{ {
_serviceScopeFactory = serviceScopeFactory; _serviceScopeFactory = serviceScopeFactory;
_logger = logger;
} }
/// <summary> /// <summary>
@@ -71,34 +75,34 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
{ {
try try
{ {
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) // 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); int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// only execute this job's payload when it has no parents, or when all the parents finished their execution // only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsCompleted == Parents.Count) 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 // 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 // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
await Task.Run(async () => await Task.Run(async () =>
{ {
Status = LibraryScanJobStatus.Running; Status = LibraryScanJobStatus.Running;
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-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(); await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!; IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository // Get the library from the repository.
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null) if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
// convert it to a domain object // Convert it to a domain object.
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure) if (domainLibraryResult.IsFailure)
throw new InvalidOperationException(domainLibraryResult.FirstError.Description); 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 // 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; Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
{ {
@@ -108,7 +112,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
fingerprintsByPath = getFingerprintsResult.Value; fingerprintsByPath = getFingerprintsResult.Value;
} }
// set the initial progress of the scan job // Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure) if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -120,7 +124,12 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
List<LibraryScanStagingResultsEntity> stagingBatch = []; List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<DirectoryScanFingerprintEntity> fingerprintBatch = []; List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
// get the files for each of the media library content locations // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads)
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@@ -128,6 +137,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
await DiscoverContentLocationAsync( await DiscoverContentLocationAsync(
contentLocation.Path, contentLocation.Path,
fingerprintsByPath is not null, fingerprintsByPath is not null,
shouldParallelizeReads,
fingerprintsByPath, fingerprintsByPath,
stagingBatch, stagingBatch,
fingerprintBatch, fingerprintBatch,
@@ -136,7 +146,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
cancellationToken).ConfigureAwait(false); cancellationToken).ConfigureAwait(false);
processedContentLocations++; processedContentLocations++;
// increment the number of processed elements progress in a high-frequency counter with low overhead check // Increment the number of processed elements progress in a high-frequency counter with low overhead check.
DateTime now = DateTime.UtcNow; DateTime now = DateTime.UtcNow;
if (now - lastHeartbeat >= heartbeatInterval) if (now - lastHeartbeat >= heartbeatInterval)
{ {
@@ -148,7 +158,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
} }
} }
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
if (stagingBatch.Count > 0) if (stagingBatch.Count > 0)
{ {
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
@@ -162,11 +172,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
throw new InvalidOperationException(upsertResult.FirstError.Description); throw new InvalidOperationException(upsertResult.FirstError.Description);
} }
// this job finished, increment the number of processed jobs progress // This job finished, increment the number of processed jobs progress.
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed; Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload // Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children) foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
@@ -189,6 +199,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
/// </summary> /// </summary>
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param> /// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
/// <param name="shouldSkipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param> /// <param name="shouldSkipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
/// <param name="shouldParallelizeReads">Whether the file system reads should run in parallel, which benefits solid state drives.</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="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="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="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
@@ -202,6 +213,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
private async Task DiscoverContentLocationAsync( private async Task DiscoverContentLocationAsync(
string rootDirectoryPath, string rootDirectoryPath,
bool shouldSkipUnchangedDirectories, bool shouldSkipUnchangedDirectories,
bool shouldParallelizeReads,
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath, Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
List<LibraryScanStagingResultsEntity> stagingBatch, List<LibraryScanStagingResultsEntity> stagingBatch,
List<DirectoryScanFingerprintEntity> fingerprintBatch, List<DirectoryScanFingerprintEntity> fingerprintBatch,
@@ -212,14 +224,13 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
Queue<DirectoryInfo> directoryQueue = new(); Queue<DirectoryInfo> directoryQueue = new();
directoryQueue.Enqueue(new DirectoryInfo(rootDirectoryPath)); directoryQueue.Enqueue(new DirectoryInfo(rootDirectoryPath));
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory // 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.
// and could result in stack overflow on deeply nested directories
while (directoryQueue.Count > 0) while (directoryQueue.Count > 0)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo currentDirectory = directoryQueue.Dequeue(); 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 // 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 (shouldSkipUnchangedDirectories) if (shouldSkipUnchangedDirectories)
{ {
DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc; DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc;
@@ -235,7 +246,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
Path = currentDirectory.FullName, Path = currentDirectory.FullName,
LastWriteTimeUtc = currentLastWriteTimeUtc 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 // 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) if (fingerprintBatch.Count >= STAGING_BATCH_SIZE)
{ {
Result<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); Result<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
@@ -245,62 +256,56 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
} }
} }
// process the files of the current directory // Process the files of the current directory.
IEnumerable<FileInfo>? files = null; IEnumerable<FileInfo>? files = null;
try try
{ {
files = currentDirectory.EnumerateFiles("*", s_enumerationOptions) files = currentDirectory.EnumerateFiles("*", s_enumerationOptions)
.Where(file => s_bookExtensions.Contains(file.Extension)); .Where(file => s_bookExtensions.Contains(file.Extension));
} }
catch (IOException ex) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Debug.WriteLine(ex.Message); _logger.LogWarning(ex, "Failed to enumerate the files of the directory '{DirectoryPath}', so its files are skipped for this scan.", currentDirectory.FullName);
} }
if (files is not null) if (files is not null)
{ {
try try
{ {
foreach (FileInfo file in files) if (shouldParallelizeReads)
await StageFilesInParallelAsync(files, stagingBatch, stagingResultsRepository, cancellationToken).ConfigureAwait(false);
else
{ {
cancellationToken.ThrowIfCancellationRequested(); foreach (FileInfo file in files)
stagingBatch.Add(new LibraryScanStagingResultsEntity()
{ {
Id = Guid.NewGuid(), cancellationToken.ThrowIfCancellationRequested();
LibraryScanId = ScanId.Value, stagingBatch.Add(CreateStagingResult(file));
Path = file.FullName, if (stagingBatch.Count >= STAGING_BATCH_SIZE)
Size = file.Length, {
Ticks = file.LastWriteTimeUtc.Ticks, Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
ContentHash = 0, if (insertBatchResult.IsFailure)
PreviousContentHash = 0, throw new InvalidOperationException(insertBatchResult.FirstError.Description);
NeedsRehash = true, stagingBatch.Clear();
IsNew = true }
});
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
{
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
} }
} }
} }
catch (IOException ex) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// a file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped // A file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped.
Debug.WriteLine(ex.Message); _logger.LogWarning(ex, "Failed to read the metadata of the files of the directory '{DirectoryPath}', so the remaining files of the directory are skipped for this scan.", currentDirectory.FullName);
} }
} }
// process the subdirectories - each new subdirectory is added to the same stack queue, for later processing // Process the subdirectories - each new subdirectory is added to the same stack queue, for later processing.
IEnumerable<DirectoryInfo>? subdirectories = null; IEnumerable<DirectoryInfo>? subdirectories = null;
try try
{ {
subdirectories = currentDirectory.EnumerateDirectories("*", s_enumerationOptions); subdirectories = currentDirectory.EnumerateDirectories("*", s_enumerationOptions);
} }
catch (IOException ex) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Debug.WriteLine(ex.Message); _logger.LogWarning(ex, "Failed to enumerate the subdirectories of the directory '{DirectoryPath}', so its subtree is skipped for this scan.", currentDirectory.FullName);
} }
if (subdirectories is not null) if (subdirectories is not null)
@@ -313,14 +318,93 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
directoryQueue.Enqueue(subdirectory); directoryQueue.Enqueue(subdirectory);
} }
} }
catch (IOException ex) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Debug.WriteLine(ex.Message); _logger.LogWarning(ex, "Failed to process the subdirectories of the directory '{DirectoryPath}', so the remaining subdirectories are skipped for this scan.", currentDirectory.FullName);
} }
} }
} }
} }
/// <summary>
/// Reads the metadata of <paramref name="files"/> in parallel and writes the discovered files in batches to the staging results.
/// </summary>
/// <param name="files">The files of the current directory.</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="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
internal async Task StageFilesInParallelAsync(IEnumerable<FileInfo> files, List<LibraryScanStagingResultsEntity> stagingBatch, ILibraryScanStagingResultsRepository stagingResultsRepository, CancellationToken cancellationToken)
{
List<FileInfo> filesToProcess = [.. files];
LibraryScanStagingResultsEntity?[] discoveredFiles = new LibraryScanStagingResultsEntity?[filesToProcess.Count];
ParallelOptions parallelOptions = new()
{
CancellationToken = cancellationToken,
MaxDegreeOfParallelism = Environment.ProcessorCount
};
try
{
Parallel.For(0, filesToProcess.Count, parallelOptions, index =>
{
try
{
discoveredFiles[index] = CreateStagingResult(filesToProcess[index]);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file might become inaccessible between enumeration and processing, so it is skipped.
_logger.LogWarning(ex, "Failed to read the metadata of the book file '{Path}', so it is skipped for this scan.", filesToProcess[index].FullName);
}
});
}
catch (AggregateException aggregateException)
{
// Parallel.For wraps the exceptions thrown by its body, so the real cause is rethrown here, to keep the reported scan failure meaningful.
AggregateException flattenedException = aggregateException.Flatten();
if (flattenedException.InnerExceptions.Count == 1)
ExceptionDispatchInfo.Capture(flattenedException.InnerExceptions[0]).Throw();
throw new AggregateException(string.Join("; ", flattenedException.InnerExceptions.Select(exception => exception.Message)), flattenedException.InnerExceptions);
}
// The repository is not thread-safe, so the discovered files are written sequentially, in bounded batches.
foreach (LibraryScanStagingResultsEntity? discoveredFile in discoveredFiles)
{
cancellationToken.ThrowIfCancellationRequested();
if (discoveredFile is null)
continue;
stagingBatch.Add(discoveredFile);
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
{
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
}
}
}
/// <summary>
/// Creates a staging result entity from a discovered file.
/// </summary>
/// <param name="file">The discovered file.</param>
/// <returns>The staging result entity of the file.</returns>
private LibraryScanStagingResultsEntity CreateStagingResult(FileInfo file)
{
return 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
};
}
/// <summary> /// <summary>
/// Publishes a job progress update. /// Publishes a job progress update.
/// </summary> /// </summary>
@@ -27,36 +27,37 @@ internal class FileHashService : IFileHashService
/// Hashes <paramref name="inputFiles"/> by sampling chunks from them. /// Hashes <paramref name="inputFiles"/> by sampling chunks from them.
/// </summary> /// </summary>
/// <param name="inputFiles">The collection of files to hash.</param> /// <param name="inputFiles">The collection of files to hash.</param>
/// <param name="shouldParallelizeReads">Whether the files should be read in parallel. Parallel reads benefit solid state drives, while mechanical hard drives are faster with sequential reads.</param>
/// <param name="callback">Callback to invoke during processing of elements.</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> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of the hashed files, along with their hashes.</returns> /// <returns>A collection of the hashed files, along with their hashes.</returns>
public async Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> inputFiles, Func<Task> callback, CancellationToken cancellationToken) public async Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> inputFiles, bool shouldParallelizeReads, Func<Task> callback, CancellationToken cancellationToken)
{ {
List<HashedFileSystemFileDto> outputFiles = []; List<HashedFileSystemFileDto> outputFiles = [];
object listLock = new(); object listLock = new();
// make use of all available processors // Solid state drives benefit from reading multiple files at once, while mechanical hard drives are faster with sequential reads because of their seek time.
ParallelOptions parallelOptions = new() ParallelOptions parallelOptions = new()
{ {
CancellationToken = cancellationToken, CancellationToken = cancellationToken,
MaxDegreeOfParallelism = Environment.ProcessorCount // TODO: make this configurable, such that parallelism can be turned off for mechanical hard drives MaxDegreeOfParallelism = shouldParallelizeReads ? Environment.ProcessorCount : 1
}; };
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) => await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
try try
{ {
// invoke the method that triggers progress reporting // Invoke the method that triggers progress reporting.
await callback().ConfigureAwait(false); await callback().ConfigureAwait(false);
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Size); 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 // Get the file hash and check if it differs from the one stored on previous scan.
ulong currentHash = file.Size == 0 ulong currentHash = file.Size == 0
? s_emptyFileHash // precomputed constant: XxHash64 hash of zero-length input ? s_emptyFileHash // Precomputed constant: XxHash64 hash of zero-length input.
: ComputeFileHash(file.Path, file.Size, bufferSize); : ComputeFileHash(file.Path, file.Size, bufferSize);
// the decision of whether a file changed is already made before hashing, so all files that reach this point get their hash stored // 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) lock (listLock)
outputFiles.Add(file with { CurrentHash = currentHash }); outputFiles.Add(file with { CurrentHash = currentHash });
} }
@@ -78,7 +79,7 @@ internal class FileHashService : IFileHashService
{ {
long fileSize = new FileInfo(filePath).Length; long fileSize = new FileInfo(filePath).Length;
if (fileSize == 0) if (fileSize == 0)
return s_emptyFileHash; // precomputed constant: XxHash64 hash of zero-length input return s_emptyFileHash; // Precomputed constant: XxHash64 hash of zero-length input.
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, fileSize); ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, fileSize);
return ComputeFileHash(filePath, fileSize, bufferSize); return ComputeFileHash(filePath, fileSize, bufferSize);
@@ -92,46 +93,46 @@ internal class FileHashService : IFileHashService
/// <param name="bufferSize">Sample window size (automatically clamped to file size).</param> /// <param name="bufferSize">Sample window size (automatically clamped to file size).</param>
private static unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize) private static unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize)
{ {
// create a memory-mapped file for efficient access to large files // Create a memory-mapped file for efficient access to large files.
using MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); using MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read);
// create a view accessor to read from the memory-mapped file // Create a view accessor to read from the memory-mapped file.
using MemoryMappedViewAccessor memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, fileSize, MemoryMappedFileAccess.Read); using MemoryMappedViewAccessor memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, fileSize, MemoryMappedFileAccess.Read);
byte* memoryPointer = null; byte* memoryPointer = null;
try try
{ {
// get a direct pointer to the memory-mapped file, for faster access // Get a direct pointer to the memory-mapped file, for faster access.
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer); memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer);
// get the thread-local hasher and reset it before use; resetting at entry (rather than at exit) ensures // 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 // the hasher is always in a clean state even if a previous call on this thread threw mid-computation.
XxHash64 hasher = s_threadLocalHasher.Value!; XxHash64 hasher = s_threadLocalHasher.Value!;
hasher.Reset(); hasher.Reset();
// allocate hash result buffer on the stack, to avoid heap allocation // Allocate hash result buffer on the stack, to avoid heap allocation.
Span<byte> hashSpan = stackalloc byte[sizeof(ulong)]; Span<byte> hashSpan = stackalloc byte[sizeof(ulong)];
// process only predefined sampled segments of the file, instead of the entire file // Process only predefined sampled segments of the file, instead of the entire file.
foreach (long offset in GetByteBufferSampleOffsets(fileSize, bufferSize)) foreach (long offset in GetByteBufferSampleOffsets(fileSize, bufferSize))
{ {
// calculate how many bytes to read (handle edge case at end of file, or when the file size is smaller than the buffer) // Calculate how many bytes to read (handle edge case at end of file, or when the file size is smaller than the buffer).
ushort readSize = (ushort)Math.Min(bufferSize, fileSize - offset); ushort readSize = (ushort)Math.Min(bufferSize, fileSize - offset);
// create a span directly over the memory-mapped region // Create a span directly over the memory-mapped region.
ReadOnlySpan<byte> dataSpan = new(memoryPointer + offset, readSize); ReadOnlySpan<byte> dataSpan = new(memoryPointer + offset, readSize);
// update the hash with this chunk of data // Update the hash with this chunk of data.
hasher.Append(dataSpan); hasher.Append(dataSpan);
} }
// get the final hash value // Get the final hash value.
if (!hasher.TryGetCurrentHash(hashSpan, out int bytesWritten) || bytesWritten != sizeof(ulong)) if (!hasher.TryGetCurrentHash(hashSpan, out int bytesWritten) || bytesWritten != sizeof(ulong))
throw new InvalidOperationException("Hash computation failed"); throw new InvalidOperationException("Hash computation failed");
// convert the hash byte span to a long, and return it // Convert the hash byte span to a long, and return it.
return BitConverter.ToUInt64(hashSpan); return BitConverter.ToUInt64(hashSpan);
} }
finally finally
{ {
if (memoryPointer is not null) // always release the pointer, to prevent memory leaks if (memoryPointer is not null) // Always release the pointer, to prevent memory leaks.
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer(); memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer();
} }
} }
@@ -144,20 +145,20 @@ internal class FileHashService : IFileHashService
/// <returns>An enumerable of byte offsets to sample from the file.</returns> /// <returns>An enumerable of byte offsets to sample from the file.</returns>
private static IEnumerable<long> GetByteBufferSampleOffsets(long fileSize, ushort bufferSize) private static IEnumerable<long> GetByteBufferSampleOffsets(long fileSize, ushort bufferSize)
{ {
// for small files, just read from the beginning // For small files, just read from the beginning.
if (fileSize <= bufferSize * SAMPLE_COUNT) if (fileSize <= bufferSize * SAMPLE_COUNT)
{ {
yield return 0; yield return 0;
yield break; yield break;
} }
// for larger files, sample at strategic points: // For larger files, sample at strategic points:
yield return 0; // beginning of the file yield return 0; // Beginning of the file.
yield return fileSize / 4; // quarter of the file yield return fileSize / 4; // Quarter of the file.
yield return fileSize / 2; // half of the file yield return fileSize / 2; // Half of the file.
yield return 3 * fileSize / 4; // three quarters 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) yield return Math.Max(0, fileSize - bufferSize); // End of the file (ensure we don't go past the end).
// additional evenly spaced samples, if needed // Additional evenly spaced samples, if needed.
long interval = fileSize / (SAMPLE_COUNT + 1); long interval = fileSize / (SAMPLE_COUNT + 1);
for (int i = 1; i <= SAMPLE_COUNT - 4; i++) for (int i = 1; i <= SAMPLE_COUNT - 4; i++)
yield return interval * i; yield return interval * i;