mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +00:00
Replaces the in-memory media library scan diff with a database-centric job pipeline
This commit is contained in:
1 parent
1dc3da3da1
commit
9905aa08f9
38 files changed
+1032
-987
No files matched your search
-238
@@ -1,238 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started file system discovery scan job...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
long processedFiles = 0L;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
// get the files for each of the media library content locations
|
||||
List<FileInfo> discoveredFiles = [];
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
foreach (FileInfo file in GetFiles(contentLocation.Path, true, cancellationToken))
|
||||
{
|
||||
discoveredFiles.Add(file);
|
||||
processedFiles++;
|
||||
|
||||
// increment the number of processed elements progress in a high-frequency counter with low overhead check
|
||||
if (processedFiles % 1000 == 0)
|
||||
{
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
processedContentLocations++;
|
||||
}
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended file system discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {discoveredFiles.Count} files.");
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, discoveredFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all files under the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details.
|
||||
/// </remarks>
|
||||
/// <returns>The discovered collection of files.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static IEnumerable<FileInfo> GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> directoryStack = new();
|
||||
directoryStack.Enqueue(new DirectoryInfo(rootDirectoryPath));
|
||||
|
||||
EnumerationOptions enumerationOptions = new()
|
||||
{
|
||||
AttributesToSkip = includeHiddenElements ? FileAttributes.None : FileAttributes.Hidden,
|
||||
IgnoreInaccessible = true,
|
||||
RecurseSubdirectories = false
|
||||
};
|
||||
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
|
||||
// and could result in stack overflow on deeply nested directories
|
||||
while (directoryStack.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
DirectoryInfo currentDirectory = directoryStack.Dequeue();
|
||||
|
||||
// process files first
|
||||
IEnumerable<FileInfo>? files = null;
|
||||
try
|
||||
{
|
||||
files = currentDirectory.EnumerateFiles("*", enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (files is not null)
|
||||
{
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
yield return file;
|
||||
}
|
||||
}
|
||||
|
||||
// process subdirectories - each new subdirectory is added to the same stack queue, for later processing
|
||||
IEnumerable<DirectoryInfo>? subdirs = null;
|
||||
try
|
||||
{
|
||||
subdirs = currentDirectory.EnumerateDirectories("*", enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (subdirs is not null)
|
||||
{
|
||||
foreach (DirectoryInfo subdir in subdirs)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
directoryStack.Enqueue(subdir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
-197
@@ -1,197 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private Dictionary<string, LibraryScanResultEntity> libraryScanResultEntities = [];
|
||||
private List<FileInfo> files = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HashComparerJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public HashComparerJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
|
||||
// store the incoming payloads as they arrive from parent jobs
|
||||
if (input is Dictionary<string, LibraryScanResultEntity> libraryScanResultsPayload)
|
||||
libraryScanResultEntities = libraryScanResultsPayload;
|
||||
else if (input is List<FileInfo> filesPayload)
|
||||
files = filesPayload;
|
||||
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started file hashing...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
IFileService fileService = asyncServiceScope.ServiceProvider.GetService<IFileService>()!;
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job; total progress is going twice through the list of files, once to determine what needs to be hashed, second to actually hash
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, files.Count * 2, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
// pre-allocate with worst case scenario, to avoid memory copying and garbage collection
|
||||
List<FileInfo> filesToHash = new(files.Count);
|
||||
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
FileInfo file = files[i];
|
||||
// fastest path - file does not exist in past scan, so it's a new file
|
||||
if (!libraryScanResultEntities.TryGetValue(file.FullName, out LibraryScanResultEntity? previousScanFile))
|
||||
filesToHash.Add(file);
|
||||
else if (file.Length != previousScanFile.FileSize) // next best comparison, check if file size or the last modified date changed
|
||||
filesToHash.Add(file); // definitely changed
|
||||
else if (file.LastWriteTimeUtc != previousScanFile.LastModified) // potential change - requires hash verification
|
||||
filesToHash.Add(file);
|
||||
|
||||
// remove any found items, to speed up subsequent lookups (if needed, all the remaining entries in this dictionary at the end of the scan are deleted filed)
|
||||
libraryScanResultEntities.Remove(file.FullName);
|
||||
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, files.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
int processedFilesCount = 0;
|
||||
List<ChangedFileSystemFile> processedFiles = await fileHashService.HashFilesAsync(filesToHash, libraryScanResultEntities,
|
||||
async () =>
|
||||
{
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), files.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended file hashing in {sw.ElapsedMilliseconds}ms, hashed {processedFiles.Count} files.");
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, processedFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+33
-54
@@ -1,21 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -23,25 +16,31 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for retrieving persistence data from any eventual previous scans.
|
||||
/// Media library scan job for computing the differences between the files on disk and the media library scan snapshot of the previous scan.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
|
||||
internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibraryScanDiffJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataDiscoveryJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanDiffJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanDiffJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -52,62 +51,40 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started repo discovering...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository<ILibraryScanResultRepository>();
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job, it's a 1 step job - retrieving stuff from repository
|
||||
// set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// get the results of the last scan of the media library
|
||||
ErrorOr<Dictionary<string, LibraryScanResultEntity>> getScanResultsResult =
|
||||
await libraryScanResultRepository.GetPathMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getScanResultsResult.IsError)
|
||||
return;
|
||||
// mark the staging results against the media library scan snapshot of the previous scan
|
||||
ErrorOr<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (markChangesResult.IsError)
|
||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended repository discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {getScanResultsResult.Value.Count} items.");
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, getScanResultsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -116,6 +93,11 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,12 +111,9 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData");
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for computing the content hashes of the files that changed since the previous scan.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibraryScanHashJob
|
||||
{
|
||||
private const int HASHING_PAGE_SIZE = 1000; // the number of files that are hashed and written back in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public MediaLibraryScanHashJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// count the files that need hashing, for progress reporting purposes
|
||||
ErrorOr<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashCountResult.IsError)
|
||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
||||
int totalFilesToHash = getFilesToHashCountResult.Value;
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedFilesCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<IReadOnlyList<HashedFileSystemFile>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsError)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> filesToHashPage = getFilesToHashPageResult.Value;
|
||||
if (filesToHashPage.Count == 0)
|
||||
break;
|
||||
|
||||
// hash the files of the current page in parallel, invoking the progress callback before each file
|
||||
List<HashedFileSystemFile> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, async () =>
|
||||
{
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// write the computed hashes back to the staging results
|
||||
ErrorOr<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||
if (updateHashesResult.IsError)
|
||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||
|
||||
lastPath = filesToHashPage[^1].Path;
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+47
-51
@@ -1,20 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -22,25 +17,31 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// Media library scan job for persisting the results of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob
|
||||
internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMediaLibraryScanResultsSaveJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataSaveJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanResultsSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -51,54 +52,48 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started repository saving...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
// set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> ints = [1, 2, 3];
|
||||
foreach (int nr in ints)
|
||||
// get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them
|
||||
ErrorOr<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getDeletedPathsResult.IsError)
|
||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
||||
|
||||
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
|
||||
ErrorOr<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (applySnapshotSwapResult.IsError)
|
||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||
|
||||
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
|
||||
foreach (string deletedPath in getDeletedPathsResult.Value)
|
||||
{
|
||||
await Task.Delay(500);
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// this job finished, and it's the last in the chain, the scan is completed
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended repository saving scan job in {sw.ElapsedMilliseconds}ms, saved {ints.Count} items.");
|
||||
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -108,6 +103,11 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,13 +123,9 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for publishing the media library scan failure domain event, from within a media library scan job.
|
||||
/// </summary>
|
||||
internal static class ScanFailurePublisher
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes the media library scan failure domain event for the scan that the job is part of.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which the publisher is resolved.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan has failed.</param>
|
||||
/// <param name="compositeKey">Model for tracking media library scans.</param>
|
||||
/// <param name="exception">The exception that caused the failure.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public static async Task PublishAsync(IServiceScopeFactory serviceScopeFactory, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, Exception exception, CancellationToken cancellationToken)
|
||||
{
|
||||
// failure reporting is best-effort, a failure to report the failure must not crash the job processing
|
||||
try
|
||||
{
|
||||
await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope();
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// the failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
|
||||
/// </summary>
|
||||
internal sealed class ScanJobRegistry : IScanJobRegistry
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly IReadOnlyDictionary<string, IReadOnlyList<Type>> _jobsByHook;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanJobRegistry"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider, used to resolve the registered plugin jobs.</param>
|
||||
/// <param name="jobsByHook">The media library scan job types registered for each hook point, provided by the composition root of the plugin system.</param>
|
||||
public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary<string, IReadOnlyList<Type>> jobsByHook)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_jobsByHook = jobsByHook;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scan jobs registered for the provided <paramref name="hookName"/>.
|
||||
/// </summary>
|
||||
/// <param name="hookName">The name of the hook point at which the media library scan jobs were injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The collection of media library scan jobs registered at the provided hook point.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> GetJobsForHook(string hookName, LibraryId libraryId)
|
||||
{
|
||||
// no plugin jobs are registered for this hook point, unless the plugin system provides them
|
||||
if (!_jobsByHook.TryGetValue(hookName, out IReadOnlyList<Type>? jobTypes))
|
||||
yield break;
|
||||
|
||||
foreach (Type jobType in jobTypes)
|
||||
{
|
||||
IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType);
|
||||
pluginJob.LibraryId = libraryId;
|
||||
yield return pluginJob;
|
||||
}
|
||||
}
|
||||
}
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for filtering only files that have known book formats extensions.
|
||||
/// </summary>
|
||||
internal sealed class BooksFileExtensionsFilterJob : MediaLibraryScanJob, IBooksFileExtensionsFilterJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly string[] _knownBookFileExtensions =
|
||||
[
|
||||
".pdf", ".epub", ".mobi", ".azw", ".azw3",
|
||||
".cbz", ".cbr", ".djvu", ".fb2", ".lit",
|
||||
".prc", ".txt", ".doc", ".docx", ".rtf"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileExtensionsFilterJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
if (input is List<FileInfo> payload)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started book file filtering...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
|
||||
List<FileInfo> bookFiles = new(payload.Count / 2); // pre-allocate with estimated capacity (boy, that's an optimistic view on books...)
|
||||
for (int i = 0; i < payload.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
FileInfo file = payload[i];
|
||||
|
||||
if (HasKnownBookExtension(file.Name.AsSpan()))
|
||||
bookFiles.Add(file);
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// update job progress report
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, payload.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended book file filtering in {sw.ElapsedMilliseconds}ms, filtered {bookFiles.Count} files.");
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, bookFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="filePath"/> has a known book file extension or not.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The file path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="filePath"/> contains a known book file extension, <see langword="false"/> otherwise.</returns>
|
||||
public bool HasKnownBookExtension(ReadOnlySpan<char> filePath)
|
||||
{
|
||||
// find the last dot in the path
|
||||
int lastDotIndex = filePath.LastIndexOf('.');
|
||||
|
||||
// if no dot found or it's the last character, return false
|
||||
if (lastDotIndex == -1)
|
||||
return false;
|
||||
|
||||
// get the extension part (including the dot)
|
||||
ReadOnlySpan<char> extension = filePath[lastDotIndex..];
|
||||
|
||||
// check against each known extension
|
||||
foreach (string knownExt in _knownBookFileExtensions)
|
||||
if (extension.SequenceEqual(knownExt.AsSpan()))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "FilteringBookFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering book file system items.
|
||||
/// </summary>
|
||||
internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksFileSystemDiscoveryJob
|
||||
{
|
||||
private const int STAGING_BATCH_SIZE = 1000; // the number of discovered files that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private static readonly HashSet<string> s_bookExtensions = new(
|
||||
[
|
||||
".pdf", ".epub", ".mobi", ".azw", ".azw3",
|
||||
".cbz", ".cbr", ".djvu", ".fb2", ".lit",
|
||||
".prc", ".txt", ".doc", ".docx", ".rtf"
|
||||
],
|
||||
StringComparer.OrdinalIgnoreCase
|
||||
);
|
||||
private static readonly EnumerationOptions s_enumerationOptions = new()
|
||||
{
|
||||
AttributesToSkip = FileAttributes.None, // hidden files and directories are included in the discovery
|
||||
IgnoreInaccessible = true,
|
||||
RecurseSubdirectories = false
|
||||
};
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsError ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// when the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
{
|
||||
ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsError)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// get the files for each of the media library content locations
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fingerprintsByPath is not null,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
stagingResultsRepository,
|
||||
directoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// increment the number of processed elements progress in a high-frequency counter with low overhead check
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
ErrorOr<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsError)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
ErrorOr<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsError)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers the book files of a content location of the media library, using a breadth-first traversal, and writes them in batches to the staging results.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="skipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
|
||||
/// <param name="fingerprintsByPath">The directory scan fingerprints of the library, mapped by the directory path. Can be <see langword="null"/> when the fast skip is disabled.</param>
|
||||
/// <param name="stagingBatch">The batch of discovered files that is written to the staging results when it reaches the batch size.</param>
|
||||
/// <param name="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
|
||||
/// <param name="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
|
||||
/// <param name="directoryScanFingerprintRepository">The repository used to write the directory scan fingerprints to the storage medium.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private async Task DiscoverContentLocationAsync(
|
||||
string rootDirectoryPath,
|
||||
bool skipUnchangedDirectories,
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch,
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch,
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository,
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> directoryQueue = new();
|
||||
directoryQueue.Enqueue(new DirectoryInfo(rootDirectoryPath));
|
||||
|
||||
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
|
||||
// and could result in stack overflow on deeply nested directories
|
||||
while (directoryQueue.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
DirectoryInfo currentDirectory = directoryQueue.Dequeue();
|
||||
|
||||
// when the fast skip is enabled, skip the whole subtree of a directory whose last write time has not changed since the last scan
|
||||
if (skipUnchangedDirectories)
|
||||
{
|
||||
DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc;
|
||||
if (fingerprintsByPath is not null &&
|
||||
fingerprintsByPath.TryGetValue(currentDirectory.FullName, out DirectoryScanFingerprintEntity? fingerprint) &&
|
||||
fingerprint.LastWriteTimeUtc == currentLastWriteTimeUtc)
|
||||
continue;
|
||||
|
||||
fingerprintBatch.Add(new DirectoryScanFingerprintEntity()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = LibraryId.Value,
|
||||
Path = currentDirectory.FullName,
|
||||
LastWriteTimeUtc = currentLastWriteTimeUtc
|
||||
});
|
||||
// flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has
|
||||
if (fingerprintBatch.Count >= STAGING_BATCH_SIZE)
|
||||
{
|
||||
ErrorOr<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertFingerprintsResult.IsError)
|
||||
throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description);
|
||||
fingerprintBatch.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// process the files of the current directory
|
||||
IEnumerable<FileInfo>? files = null;
|
||||
try
|
||||
{
|
||||
files = currentDirectory.EnumerateFiles("*", s_enumerationOptions)
|
||||
.Where(file => s_bookExtensions.Contains(file.Extension));
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (files is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
stagingBatch.Add(new LibraryScanStagingResultsEntity()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryScanId = ScanId.Value,
|
||||
Path = file.FullName,
|
||||
Size = file.Length,
|
||||
Ticks = file.LastWriteTimeUtc.Ticks,
|
||||
ContentHash = 0,
|
||||
PreviousContentHash = 0,
|
||||
NeedsRehash = true,
|
||||
IsNew = true
|
||||
});
|
||||
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
|
||||
{
|
||||
ErrorOr<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsError)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
stagingBatch.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// a file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// process the subdirectories - each new subdirectory is added to the same stack queue, for later processing
|
||||
IEnumerable<DirectoryInfo>? subdirectories = null;
|
||||
try
|
||||
{
|
||||
subdirectories = currentDirectory.EnumerateDirectories("*", s_enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (subdirectories is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (DirectoryInfo subdirectory in subdirectories)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
directoryQueue.Enqueue(subdirectory);
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+101
-61
@@ -1,20 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -26,21 +24,28 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Writt
|
||||
/// </summary>
|
||||
internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of media library items that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GoodReadsMetadataScrapJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -50,67 +55,76 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Console.WriteLine("started goodreads metadata");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
|
||||
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload");
|
||||
//ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
// count the media library items that need their metadata enriched, which are the items that were new or changed in this scan
|
||||
ErrorOr<int> getItemsToEnrichCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getItemsToEnrichCountResult.IsError)
|
||||
throw new InvalidOperationException(getItemsToEnrichCountResult.FirstError.Description);
|
||||
int totalItemsToEnrich = getItemsToEnrichCountResult.Value;
|
||||
|
||||
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> ints = Enumerable.Range(0, 20).ToList();
|
||||
foreach (int nr in ints)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
// increment the number of processed elements progress
|
||||
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
|
||||
nr, 20, "GoodReadsMetadataDownload");
|
||||
//scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedItemsCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// process the media library items that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
|
||||
while (true)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<IReadOnlyList<HashedFileSystemFile>> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getItemsToEnrichPageResult.IsError)
|
||||
throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> itemsToEnrichPage = getItemsToEnrichPageResult.Value;
|
||||
if (itemsToEnrichPage.Count == 0)
|
||||
break;
|
||||
|
||||
// TODO: retrieve the metadata of each media library item from GoodReads, and store it, once the real scraping is implemented
|
||||
foreach (HashedFileSystemFile item in itemsToEnrichPage)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedItemsCount), totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
lastPath = itemsToEnrichPage[^1].Path;
|
||||
}
|
||||
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
Console.WriteLine("ended goodreads metadata");
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
@@ -118,5 +132,31 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user