mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 09:11:10 +00:00
Integrates the plugin system into the host and the media library scan pipeline
This commit is contained in:
1 parent
f71e72a948
commit
6f501a51f3
45 files changed
+1268
-370
No files matched your search
+262
@@ -0,0 +1,262 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for enriching the metadata of the media library items, using the metadata providers configured for the media library.
|
||||
/// This should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanMetadataEnrichmentJob"/> 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>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while enriching the metadata.</param>
|
||||
public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanMetadataEnrichmentJob> logger)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <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>()!;
|
||||
ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
|
||||
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the metadata providers configured for the media library, in their configured order, that support the media library type
|
||||
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsError)
|
||||
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
|
||||
List<IRemoteMetadataProvider> providers = [];
|
||||
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
|
||||
{
|
||||
List<IRemoteMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IRemoteMetadataProvider>(configuration.PluginId)
|
||||
.Where(provider => provider.SupportedLibraryType == LibraryType.Book)];
|
||||
if (configuredProviders.Count == 0)
|
||||
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
|
||||
providers.AddRange(configuredProviders);
|
||||
}
|
||||
|
||||
// count the books that need their metadata enriched, for progress reporting purposes
|
||||
ErrorOr<int> getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksToEnrichCountResult.IsError)
|
||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedBooksCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<IReadOnlyList<BookEntity>> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksPageResult.IsError)
|
||||
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
||||
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
|
||||
if (booksPage.Count == 0)
|
||||
break;
|
||||
|
||||
foreach (BookEntity bookEntity in booksPage)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await EnrichBookAsync(bookEntity, providers, bookRepository, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// 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 processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
lastPath = booksPage[^1].Path;
|
||||
}
|
||||
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// this job finished, and it's the last in the chain, the scan is completed
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// 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>
|
||||
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided <paramref name="providers"/> in their configured order.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose metadata is enriched.</param>
|
||||
/// <param name="providers">The metadata providers, in their configured order.</param>
|
||||
/// <param name="bookRepository">The repository used to persist the enriched metadata.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IRemoteMetadataProvider> providers, IBookRepository bookRepository, CancellationToken cancellationToken)
|
||||
{
|
||||
// convert the book to a domain object
|
||||
ErrorOr<Book> getBookResult = bookEntity.ToDomainEntity();
|
||||
if (getBookResult.IsError)
|
||||
return;
|
||||
Book book = getBookResult.Value;
|
||||
|
||||
BookMetadataLookupDto lookup = new(
|
||||
LibraryId: bookEntity.LibraryId,
|
||||
Path: bookEntity.Path,
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results
|
||||
OpenLibraryId: bookEntity.OpenLibraryId,
|
||||
Title: bookEntity.Title,
|
||||
Author: null,
|
||||
LanguageCode: bookEntity.LanguageCode
|
||||
);
|
||||
|
||||
// try the metadata providers in order, until one returns usable metadata
|
||||
foreach (IRemoteMetadataProvider provider in providers)
|
||||
{
|
||||
try
|
||||
{
|
||||
MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
|
||||
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
|
||||
continue;
|
||||
|
||||
ErrorOr<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
|
||||
if (applyMetadataResult.IsError)
|
||||
continue;
|
||||
|
||||
ErrorOr<Updated> updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateBookResult.IsError)
|
||||
continue;
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// a failing metadata provider must not prevent the other providers from being tried
|
||||
}
|
||||
}
|
||||
|
||||
// no metadata provider returned usable metadata, mark the book as failed to enrich
|
||||
book.MarkMetadataAsFailed();
|
||||
await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided <paramref name="metadata"/> is usable, meaning it has a title and at least one primary identifier.
|
||||
/// </summary>
|
||||
/// <param name="metadata">The metadata to validate.</param>
|
||||
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsUsableMetadata(BookMetadataDto metadata)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(metadata.Title))
|
||||
return false;
|
||||
return !string.IsNullOrWhiteSpace(metadata.GoodreadsId)
|
||||
|| !string.IsNullOrWhiteSpace(metadata.OpenLibraryId)
|
||||
|| !string.IsNullOrWhiteSpace(metadata.GoogleBooksId)
|
||||
|| !string.IsNullOrWhiteSpace(metadata.ASIN)
|
||||
|| (metadata.Isbns is not null && metadata.Isbns.Count > 0);
|
||||
}
|
||||
|
||||
/// <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, "EnrichingMetadata");
|
||||
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;
|
||||
}
|
||||
}
|
||||
+69
-4
@@ -1,8 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.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;
|
||||
@@ -10,6 +13,9 @@ using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -86,15 +92,40 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
|
||||
ErrorOr<IReadOnlyList<string>> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsError)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
|
||||
foreach (string path in getPathsResult.Value)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<BookEntity?> getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
|
||||
if (getExistingBookResult.IsError)
|
||||
throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
|
||||
if (getExistingBookResult.Value is not null)
|
||||
continue;
|
||||
|
||||
ErrorOr<Created> insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
|
||||
if (insertBookResult.IsError)
|
||||
throw new InvalidOperationException(insertBookResult.FirstError.Description);
|
||||
}
|
||||
await unitOfWork.SaveChangesAsync(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);
|
||||
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
|
||||
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
|
||||
if (Children.Count == 0)
|
||||
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -129,4 +160,38 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a shell book entity for the file stored at <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>,
|
||||
/// with a title derived from the file name, and no web metadata yet.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <returns>The created shell book entity.</returns>
|
||||
private static BookEntity CreateShellBookEntity(Guid libraryId, string path)
|
||||
{
|
||||
return new BookEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = path,
|
||||
Title = GetTitleFromPath(path),
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Derives a book title from the file name of the provided <paramref name="path"/>, by removing the extension and replacing separators with spaces.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <returns>The derived title.</returns>
|
||||
private static string GetTitleFromPath(string path)
|
||||
{
|
||||
string fileName = Path.GetFileNameWithoutExtension(path);
|
||||
string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim();
|
||||
return title.Length > 0 ? title : fileName;
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
#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.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 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.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 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/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public GoodReadsMetadataScrapJob(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>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// 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;
|
||||
|
||||
// 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);
|
||||
|
||||
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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// 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, "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;
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -4,7 +4,7 @@ using ErrorOr;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
@@ -79,7 +79,8 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
|
||||
if (!progressResult.IsError)
|
||||
{
|
||||
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
|
||||
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanFinishedEvent", progress, cancellationToken).ConfigureAwait(false);
|
||||
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(
|
||||
"libraryScanFinishedEvent", progress with { Status = LibraryScanJobStatus.Completed.ToString() }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user