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.
/// </summary>
/// <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="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <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>
/// 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.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -41,6 +43,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
StringComparer.OrdinalIgnoreCase
);
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MusicFileSystemDiscoveryJob> _logger;
/// <summary>
/// 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.
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </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;
_logger = logger;
}
/// <summary>
@@ -116,6 +121,11 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads)
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
@@ -126,6 +136,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
fileProviderService,
directoryProviderService,
fingerprintsByPath is not null,
shouldParallelizeReads,
fingerprintsByPath,
stagingBatch,
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="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="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="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>
@@ -204,6 +216,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
IFileProviderService fileProviderService,
IDirectoryProviderService directoryProviderService,
bool shouldSkipUnchangedDirectories,
bool shouldParallelizeReads,
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
List<LibraryScanStagingResultsEntity> stagingBatch,
List<DirectoryScanFingerprintEntity> fingerprintBatch,
@@ -258,40 +271,24 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
Result<IEnumerable<FileSystemPathId>> getFilesResult = fileProviderService.GetFilePaths(currentDirectory, true);
if (getFilesResult.IsSuccess)
{
foreach (FileSystemPathId filePath in getFilesResult.Value)
if (shouldParallelizeReads)
await StageFilesInParallelAsync(getFilesResult.Value, fileProviderService, stagingBatch, stagingResultsRepository, cancellationToken).ConfigureAwait(false);
else
{
cancellationToken.ThrowIfCancellationRequested();
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()
foreach (FileSystemPathId filePath in getFilesResult.Value)
{
Id = Guid.NewGuid(),
LibraryScanId = ScanId.Value,
Path = filePath.Path,
Size = size,
Ticks = ticks,
ContentHash = 0,
PreviousContentHash = 0,
NeedsRehash = true,
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();
cancellationToken.ThrowIfCancellationRequested();
if (!s_audioExtensions.Contains(Path.GetExtension(filePath.Path)))
continue;
stagingBatch.Add(CreateStagingResult(filePath, fileProviderService));
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();
}
}
}
}
@@ -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>
/// Publishes a job progress update.
/// </summary>
@@ -1,19 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
@@ -23,7 +23,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// </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 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>
@@ -49,9 +49,9 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
{
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);
// only execute this job's payload when it has no parents, or when all the parents finished their execution
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
@@ -59,7 +59,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
await Task.Run(async () =>
{
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();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
@@ -74,7 +74,22 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
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);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -84,7 +99,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
int processedFilesCount = 0;
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)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -96,14 +111,14 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
if (filesToHashPage.Count == 0)
break;
// hash the files of the current page in parallel, invoking the progress callback before each file
List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, async () =>
// Hash the files of the current page in parallel, invoking the progress callback before each file.
List<HashedFileSystemFileDto> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, shouldParallelizeReads, async () =>
{
// check if enough time has passed since last update
// 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
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -111,7 +126,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
}
}, 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);
if (updateHashesResult.IsFailure)
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
@@ -119,11 +134,11 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
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);
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -1,25 +1,26 @@
#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.Mapping.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
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.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -31,7 +32,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Writt
/// </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 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",
@@ -42,11 +43,12 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
);
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,
RecurseSubdirectories = false
};
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<BooksFileSystemDiscoveryJob> _logger;
/// <summary>
/// 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.
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </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;
_logger = logger;
}
/// <summary>
@@ -71,34 +75,34 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
{
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);
// 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
// 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:
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
// Get the library from the repository.
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
// convert it to a domain object
// Convert it to a domain object.
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure)
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
// when the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan
// 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)
{
@@ -108,7 +112,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
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);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -120,7 +124,12 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
List<LibraryScanStagingResultsEntity> stagingBatch = [];
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)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -128,6 +137,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
await DiscoverContentLocationAsync(
contentLocation.Path,
fingerprintsByPath is not null,
shouldParallelizeReads,
fingerprintsByPath,
stagingBatch,
fingerprintBatch,
@@ -136,7 +146,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
cancellationToken).ConfigureAwait(false);
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;
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)
{
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);
}
// 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);
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -189,6 +199,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
/// </summary>
/// <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="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="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>
@@ -202,6 +213,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
private async Task DiscoverContentLocationAsync(
string rootDirectoryPath,
bool shouldSkipUnchangedDirectories,
bool shouldParallelizeReads,
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
List<LibraryScanStagingResultsEntity> stagingBatch,
List<DirectoryScanFingerprintEntity> fingerprintBatch,
@@ -212,14 +224,13 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
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
// 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
// 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)
{
DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc;
@@ -235,7 +246,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
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
// 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)
{
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;
try
{
files = currentDirectory.EnumerateFiles("*", s_enumerationOptions)
.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)
{
try
{
foreach (FileInfo file in files)
if (shouldParallelizeReads)
await StageFilesInParallelAsync(files, stagingBatch, stagingResultsRepository, cancellationToken).ConfigureAwait(false);
else
{
cancellationToken.ThrowIfCancellationRequested();
stagingBatch.Add(new LibraryScanStagingResultsEntity()
foreach (FileInfo file in files)
{
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)
{
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
cancellationToken.ThrowIfCancellationRequested();
stagingBatch.Add(CreateStagingResult(file));
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
Debug.WriteLine(ex.Message);
// A file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped.
_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;
try
{
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)
@@ -313,14 +318,93 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
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>
/// Publishes a job progress update.
/// </summary>
@@ -27,36 +27,37 @@ internal class FileHashService : IFileHashService
/// Hashes <paramref name="inputFiles"/> by sampling chunks from them.
/// </summary>
/// <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="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <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 = [];
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()
{
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) =>
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// invoke the method that triggers progress reporting
// Invoke the method that triggers progress reporting.
await callback().ConfigureAwait(false);
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
? 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);
// 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)
outputFiles.Add(file with { CurrentHash = currentHash });
}
@@ -78,7 +79,7 @@ internal class FileHashService : IFileHashService
{
long fileSize = new FileInfo(filePath).Length;
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);
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>
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);
// 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);
byte* memoryPointer = null;
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);
// 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
// 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
// Allocate hash result buffer on the stack, to avoid heap allocation.
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))
{
// 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);
// 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);
// update the hash with this chunk of data
// Update the hash with this chunk of data.
hasher.Append(dataSpan);
}
// get the final hash value
// Get the final hash value.
if (!hasher.TryGetCurrentHash(hashSpan, out int bytesWritten) || bytesWritten != sizeof(ulong))
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);
}
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();
}
}
@@ -144,20 +145,20 @@ internal class FileHashService : IFileHashService
/// <returns>An enumerable of byte offsets to sample from the file.</returns>
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)
{
yield return 0;
yield break;
}
// 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; // 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)
// 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; // 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).
// additional evenly spaced samples, if needed
// Additional evenly spaced samples, if needed.
long interval = fileSize / (SAMPLE_COUNT + 1);
for (int i = 1; i <= SAMPLE_COUNT - 4; i++)
yield return interval * i;