Adds media library scan progress tracking

This commit is contained in:
BinaryAlley committed 2025-02-18 17:24:39 +02:00
1 parent e8dbf9456c
commit 27fa8e2e4f
87 files changed
+2078 -421

No files matched your search

@@ -5,10 +5,18 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Core.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
using Microsoft.Extensions.DependencyInjection;
@@ -46,6 +54,17 @@ public static class InfrastructureLayerServices
services.AddScoped<IOver18Policy, Over18Policy>();
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
services.AddScoped<IAuthorizationService, AuthorizationService>();
// media library scanning
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
services.AddTransient<IFileSystemDiscoveryJob, FileSystemDiscoveryJob>();
services.AddTransient<IRepositoryMetadataDiscoveryJob, RepositoryMetadataDiscoveryJob>();
services.AddTransient<IHashComparerJob, HashComparerJob>();
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
return services;
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Collections.Concurrent;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
/// <summary>
/// Tracker used for canceling in-memory media library scans.
/// </summary>
internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable
{
private readonly ConcurrentDictionary<MediaLibraryScanCompositeId, CancellationTokenSource> _runningScans = new();
private bool _disposed;
/// <summary>
/// Registers a new scan operation for tracking.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
public void RegisterScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId)
{
_runningScans.TryAdd(mediaLibraryScanCompositeId, new CancellationTokenSource());
}
/// <summary>
/// Removes a scan operation from tracking.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
public void RemoveScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId)
{
if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan))
{
scan.Cancel();
// remove and dispose after cancellation
if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan))
removedScan?.Dispose();
}
}
/// <summary>
/// Gets the cancellation token for a scan identified by <paramref name="mediaLibraryScanCompositeId"/>.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
/// <returns>A cancellation token for the specified scan.</returns>
public CancellationToken GetTokenForScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId)
{
return _runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan)
? scan.Token
: CancellationToken.None;
}
/// <summary>
/// Cancels a scan identified by <paramref name="mediaLibraryScanCompositeId"/>.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">Model for tracking media library scans.</param>
public void CancelScan(MediaLibraryScanCompositeId mediaLibraryScanCompositeId)
{
if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan))
{
scan.Cancel();
// remove and dispose after cancellation
if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan))
removedScan?.Dispose();
}
}
/// <summary>
/// Disposes the tracker and cancels all media library scans.
/// </summary>
public void Dispose()
{
if (!_disposed)
{
foreach (CancellationTokenSource scan in _runningScans.Values)
{
scan.Cancel();
scan.Dispose();
}
_runningScans.Clear();
_disposed = true;
}
}
}
@@ -0,0 +1,210 @@
#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.FileSystem;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads;
using 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 discovering file system items.
/// </summary>
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
{
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
/// <param name="fileService">Injected service for handling files.</param>
/// <param name="serviceScopeFactory">
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
/// </param>
public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService, IServiceScopeFactory serviceScopeFactory)
{
_directoryService = directoryService;
_fileService = fileService;
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == 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;
await Task.Delay(25000);
Console.WriteLine("started file discovering");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
// 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(), ScanId, LibraryId, 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(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
await Task.Delay(5000);
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken);
if (treeResult.IsError)
{
// handle errors, maybe:
// Status = LibraryScanJobStatus.Failed;
}
else
contentLocationTrees.Add(treeResult.Value);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended file discovering");
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
/// <summary>
/// Builds a hierarchical tree structure representing the file system starting from the specified path.
/// </summary>
/// <param name="path">The identifier of the root path from which to build the tree.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the tree.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default)
{
// validate the path and get the root directory node
ErrorOr<Directory> rootDirectoryResult = Directory.Create(path, path.Path, Optional<DateTime>.None(), Optional<DateTime>.None());
if (rootDirectoryResult.IsError)
return rootDirectoryResult.Errors;
// build the tree starting from the root directory
return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements, cancellationToken);
}
/// <summary>
/// Recursively builds a tree node for a given directory, including its subdirectories and files.
/// </summary>
/// <param name="directory">The directory for which to build a tree node.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the node's children.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildNodeRecursive(Directory directory, bool includeHiddenElements, CancellationToken cancellationToken)
{
FileSystemTreeNode node = new()
{
Path = directory.Id.Path,
Name = directory.Name,
ItemType = FileSystemItemType.Directory,
Children = []
};
// fetch and add subdirectories
ErrorOr<IEnumerable<Directory>> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements);
if (subdirectoriesResult.IsError)
return subdirectoriesResult.Errors;
foreach (Directory subdirectory in subdirectoriesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements, cancellationToken);
if (subNodeResult.IsError)
return subNodeResult.Errors;
node.Children.Add(subNodeResult.Value);
}
// fetch and add files
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(directory.Id, includeHiddenElements);
if (filesResult.IsError)
return filesResult.Errors;
foreach (File file in filesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
node.Children.Add(new FileSystemTreeNode
{
Path = file.Id.Path,
Name = file.Name,
ItemType = FileSystemItemType.File,
Children = [] // files have no children
});
}
return node;
}
}
@@ -0,0 +1,115 @@
#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 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 comparing hashes.
/// </summary>
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <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
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
Console.WriteLine("started file hashing");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
// 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(), ScanId, LibraryId, 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(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended file hashing");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
}
@@ -0,0 +1,118 @@
#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 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 retrieving persistence data from any eventual previous scans.
/// </summary>
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryMetadataDiscoveryJob"/> 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 RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == 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;
Console.WriteLine("started repo discovering");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
// 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(), ScanId, LibraryId, 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(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended repo discovering");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
}
@@ -0,0 +1,116 @@
#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 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 persisting data of the current scan. This should always be the last job in the directed acyclic job graph.
/// </summary>
internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryMetadataSaveJob"/> 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 RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == 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;
Console.WriteLine("started repo saving");
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
// 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(), ScanId, LibraryId, 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(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
await publisher!.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended repo saving");
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
}, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads;
/// <summary>
/// Generic file system node.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class FileSystemTreeNode
{
/// <summary>
/// Gets or sets the full path of the file or directory.
/// </summary>
public string Path { get; set; } = null!;
/// <summary>
/// Gets or sets the name of the file or directory.
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the type of the item, indicating whether it is a file, directory, or drive.
/// </summary>
public FileSystemItemType ItemType { get; set; }
/// <summary>
/// Gets or sets the list of child nodes.
/// </summary>
public List<FileSystemTreeNode> Children { get; set; } = [];
}
@@ -0,0 +1,116 @@
#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.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
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.WrittenContent.Books;
/// <summary>
/// Media library scan job for retrieving written content metadata from GoodReads.
/// </summary>
internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
{
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.
/// </param>
public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == 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>();
// 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(), ScanId, LibraryId, 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(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsDownload");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended goodreads metadata");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using System.Threading.Channels;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
/// <summary>
/// Provides an in-memory message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
{
private readonly Channel<IMediaLibraryScanJob> _channel = Channel.CreateUnbounded<IMediaLibraryScanJob>();
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
public ChannelWriter<IMediaLibraryScanJob> Writer => _channel.Writer;
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
public ChannelReader<IMediaLibraryScanJob> Reader => _channel.Reader;
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
/// <summary>
/// Background service for processing media library scan jobs from an in-memory message queue.
/// </summary>
internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService
{
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJob"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker)
{
_mediaScanQueue = mediaScanQueue;
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
}
/// <summary>
/// Method called when the background service starts.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// continuously processes and executes media library scan jobs from the queue until the application shuts down
// remark: since only top level scan jobs are placed on the bus, but they themselves trigger the execution of their children jobs, and so on,
// their completion should not be awaited here due to some of them being long running tasks; therefor they are just fired synchronously
// without being awaited, while still properly handling any exceptions they might throw in their asynchronous execution
await foreach (IMediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
// get the cancellation token that was associated with this library scan
CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(MediaLibraryScanCompositeId.Create(mediaScanJob.ScanId, mediaScanJob.UserId));
// create linked token to handle both scan cancellation and service shutdown
CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, scanToken);
mediaScanJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).FireAndForgetSafeAsync(() => linkedSource.Dispose());
}
}
}