Implements file hashing media library scan job

This commit is contained in:
BinaryAlley committed 2025-03-01 16:44:10 +02:00
1 parent 66998055f0
commit 03a000e1e4
63 files changed
+2009 -287

No files matched your search

@@ -46,7 +46,8 @@ public static class InfrastructureLayerServices
// scan the current assembly for validators and add them to the DI container
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
services.AddSingleton<IHashService, HashService>();
services.AddSingleton<IFileHashService, FileHashService>();
services.AddSingleton<IPasswordHashService, PasswordHashService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
@@ -68,10 +69,12 @@ public static class InfrastructureLayerServices
services.AddTransient<IFileSystemDiscoveryJob, FileSystemDiscoveryJob>();
services.AddTransient<IRepositoryMetadataDiscoveryJob, RepositoryMetadataDiscoveryJob>();
services.AddTransient<IBooksFileExtensionsFilterJob, BooksFileExtensionsFilterJob>();
services.AddTransient<IHashComparerJob, HashComparerJob>();
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
return services;
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Infrastructure.Common.Errors;
/// <summary>
/// Media Library Scan error types.
/// </summary>
public static partial class Errors
{
public static class LibraryScanning
{
public static Error FailedToCreateScanJobProgress => Error.Failure(description: nameof(FailedToCreateScanJobProgress));
}
}
@@ -4,21 +4,20 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads;
using Lumina.Infrastructure.Common.Errors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -30,23 +29,17 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// </summary>
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
{
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
/// <param name="fileService">Injected service for handling files.</param>
/// <param name="serviceScopeFactory">
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
/// </param>
public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService, IServiceScopeFactory serviceScopeFactory)
public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
{
_directoryService = directoryService;
_fileService = fileService;
_serviceScopeFactory = serviceScopeFactory;
}
@@ -65,19 +58,20 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
Console.WriteLine("started file discovering");
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine("Started file system discovery scan job...");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -85,57 +79,58 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
DateTime lastHeartbeat = DateTime.UtcNow;
long processedFiles = 0L;
int processedContentLocations = 0;
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
// get the files for each of the media library content locations
List<FileInfo> discoveredFiles = [];
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
await Task.Delay(1000);
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken);
if (treeResult.IsError)
{
// handle errors, maybe:
// Status = LibraryScanJobStatus.Failed;
}
else
contentLocationTrees.Add(treeResult.Value);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
foreach (FileInfo file in GetFiles(contentLocation.Path, true, cancellationToken))
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
discoveredFiles.Add(file);
processedFiles++;
// increment the number of processed elements progress in a high-frequency counter with low overhead check
if (processedFiles % 1000 == 0)
{
DateTime now = DateTime.UtcNow;
if (now - lastHeartbeat >= heartbeatInterval)
{
publishJobProgressResult = await PublishJobProgress(
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
lastHeartbeat = now;
}
}
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
processedContentLocations++;
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended file discovering");
sw.Stop();
Console.WriteLine($"Ended file system discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {discoveredFiles.Count} files.");
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false);
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, discoveredFiles, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
@@ -147,69 +142,97 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
}
/// <summary>
/// Builds a hierarchical tree structure representing the file system starting from the specified path.
/// Gets all files under the specified directory.
/// </summary>
/// <param name="path">The identifier of the root path from which to build the tree.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the tree.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default)
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details.
/// </remarks>
/// <returns>The discovered collection of files.</returns>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static IEnumerable<FileInfo> GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken)
{
// validate the path and get the root directory node
ErrorOr<Directory> rootDirectoryResult = Directory.Create(path, path.Path, Optional<DateTime>.None(), Optional<DateTime>.None());
if (rootDirectoryResult.IsError)
return rootDirectoryResult.Errors;
Queue<DirectoryInfo> directoryStack = new();
directoryStack.Enqueue(new DirectoryInfo(rootDirectoryPath));
// build the tree starting from the root directory
return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements, cancellationToken);
EnumerationOptions enumerationOptions = new()
{
AttributesToSkip = includeHiddenElements ? FileAttributes.None : FileAttributes.Hidden,
IgnoreInaccessible = true,
RecurseSubdirectories = false
};
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
// and could result in stack overflow on deeply nested directories
while (directoryStack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo currentDirectory = directoryStack.Dequeue();
// process files first
IEnumerable<FileInfo>? files = null;
try
{
files = currentDirectory.EnumerateFiles("*", enumerationOptions);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
if (files is not null)
{
foreach (FileInfo file in files)
{
cancellationToken.ThrowIfCancellationRequested();
yield return file;
}
}
// process subdirectories - each new subdirectory is added to the same stack queue, for later processing
IEnumerable<DirectoryInfo>? subdirs = null;
try
{
subdirs = currentDirectory.EnumerateDirectories("*", enumerationOptions);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
if (subdirs is not null)
{
foreach (DirectoryInfo subdir in subdirs)
{
cancellationToken.ThrowIfCancellationRequested();
directoryStack.Enqueue(subdir);
}
}
}
}
/// <summary>
/// Recursively builds a tree node for a given directory, including its subdirectories and files.
/// Publishes a job progress update.
/// </summary>
/// <param name="directory">The directory for which to build a tree node.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the node's children.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildNodeRecursive(Directory directory, bool includeHiddenElements, CancellationToken cancellationToken)
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
FileSystemTreeNode node = new()
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
{
Path = directory.Id.Path,
Name = directory.Name,
ItemType = FileSystemItemType.Directory,
Children = []
};
// fetch and add subdirectories
ErrorOr<IEnumerable<Directory>> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements);
if (subdirectoriesResult.IsError)
return subdirectoriesResult.Errors;
foreach (Directory subdirectory in subdirectoriesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements, cancellationToken);
if (subNodeResult.IsError)
return subNodeResult.Errors;
node.Children.Add(subNodeResult.Value);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
}
// fetch and add files
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(directory.Id, includeHiddenElements);
if (filesResult.IsError)
return filesResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
foreach (File file in filesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
node.Children.Add(new FileSystemTreeNode
{
Path = file.Id.Path,
Name = file.Name,
ItemType = FileSystemItemType.File,
Children = [] // files have no children
});
}
return node;
return Result.Success;
}
}
@@ -3,17 +3,22 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Common.Errors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -26,6 +31,8 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private Dictionary<string, LibraryScanResultEntity> libraryScanResultEntities = [];
private List<FileInfo> files = [];
/// <summary>
/// Initializes a new instance of the <see cref="HashComparerJob"/> class.
@@ -46,70 +53,115 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// store the incoming payloads as they arrive from parent jobs
if (input is Dictionary<string, LibraryScanResultEntity> libraryScanResultsPayload)
libraryScanResultEntities = libraryScanResultsPayload;
else if (input is List<FileInfo> filesPayload)
files = filesPayload;
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
Console.WriteLine("started file hashing");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
Status = LibraryScanJobStatus.Running;
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine("Started file hashing...");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IFileService fileService = asyncServiceScope.ServiceProvider.GetService<IFileService>()!;
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// convert it to a domain object
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 50, "ComparingFileHashes");
//ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = Enumerable.Range(0, 50).ToList();
foreach (int nr in ints)
{
await Task.Delay(100);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
nr, 50, "ComparingFileHashes");
//scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended file hashing");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
// convert it to a domain object
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job; total progress is going twice through the list of files, once to determine what needs to be hashed, second to actually hash
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, files.Count * 2, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
DateTime lastUpdateTime = DateTime.UtcNow;
int minUpdateIntervalMs = 100;
// pre-allocate with worst case scenario, to avoid memory copying and garbage collection
List<FileInfo> filesToHash = new(files.Count);
for (int i = 0; i < files.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
FileInfo file = files[i];
// fastest path - file does not exist in past scan, so it's a new file
if (!libraryScanResultEntities.TryGetValue(file.FullName, out LibraryScanResultEntity? previousScanFile))
filesToHash.Add(file);
else if (file.Length != previousScanFile.FileSize) // next best comparison, check if file size or the last modified date changed
filesToHash.Add(file); // definitely changed
else if (file.LastWriteTimeUtc != previousScanFile.LastModified) // potential change - requires hash verification
filesToHash.Add(file);
// remove any found items, to speed up subsequent lookups (if needed, all the remaining entries in this dictionary at the end of the scan are deleted filed)
libraryScanResultEntities.Remove(file.FullName);
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, files.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
// update the last update time
lastUpdateTime = now;
}
}
int processedFiles = 0;
List<ChangedFileSystemFile> processed = fileHashService.HashFiles(filesToHash, libraryScanResultEntities,
async () =>
{
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(
publisher, compositeKey, Interlocked.Increment(ref processedFiles), files.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
// update the last update time
lastUpdateTime = now;
}
}, cancellationToken);
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
sw.Stop();
Console.WriteLine($"Ended file hashing in {sw.ElapsedMilliseconds}ms, hashed {processed.Count} files.");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, files, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -118,4 +170,28 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
throw;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
}
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -9,10 +9,13 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Common.Errors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -49,23 +52,26 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
Console.WriteLine("started repo discovering");
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine("Started repo discovering...");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository<ILibraryScanResultRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -73,45 +79,35 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// set the initial progress of the scan job, it's a 1 step job - retrieving stuff from repository
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// get the results of the last scan of the media library
ErrorOr<Dictionary<string, LibraryScanResultEntity>> getScanResultsResult =
await libraryScanResultRepository.GetPathMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getScanResultsResult.IsError)
return;
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(1000);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(
new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended repo discovering");
sw.Stop();
Console.WriteLine($"Ended repository discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {getScanResultsResult.Value.Count} items.");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, getScanResultsResult.Value, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
@@ -121,4 +117,28 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
throw;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
}
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -9,10 +9,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Common.Errors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -49,23 +51,24 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
Console.WriteLine("started repo saving");
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine("Started repository saving...");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -73,40 +76,29 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(500);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
await publisher!.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended repo saving");
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
sw.Stop();
Console.WriteLine($"Ended repository saving scan job in {sw.ElapsedMilliseconds}ms, saved {ints.Count} items.");
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
}, cancellationToken).ConfigureAwait(false);
}
@@ -117,4 +109,28 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
throw;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
}
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads;
/// <summary>
/// Generic file system node.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class FileSystemTreeNode
{
/// <summary>
/// Gets or sets the full path of the file or directory.
/// </summary>
public string Path { get; set; } = null!;
/// <summary>
/// Gets or sets the name of the file or directory.
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the type of the item, indicating whether it is a file, directory, or drive.
/// </summary>
public FileSystemItemType ItemType { get; set; }
/// <summary>
/// Gets or sets the list of child nodes.
/// </summary>
public List<FileSystemTreeNode> Children { get; set; } = [];
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using Lumina.Infrastructure.Common.Errors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Media library scan job for filtering only files that have known book formats extensions.
/// </summary>
internal sealed class BooksFileExtensionsFilterJob : MediaLibraryScanJob, IBooksFileExtensionsFilterJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly string[] _knownBookFileExtensions =
[
".pdf", ".epub", ".mobi", ".azw", ".azw3",
".cbz", ".cbr", ".djvu", ".fb2", ".lit",
".prc", ".txt", ".doc", ".docx", ".rtf"
];
/// <summary>
/// Initializes a new instance of the <see cref="BooksFileExtensionsFilterJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
/// </param>
public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
if (input is List<FileInfo> payload)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
Stopwatch sw = Stopwatch.StartNew();
Console.WriteLine("Started book file filtering...");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// convert it to a domain object
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
DateTime lastUpdateTime = DateTime.UtcNow;
int minUpdateIntervalMs = 100;
List<FileInfo> bookFiles = new(payload.Count / 2); // pre-allocate with estimated capacity (boy, that's an optimistic view on books...)
for (int i = 0; i < payload.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
FileInfo file = payload[i];
if (HasKnownBookExtension(file.Name.AsSpan()))
bookFiles.Add(file);
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// update job progress report
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, payload.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
// update the last update time
lastUpdateTime = now;
}
}
// this job finished, increment the number of processed jobs progress
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
sw.Stop();
Console.WriteLine($"Ended book file filtering in {sw.ElapsedMilliseconds}ms, filtered {bookFiles.Count} files.");
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, bookFiles, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
/// <summary>
/// Checks if <paramref name="filePath"/> has a known book file extension or not.
/// </summary>
/// <param name="filePath">The file path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="filePath"/> contains a known book file extension, <see langword="false"/> otherwise.</returns>
public bool HasKnownBookExtension(ReadOnlySpan<char> filePath)
{
// find the last dot in the path
int lastDotIndex = filePath.LastIndexOf('.');
// if no dot found or it's the last character, return false
if (lastDotIndex == -1)
return false;
// get the extension part (including the dot)
ReadOnlySpan<char> extension = filePath[lastDotIndex..];
// check against each known extension
foreach (string knownExt in _knownBookFileExtensions)
if (extension.SequenceEqual(knownExt.AsSpan()))
return true;
return false;
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "FilteringBookFiles");
if (scanJobProgressResult.IsError)
{
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
}
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -109,8 +109,8 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended goodreads metadata");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security;
using Microsoft.Extensions.ObjectPool;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Hashing;
using System.IO.MemoryMappedFiles;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Security;
/// <summary>
/// Service for hashing files by sampling chunks from them.
/// </summary>
internal class FileHashService : IFileHashService
{
private const int SAMPLE_COUNT = 6; // number of sample points for hash computation
private const ushort DEFAULT_BUFFER_SIZE = 65535; // buffer size (64KB - 1) for reading file chunks
private readonly ThreadLocal<byte[]> _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing
private static readonly ObjectPool<XxHash64> s_hasherPool = new DefaultObjectPool<XxHash64>(new DefaultPooledObjectPolicy<XxHash64>()); // object pool for reusing hashers, to reduce GC pressure
/// <summary>
/// Hashes <paramref name="files"/> by sampling chunks from them.
/// </summary>
/// <param name="files">The collection of files to hash.</param>
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
/// <param name="callback">Callback to invoke during processing of elements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
public List<ChangedFileSystemFile> HashFiles(
List<FileInfo> files,
Dictionary<string, LibraryScanResultEntity> previousScanResults,
Func<Task> callback,
CancellationToken cancellationToken)
{
List<ChangedFileSystemFile> changedFiles = [];
object listLock = new();
int totalFiles = files.Count;
// make use of all available processors
ParallelOptions parallelOptions = new()
{
CancellationToken = cancellationToken,
MaxDegreeOfParallelism = Environment.ProcessorCount
};
Parallel.ForEach(files, parallelOptions, async file =>
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// invoke the method that triggers progress reporting
await callback().ConfigureAwait(false);
// if file has no contents, it needs no hashing
if (file.Length == 0)
return;
// buffer management with thread-local reuse
byte[] buffer = _threadLocalBuffer.Value ?? new byte[DEFAULT_BUFFER_SIZE];
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Length);
// get the file hash and check if it differs from the one stored on previous scan
ulong currentHash = ComputeFileHash(file.FullName, file.Length, bufferSize, buffer);
bool isChanged = !previousScanResults.TryGetValue(file.FullName, out LibraryScanResultEntity? previous) || previous.ContentHash != currentHash;
if (isChanged) // hash changed, file needs to be re-scanned
lock (listLock)
changedFiles.Add(new ChangedFileSystemFile(file, currentHash));
}
catch (Exception ex)
{
Debug.WriteLine($"Error processing {file.FullName}: {ex.Message}");
}
});
return changedFiles;
}
/// <summary>
/// Computes content hash using memory-mapped sampling.
/// </summary>
/// <param name="bufferSize">Sample window size (automatically clamped to file size).</param>
/// <param name="buffer">Reusable read buffer (thread-local allocation optimized).</param>
private unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize, byte[] buffer)
{
// 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
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
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer);
// get a hasher from the pool to avoid allocations
XxHash64 hasher = s_hasherPool.Get();
// 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
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)
ushort readSize = (ushort)Math.Min(bufferSize, fileSize - offset);
// create a span directly over the memory-mapped region
ReadOnlySpan<byte> dataSpan = new(memoryPointer + offset, readSize);
// update the hash with this chunk of data
hasher.Append(dataSpan);
}
// 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
return BitConverter.ToUInt64(hashSpan);
}
finally
{
if (memoryPointer is not null) // always release the pointer, to prevent memory leaks
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer();
}
}
/// <summary>
/// Generates sample offsets for reading portions of a file.
/// </summary>
/// <param name="fileSize">The size of the file, in bytes.</param>
/// <param name="bufferSize">The buffer size used for reading.</param>
/// <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
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; // file 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
long interval = fileSize / (SAMPLE_COUNT + 1);
for (int i = 1; i <= SAMPLE_COUNT - 4; i++)
yield return interval * i;
}
}
@@ -11,7 +11,7 @@ namespace Lumina.Infrastructure.Core.Security;
/// <summary>
/// Service for hashing passwords.
/// </summary>
public sealed class HashService : IHashService
public sealed class PasswordHashService : IPasswordHashService
{
// OWASP recommended parameters for Argon2id
private const int MEMORY_SIZE = 19456; // 19 MiB (19 * 1024 = 19456)
@@ -7,6 +7,7 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
@@ -19,6 +20,7 @@
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.2.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0" />
@@ -27,6 +29,7 @@
<PackageReference Include="Otp.NET" Version="1.4.0" />
<PackageReference Include="QRCoder" Version="1.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
<PackageReference Include="System.IO.Hashing" Version="9.0.2" />
</ItemGroup>
<ItemGroup>