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

@@ -10,4 +10,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Command for initiating the scan of all media libraries.
/// </summary>
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<ScanLibraryResponse>>>;
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<MediaLibraryScanResponse>>>;
@@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Handler for the command for initiating the scan of all media libraries.
/// </summary>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<ScanLibraryResponse>>>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -57,7 +57,7 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
/// <param name="request">The request to be handled.</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>
public async ValueTask<ErrorOr<IEnumerable<ScanLibraryResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -74,7 +74,7 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value);
List<ScanLibraryResponse> responses = [];
List<MediaLibraryScanResponse> responses = [];
List<IDomainEvent> domainEvents = [];
// for each library, start the scan
@@ -118,7 +118,7 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
// collect all the domain events created during this library scan start
domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents());
responses.Add(new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value));
responses.Add(new MediaLibraryScanResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value));
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -13,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <param name="Id">The unique identifier of the library to scan.</param>
public record ScanLibraryCommand(
Guid Id
) : IRequest<ErrorOr<ScanLibraryResponse>>;
) : IRequest<ErrorOr<MediaLibraryScanResponse>>;
@@ -28,7 +28,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <summary>
/// Handler for the command for initiating the scan of a media library.
/// </summary>
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<ScanLibraryResponse>>
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -60,7 +60,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
/// <param name="request">The request to be handled.</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>
public async ValueTask<ErrorOr<ScanLibraryResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
public async ValueTask<ErrorOr<MediaLibraryScanResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -125,6 +125,6 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value);
return new MediaLibraryScanResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value);
}
}
@@ -54,7 +54,7 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryS
// mark the media library scan as failed
ErrorOr<Success> failScanResult = libraryScanDomainResult.Value.FailScan();
// we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs might trigger this domain event,
// we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event,
// trying to set as failed a scan that has already been marked as failed by a concurrent job
if (!failScanResult.IsError)
{
@@ -0,0 +1,83 @@
#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.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan is finished.
/// </summary>
public class LibraryScanFinishedDomainEventHandler : INotificationHandler<LibraryScanFinishedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanFinishedDomainEventHandler"/> class.
/// </summary>
/// <param name="mediaLibrariesScanProgressTracker">Injected service for tracking the progress of media library scans.</param>
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public LibraryScanFinishedDomainEventHandler(
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
IUnitOfWork unitOfWork)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the event raised when a media library scan is finished.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask Handle(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan from the repository
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryScansResult.IsError)
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
if (getLibraryScansResult.Value is null)
throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound);
// convert the repository scan to a domain object
ErrorOr<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
if (libraryScanDomainResult.IsError)
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
// mark the media library scan as finished
ErrorOr<Success> finishScanResult = libraryScanDomainResult.Value.FinishScan();
if (finishScanResult.IsError)
throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors);
// update the library scan in the repository
ErrorOr<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryScanResult.IsError)
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// mark the scan progress as completed, and remove its cancellation tracking
_mediaLibrariesScanProgressTracker.UpdateScanProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId));
_mediaLibrariesScanCancellationTracker.RemoveScan(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId));
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library's scan progress changes.
/// </summary>
public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHandler<LibraryScanJobProgressChangedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanJobProgressChangedDomainEventHandler"/> class.
/// </summary>
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
public LibraryScanJobProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
}
/// <summary>
/// Handles the event raised when a media library's scan progress changes.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
{
_mediaLibrariesScanProgressTracker.UpdateScanJobProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId), domainEvent.Progress);
await Task.CompletedTask;
}
}
@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
@@ -12,6 +14,17 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// </summary>
public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler<LibraryScanProgressChangedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanProgressChangedDomainEventHandler"/> class.
/// </summary>
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
public LibraryScanProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
}
/// <summary>
/// Handles the event raised when a media library's scan progress changes.
/// </summary>
@@ -19,6 +32,7 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
{
_mediaLibrariesScanProgressTracker.UpdateScanProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId));
await Task.CompletedTask;
}
}
@@ -62,8 +62,7 @@ public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<L
// if the user that requested the library is not an Admin or is not the owner of the library, they do not have the right to view it
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken)))
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
return getLibraryResult.Value.ToResponse();
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress;
/// <summary>
/// Query for getting the progress of a media library scan.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose scan progress is requested.</param>
/// <param name="ScanId">The Id of the media library scan whose progress is requested.</param>
public record GetLibraryScanProgressQuery(
Guid LibraryId,
Guid ScanId
) : IRequest<ErrorOr<MediaLibraryScanProgressResponse>>;
@@ -0,0 +1,82 @@
#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.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress;
/// <summary>
/// Handler for the query to get the progress of a library scan.
/// </summary>
public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScanProgressQuery, ErrorOr<MediaLibraryScanProgressResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryScanProgressQueryHandler"/> class.
/// </summary>
/// <param name="mediaLibrariesScanProgressTracker">Injected service for tracking the progress of media library scans.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetLibraryScanProgressQueryHandler(
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get the progress of a library scan.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="MediaLibraryScanProgressResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<MediaLibraryScanProgressResponse>> Handle(GetLibraryScanProgressQuery request, CancellationToken cancellationToken)
{
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to view its scan progress
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
ErrorOr<MediaLibraryScanProgress> getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
MediaLibraryScanCompositeId.Create(ScanId.Create(request.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
if (getProgressResult.IsError)
return getProgressResult.Errors;
return getProgressResult.Value.ToResponse();
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress;
/// <summary>
/// Validates the needed validation rules for <see cref="GetLibraryScanProgressQuery"/>.
/// </summary>
public class GetLibraryScanProgressQueryValidator : AbstractValidator<GetLibraryScanProgressQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryScanProgressQueryValidator"/> class.
/// </summary>
public GetLibraryScanProgressQueryValidator()
{
RuleFor(x => x.ScanId)
.NotEmpty().WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description);
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
}
}
@@ -1,101 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.Scanning;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using System;
using System.Collections.Concurrent;
using System.Threading;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation;
/// <summary>
/// Tracker used for canceling in-memory media library scans.
/// </summary>
internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable
{
private readonly ConcurrentDictionary<MediaScanTrackerModel, CancellationTokenSource> _runningScans = new();
private bool _disposed;
/// <summary>
/// Registers a new scan operation for tracking.
/// </summary>
/// <param name="scanId">The unique identifier of the scan operation to track.</param>
/// <param name="userId">The unique identifier of the user who initiated the scan to track.</param>
public void RegisterScan(Guid scanId, Guid userId)
{
_runningScans.TryAdd(new MediaScanTrackerModel(scanId, userId), new CancellationTokenSource());
}
/// <summary>
/// Gets the cancellation token for a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The unique identifier of the scan to get the cancellation token for<./param>
/// <param name="userId">The unique identifier of the user who initiated the scan for which to get the cancellation token.</param>
/// <returns>A cancellation token for the specified scan.</returns>
public CancellationToken GetTokenForScan(Guid scanId, Guid userId)
{
return _runningScans.TryGetValue(new MediaScanTrackerModel(scanId, userId), out CancellationTokenSource? scan)
? scan.Token
: CancellationToken.None;
}
/// <summary>
/// Cancels a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The unique identifier of the scan operation to cancel.</param>
/// <param name="userId">The unique identifier of the user requesting the cancellation.</param>
public void CancelScan(Guid scanId, Guid userId)
{
foreach (MediaScanTrackerModel key in _runningScans.Keys)
{
if (key.ScanId == scanId && key.UserId == userId)
{
if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan))
{
scan.Cancel();
// remove and dispose after cancellation
if (_runningScans.TryRemove(key, out CancellationTokenSource? removedScan))
removedScan?.Dispose();
}
}
}
}
/// <summary>
/// Cancels all active scan operations for a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The unique identifier of the user whose scans should be canceled.</param>
public void CancelUserScans(Guid userId)
{
foreach (MediaScanTrackerModel key in _runningScans.Keys)
{
if (key.UserId == userId)
{
if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan))
{
scan.Cancel();
// remove and dispose after cancellation
if (_runningScans.TryRemove(key, 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;
}
}
}
@@ -1,204 +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.DomainEvents;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads;
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 Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.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)
{
Status = LibraryScanJobStatus.Running;
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<ScanJobProgress> scanJobProgressResult = ScanJobProgress.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;
}
_jobProgress = scanJobProgressResult.Value;
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine($"Reporting job progress in file discovery. Total: {_jobProgress.TotalItems}; Completed: {_jobProgress.CompletedItems}; Current: {_jobProgress.CurrentOperation}");
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
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 = ScanJobProgress.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 LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, 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);
}
}
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;
}
}
@@ -1,48 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for comparing hashes.
/// </summary>
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
{
/// <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");
List<int> ints = [1, 2, 3];
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(1111, cancellationToken).ConfigureAwait(false);
Console.WriteLine("ticking");
cancellationToken.ThrowIfCancellationRequested();
}
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;
}
}
}
@@ -1,42 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for retrieving persistence data from any eventual previous scans.
/// </summary>
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
{
/// <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 repo discovering");
List<int> ints = [1, 2, 3];
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);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
}
}
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.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; } = [];
}
@@ -1,43 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Media library scan job for retrieving written content metadata from GoodReads.
/// </summary>
internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
{
/// <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");
List<int> ints = [1, 2, 3];
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;
}
}
}
@@ -1,30 +0,0 @@
#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>(new UnboundedChannelOptions
{
SingleWriter = false,
SingleReader = false,
AllowSynchronousContinuations = true
});
/// <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;
}
@@ -1,52 +0,0 @@
#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 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 service for scanning media libraries.</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(mediaScanJob.ScanId.Value, mediaScanJob.UserId.Value);
// 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());
}
}
}