Integrates the plugin system into the host and the media library scan pipeline

This commit is contained in:
BinaryAlley committed 2026-08-12 11:04:45 -07:00
1 parent f71e72a948
commit 6f501a51f3
45 files changed
+1268 -370

No files matched your search

@@ -0,0 +1,47 @@
# Architecture Decision Record (ADR): 0010 - Failure Semantics of the Best-Effort Metadata Enrichment Job
## Status
**Accepted** (2026-08-09)
## Context
ADR-0009 established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed.
The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed.
## Decision
The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of ADR-0009:
- Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed.
- Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order.
- The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan.
- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of ADR-0009. In that case the file state is already committed, and a re-scan retries the enrichment.
The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Partial enrichment | Books successfully enriched before a crash stay browsable and enriched |
| Provider isolation | A crashing provider does not prevent other providers from being tried |
| Scan completion | The scan reaches a completed state regardless of enrichment outcome |
| Retryability | Books with `MetadataStatus.Failed` or `Pending` are re-enriched on the next scan |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Host failures still fail | Only host-side storage errors fail the scan; re-scan retries enrichment |
| No per-provider audit trail | Books record the failed status; per-provider error detail is a future refinement |
## Alternatives Considered
### 1. Fail the scan on any enrichment failure
Keep ADR-0009 semantics for the enrichment job.
**Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome.
### 2. Run enrichment outside the scan lifetime
Enrich the books asynchronously after the scan, decoupled from the scan progress and cancellation.
**Rejected**: This contradicts the decision that the metadata enrichment phase is part of the scan lifetime, covered by the scan progress reporting and cancellation machinery, so that the scan progress reaches completion only when the metadata is downloaded.
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Common.Infrastructure.Plugins;
/// <summary>
/// Manager of the plugins loaded by the host application.
/// </summary>
public interface IPluginManager
{
/// <summary>
/// Gets the plugins that were loaded successfully.
/// </summary>
/// <returns>The collection of loaded plugins.</returns>
IReadOnlyList<IPlugin> GetPlugins();
/// <summary>
/// Gets the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The unique identifier of the plugin.</param>
/// <returns>The plugin, or <see langword="null"/> when no plugin with the provided Id was loaded.</returns>
IPlugin? GetPlugin(Guid pluginId);
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for applying <see cref="BookMetadataDto"/> to <see cref="Book"/>.
/// </summary>
public static class BookMetadataDtoMapping
{
/// <summary>
/// Applies the metadata of <paramref name="metadata"/> to <paramref name="book"/>, marking its metadata as enriched by the provided <paramref name="providerName"/>.
/// </summary>
/// <param name="book">The domain book to which the metadata is applied.</param>
/// <param name="metadata">The metadata to be applied.</param>
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
/// <param name="lastUpdateUtc">The date and time when the metadata was enriched.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public static ErrorOr<Success> ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc)
{
if (string.IsNullOrWhiteSpace(metadata.Title))
return Domain.SharedKernel.Common.Errors.Errors.Metadata.TitleCannotBeEmpty;
if (metadata.ReleaseInfo is null)
return Domain.SharedKernel.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull;
ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate),
Optional<int>.FromNullable(metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
List<ErrorOr<Genre>> domainGenresResult = metadata.Genres is not null
? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name))]
: [];
List<Error> genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)];
if (genresErrors.Count != 0)
return genresErrors;
List<ErrorOr<Tag>> domainTagsResult = metadata.Tags is not null
? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name))]
: [];
List<Error> tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)];
if (tagsErrors.Count != 0)
return tagsErrors;
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
if (metadata.Language is not null)
{
ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional<string>.FromNullable(metadata.Language.NativeName));
if (languageInfoResult.IsError)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
Optional<LanguageInfo> originalLanguageInfo = Optional<LanguageInfo>.None();
if (metadata.OriginalLanguage is not null)
{
ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsError)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
ErrorOr<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
metadata.Title,
Optional<string>.FromNullable(metadata.OriginalTitle),
Optional<string>.FromNullable(metadata.Description),
releaseInfoResult.Value,
[.. domainGenresResult.Select(genreResult => genreResult.Value)],
[.. domainTagsResult.Select(tagResult => tagResult.Value)],
languageInfo,
originalLanguageInfo,
Optional<string>.FromNullable(metadata.Publisher),
Optional<int>.FromNullable(metadata.PageCount)
);
if (writtenContentMetadataResult.IsError)
return writtenContentMetadataResult.Errors;
List<ErrorOr<Isbn>> domainIsbnsResult = metadata.Isbns is not null
? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format!.Value))]
: [];
List<Error> isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)];
if (isbnsErrors.Count != 0)
return isbnsErrors;
List<ErrorOr<BookRating>> domainRatingsResult = metadata.Ratings is not null
? [.. metadata.Ratings.Where(rating => rating.Value is not null && rating.MaxValue is not null).Select(rating => BookRating.Create(
rating.Value!.Value,
rating.MaxValue!.Value,
Optional<BookRatingSource>.FromNullable((BookRatingSource?)(rating.Source is null ? null : (BookRatingSource)(int)rating.Source.Value)),
Optional<int>.FromNullable(rating.VoteCount)
))]
: [];
List<Error> ratingsErrors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors)];
if (ratingsErrors.Count != 0)
return ratingsErrors;
book.ApplyEnrichedMetadata(
writtenContentMetadataResult.Value,
Optional<BookFormat>.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null),
Optional<string>.FromNullable(metadata.Edition),
Optional<int>.FromNullable(metadata.VolumeNumber),
Optional<BookSeries>.None(),
Optional<string>.FromNullable(metadata.ASIN),
Optional<string>.FromNullable(metadata.GoodreadsId),
Optional<string>.FromNullable(metadata.LCCN),
Optional<string>.FromNullable(metadata.OCLCNumber),
Optional<string>.FromNullable(metadata.OpenLibraryId),
Optional<string>.FromNullable(metadata.LibraryThingId),
Optional<string>.FromNullable(metadata.GoogleBooksId),
Optional<string>.FromNullable(metadata.BarnesAndNobleId),
Optional<string>.FromNullable(metadata.AppleBooksId),
[.. domainIsbnsResult.Select(isbnResult => isbnResult.Value)],
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
providerName,
lastUpdateUtc
);
return Result.Success;
}
}
@@ -16,6 +16,7 @@
<ItemGroup>
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Domain\Lumina.Domain.csproj" />
<ProjectReference Include="..\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,6 @@
namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Base type for all metadata returned by a metadata provider.
/// </summary>
public abstract record MetadataDto;
@@ -0,0 +1,6 @@
namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Base type for all metadata lookups used to search for media items.
/// </summary>
public abstract record MetadataLookupDto;
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Data transfer object for the metadata of a book returned by a metadata provider.
/// </summary>
public sealed record BookMetadataDto(
string? Title,
string? OriginalTitle,
string? Description,
ReleaseInfoDto? ReleaseInfo,
List<GenreDto>? Genres,
List<TagDto>? Tags,
LanguageInfoDto? Language,
LanguageInfoDto? OriginalLanguage,
string? Publisher,
int? PageCount,
BookFormat? Format,
string? Edition,
int? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
string? LCCN,
string? OCLCNumber,
string? OpenLibraryId,
string? LibraryThingId,
string? GoogleBooksId,
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? Isbns,
List<MediaContributorDto>? Contributors,
List<BookRatingDto>? Ratings,
string? CoverImageUrl
) : MetadataDto;
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Data transfer object for a book metadata lookup.
/// </summary>
public sealed record BookMetadataLookupDto(
Guid LibraryId,
string Path,
string? Isbn = null,
string? OpenLibraryId = null,
string? Title = null,
string? Author = null,
string? LanguageCode = null
//string? Title,
//string? OriginalTitle,
//int? ReleaseYear,
//string? LanguageCode,
//IReadOnlyList<string>? Isbns,
//string? GoodreadsId,
//string? OpenLibraryId,
//string? GoogleBooksId
) : MetadataLookupDto;
@@ -1,21 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
/// <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>
public interface IScanJobRegistry
{
/// <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>
IEnumerable<IMediaLibraryScanJob> GetJobsForHook(string hookName, LibraryId libraryId);
}
@@ -1,32 +0,0 @@
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
/// <summary>
/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected.
/// </summary>
public static class ScanJobHooks
{
/// <summary>
/// The hook that runs after the file system discovery job, and before the scan diff job.
/// </summary>
public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery";
/// <summary>
/// The hook that runs after the scan diff job, and before the scan hash job.
/// </summary>
public const string AFTER_SCAN_DIFF = "AfterScanDiff";
/// <summary>
/// The hook that runs after the scan hash job, and before any metadata enrichment jobs.
/// </summary>
public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment";
/// <summary>
/// The hook that runs after any metadata enrichment jobs, and before the scan results save job.
/// </summary>
public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment";
/// <summary>
/// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph.
/// </summary>
public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave";
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for enriching the metadata of the media library items.
/// </summary>
public interface IMediaLibraryScanMetadataEnrichmentJob : IMediaLibraryScanJob
{
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System.Collections.Generic;
@@ -15,7 +15,7 @@ public interface IMediaTypeScanner
/// <summary>
/// The media library type that this media library scanner supports.
/// </summary>
LibraryType SupportedType { get; }
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Creates the media library scan jobs for the provided media library.
@@ -1,13 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for retrieving written content metadata from GoodReads.
/// </summary>
public interface IGoodReadsMetadataScrapJob : IMediaLibraryScanJob
{
}
@@ -1,9 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
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 Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
@@ -15,22 +14,19 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
{
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
private readonly IScanJobRegistry _scanJobRegistry;
/// <summary>
/// The media library type that this media library scanner supports.
/// </summary>
public LibraryType SupportedType { get; } = LibraryType.Book;
public LibraryType SupportedLibraryType { get; } = LibraryType.Book;
/// <summary>
/// Initializes a new instance of the <see cref="BookLibraryTypeScanner"/> class.
/// </summary>
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
/// <param name="scanJobRegistry">Injected registry of the media library scan jobs injected by plugins at the defined hook points.</param>
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry)
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
{
_mediaScanJobFactory = mediaScanJobFactory;
_scanJobRegistry = scanJobRegistry;
}
/// <summary>
@@ -45,51 +41,28 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<IGoodReadsMetadataScrapJob>(libraryId);
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
// establish the hierarchical relationships between jobs, splicing the plugin jobs at the defined hook points
IMediaLibraryScanJob previousJob = fileSystemDiscoveryJob;
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_FILE_SYSTEM_DISCOVERY, libraryId);
previousJob.AddChild(mediaLibraryScanDiffJob);
mediaLibraryScanDiffJob.AddParent(previousJob);
// establish the hierarchical relationships between jobs
fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
previousJob = SpliceJobsAtHook(mediaLibraryScanDiffJob, ScanJobHooks.AFTER_SCAN_DIFF, libraryId);
previousJob.AddChild(mediaLibraryScanHashJob);
mediaLibraryScanHashJob.AddParent(previousJob);
mediaLibraryScanDiffJob.AddChild(mediaLibraryScanHashJob);
mediaLibraryScanHashJob.AddParent(mediaLibraryScanDiffJob);
previousJob = SpliceJobsAtHook(mediaLibraryScanHashJob, ScanJobHooks.BEFORE_METADATA_ENRICHMENT, libraryId);
mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob);
// when the library permits downloading data from the web, the metadata enrichment job is the last job in the directed acyclic job graph,
// running after the scan results save job, so that the books are materialized before their metadata is enriched
if (downloadMetadataFromWeb)
{
previousJob.AddChild(goodReadsMetadataScrapJob);
goodReadsMetadataScrapJob.AddParent(previousJob);
previousJob = goodReadsMetadataScrapJob;
IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob);
}
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_METADATA_ENRICHMENT, libraryId);
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.BEFORE_SCAN_RESULTS_SAVE, libraryId);
previousJob.AddChild(mediaLibraryScanResultsSaveJob);
mediaLibraryScanResultsSaveJob.AddParent(previousJob);
// return the top level jobs that will be triggered when the scan will be started
yield return fileSystemDiscoveryJob;
}
/// <summary>
/// Splices the plugin jobs registered at the provided <paramref name="hookName"/> after the <paramref name="previousJob"/>, and returns the last job of the extended chain.
/// </summary>
/// <param name="previousJob">The job after which the plugin jobs are spliced.</param>
/// <param name="hookName">The name of the hook point at which the plugin jobs are injected.</param>
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
/// <returns>The last job of the extended chain, which can be used as the parent for the next job.</returns>
private IMediaLibraryScanJob SpliceJobsAtHook(IMediaLibraryScanJob previousJob, string hookName, LibraryId libraryId)
{
IMediaLibraryScanJob currentJob = previousJob;
foreach (IMediaLibraryScanJob pluginJob in _scanJobRegistry.GetJobsForHook(hookName, libraryId))
{
currentJob.AddChild(pluginJob);
pluginJob.AddParent(currentJob);
currentJob = pluginJob;
}
return currentJob;
}
}
@@ -4,11 +4,12 @@ using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
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;
@@ -18,17 +19,21 @@ 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;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
#endregion
@@ -44,8 +49,9 @@ public static class InfrastructureLayerServices
/// Extension method for adding the Infrastructure layer services to the DI container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">The configuration manager used to read the application configuration.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services)
public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration)
{
// scan the current assembly for validators and add them to the DI container
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
@@ -70,16 +76,29 @@ public static class InfrastructureLayerServices
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
services.AddSingleton<IScanJobRegistry>(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary<string, IReadOnlyList<Type>>()));
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
services.AddTransient<IMediaLibraryScanMetadataEnrichmentJob, MediaLibraryScanMetadataEnrichmentJob>();
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
// plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager
string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins";
string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting);
PluginLoadResult pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services);
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins));
services.AddScoped<IPluginSettingsStore, PluginSettingsStore>();
services.AddSingleton(serviceProvider => new PluginDetectionSyncJob(
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
serviceProvider.GetRequiredService<IPluginManager>(),
pluginLoadResult.Errors,
serviceProvider.GetRequiredService<ILogger<PluginDetectionSyncJob>>()));
services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<PluginDetectionSyncJob>());
return services;
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -35,33 +35,38 @@ public static class SharedConfiguration
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the appsettings sections
services.AddOptions<CommonSettingsModel>()
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME))
services.AddOptions<CommonSettingsDto>()
.Bind(configuration.GetRequiredSection(CommonSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<DatabaseSettingsModel>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME))
services.AddOptions<DatabaseSettingsDto>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<MediaSettingsModel>()
.Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME))
services.AddOptions<MediaSettingsDto>()
.Bind(configuration.GetRequiredSection(MediaSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<JwtSettingsModel>()
.Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME))
services.AddOptions<PluginsSettingsDto>()
.Bind(configuration.GetRequiredSection(PluginsSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<CorsSettingsModel>()
.Bind(configuration.GetRequiredSection(CorsSettingsModel.SECTION_NAME))
services.AddOptions<JwtSettingsDto>()
.Bind(configuration.GetRequiredSection(JwtSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
services.AddOptions<CorsSettingsDto>()
.Bind(configuration.GetRequiredSection(CorsSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<EncryptionSettingsDto>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
@@ -24,5 +24,6 @@ public static partial class Errors
public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty));
public static Error CorsOriginsCannotBeEmpty => Error.Validation(description: nameof(CorsOriginsCannotBeEmpty));
public static Error CorsOriginIsInvalid => Error.Validation(description: nameof(CorsOriginIsInvalid));
public static Error PluginsDirectoryCannotBeEmpty => Error.Validation(description: nameof(PluginsDirectoryCannotBeEmpty));
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -0,0 +1,76 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Background job that persists the detection of the loaded plugins into the storage medium at startup.
/// </summary>
internal sealed class PluginDetectionSyncJob : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IPluginManager _pluginManager;
private readonly IReadOnlyList<string> _loadErrors;
private readonly ILogger<PluginDetectionSyncJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PluginDetectionSyncJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="loadErrors">The errors that occurred while loading the plugins.</param>
/// <param name="logger">Injected logger used for logging.</param>
public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList<string> loadErrors, ILogger<PluginDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_pluginManager = pluginManager;
_loadErrors = loadErrors;
_logger = logger;
}
/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (string loadError in _loadErrors)
_logger.LogWarning("Plugin load failure: {LoadError}", loadError);
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
IPluginRepository pluginRepository = unitOfWork.GetRepository<IPluginRepository>();
foreach (IPlugin plugin in _pluginManager.GetPlugins())
{
PluginEntity pluginEntity = new()
{
Id = plugin.Id,
Name = plugin.Name,
Author = plugin.Author,
Version = plugin.Version.ToString(),
Description = plugin.Description,
LoadStatus = PluginLoadStatus.Loaded,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
ErrorOr<Updated> upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsError)
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
}
await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Assembly load context of a single plugin, resolving the shared host assemblies from the default context and the plugin local dependencies from the plugin directory.
/// </summary>
internal sealed class PluginLoadContext : AssemblyLoadContext
{
private readonly string _pluginDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="PluginLoadContext"/> class.
/// </summary>
/// <param name="pluginDirectory">The directory where the plugin assemblies and their dependencies are located.</param>
/// <param name="name">The name of the load context.</param>
public PluginLoadContext(string pluginDirectory, string name) : base(name, isCollectible: true)
{
_pluginDirectory = pluginDirectory;
}
/// <inheritdoc/>
protected override Assembly? Load(AssemblyName assemblyName)
{
if (assemblyName.Name is null)
return null;
// try to resolve the assembly from the default context first, so that the plugin shares the host and framework assemblies
try
{
return AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
}
catch (FileNotFoundException)
{
}
// fall back to resolving the assembly from the plugin directory
string dependencyPath = Path.Combine(_pluginDirectory, assemblyName.Name + ".dll");
if (File.Exists(dependencyPath))
return LoadFromAssemblyPath(dependencyPath);
return null;
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Result of loading the plugins from the plugins directory.
/// </summary>
/// <param name="Plugins">The plugins that were loaded successfully.</param>
/// <param name="Errors">The errors that occurred while loading the plugins.</param>
internal sealed record PluginLoadResult(IReadOnlyList<IPlugin> Plugins, IReadOnlyList<string> Errors);
/// <summary>
/// Loads the plugins from the plugins directory, discovers their descriptors and registers their services.
/// </summary>
internal static class PluginLoader
{
/// <summary>
/// Loads the plugins from the <paramref name="pluginsDirectory"/>, discovers their descriptors and registers their services.
/// </summary>
/// <param name="pluginsDirectory">The directory where the plugin assemblies are located.</param>
/// <param name="services">The service collection to which the plugin services are added.</param>
/// <returns>The result of loading the plugins.</returns>
public static PluginLoadResult LoadPlugins(string pluginsDirectory, IServiceCollection services)
{
List<IPlugin> plugins = [];
List<string> errors = [];
if (!Directory.Exists(pluginsDirectory))
return new PluginLoadResult(plugins, errors);
foreach (string assemblyPath in Directory.EnumerateFiles(pluginsDirectory, "*.dll"))
{
// a failing plugin must not prevent the other plugins from loading, so each assembly is isolated in its own load context
PluginLoadContext loadContext = new(pluginsDirectory, Path.GetFileNameWithoutExtension(assemblyPath));
try
{
Assembly assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
{
IPlugin plugin = (IPlugin)Activator.CreateInstance(type)!;
if (plugin is IPluginServiceRegistrator serviceRegistrator)
serviceRegistrator.RegisterServices(services);
plugins.Add(plugin);
break; // only one plugin descriptor per assembly
}
}
}
catch (Exception exception)
{
errors.Add($"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}");
}
}
return new PluginLoadResult(plugins, errors);
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Manager of the plugins loaded by the host application.
/// </summary>
internal sealed class PluginManager : IPluginManager
{
private readonly IReadOnlyDictionary<Guid, IPlugin> _pluginsById;
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <param name="plugins">The plugins that were loaded successfully.</param>
public PluginManager(IEnumerable<IPlugin> plugins)
{
_pluginsById = plugins.ToDictionary(plugin => plugin.Id);
}
/// <inheritdoc/>
public IReadOnlyList<IPlugin> GetPlugins()
{
return [.. _pluginsById.Values];
}
/// <inheritdoc/>
public IPlugin? GetPlugin(Guid pluginId)
{
return _pluginsById.GetValueOrDefault(pluginId);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Reads the settings persisted by the host for a plugin.
/// </summary>
internal sealed class PluginSettingsStore : IPluginSettingsStore
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<PluginSettingsStore> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PluginSettingsStore"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="logger">Injected logger used to report the failures to read the plugin settings.</param>
public PluginSettingsStore(IUnitOfWork unitOfWork, ILogger<PluginSettingsStore> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
/// <inheritdoc/>
public async Task<IReadOnlyDictionary<string, string>?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
{
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
ErrorOr<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsError)
{
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
return null;
}
return getPluginResult.Value?.ToSettings();
}
}
@@ -44,5 +44,6 @@
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
<ProjectReference Include="..\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -3,6 +3,9 @@
"RootDirectory": "media",
"LibrariesDirectory": "libraries"
},
"PluginsSettings": {
"Directory": "plugins"
},
"CommonSettings": {
"Theme": "LuminaDark"
},
+1 -1
View File
@@ -47,7 +47,7 @@ public class Program
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
builder.Services.AddApplicationLayerServices();
builder.Services.AddInfrastructureLayerServices();
builder.Services.AddInfrastructureLayerServices(builder.Configuration);
builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices();
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Filmreihe</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Metadaten werden von GoodReads heruntergeladen...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Metadaten werden angereichert...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Berechne die Datei-Hashes...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Film Series</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Downloading metadata from GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Enriching metadata...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Hashing file contents...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinematográfica</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Descargando metadatos de GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Enriqueciendo metadatos...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Calculando los hashes de los archivos...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinématographique</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Téléchargement des métadonnées depuis GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Enrichissement des métadonnées...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Calcul des hachages des fichiers...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinematografica</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Scaricamento dei metadati da GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Arricchimento dei metadati...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Calcolo degli hash dei file...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>映画シリーズ</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>GoodReadsからメタデータをダウンロード中...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>メタデータを補完しています...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>ファイルのハッシュを計算中...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Film Series</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Downloading metadata from GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Enriching metadata...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Hashing file contents...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Serie de Filme</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Se descarcă metadate de pe GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Se îmbogățesc metadatele...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Se calculează hash-urile fișierelor...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>Киносерия</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Загрузка метаданных из GoodReads...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>Обогащение метаданных...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>Вычисление хешей файлов...</value>
@@ -186,8 +186,8 @@
<data name="FilmSeries" xml:space="preserve">
<value>电影系列</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>正在从GoodReads下载元数据...</value>
<data name="EnrichingMetadata" xml:space="preserve">
<value>正在丰富元数据...</value>
</data>
<data name="HashingFileContents" xml:space="preserve">
<value>正在计算文件哈希...</value>
@@ -171,7 +171,7 @@
DiscoveringFiles: '@_localizer["DiscoveringFiles"]',
ComparingFileHashes: '@_localizer["ComparingFileHashes"]',
HashingFileContents: '@_localizer["HashingFileContents"]',
GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]',
EnrichingMetadata: '@_localizer["EnrichingMetadata"]',
SavingScanData: '@_localizer["SavingScanData"]'
};
const jsLocalizedLibraryTypes = {
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Contracts.UnitTests.Fakes;
/// <summary>
/// A fake book metadata provider used to exercise the plugin contracts from outside.
/// </summary>
public sealed class FakeBookMetadataProvider : IPlugin, IPluginServiceRegistrator, IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
{
/// <inheritdoc/>
public Guid Id { get; } = Guid.Parse("11111111-1111-1111-1111-111111111111");
/// <inheritdoc/>
public string Name { get; } = "Fake Book Metadata Provider";
/// <inheritdoc/>
public string Author { get; } = "Lumina";
/// <inheritdoc/>
public Version Version { get; } = new(1, 0, 0);
/// <inheritdoc/>
public string Description { get; } = "A fake metadata provider used to exercise the plugin contracts.";
/// <inheritdoc/>
public LibraryType SupportedLibraryType { get; } = LibraryType.Book;
/// <inheritdoc/>
public bool RequiresWebAccess { get; } = true;
/// <inheritdoc/>
public IReadOnlyList<PluginSettingDescriptor> GetSettingsSchema()
{
return
[
new PluginSettingDescriptor(
Key: "preferredLanguage",
Label: "Preferred Language",
Type: PluginSettingType.Text,
DefaultValue: "en"
),
new PluginSettingDescriptor(
Key: "selectionStrategy",
Label: "Selection Strategy",
Type: PluginSettingType.Select,
DefaultValue: "first",
AllowedValues: ["first", "best"]
)
];
}
/// <inheritdoc/>
public void RegisterServices(IServiceCollection services)
{
}
/// <inheritdoc/>
public Task<IReadOnlyList<BookMetadataDto>> GetSearchResultsAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return Task.FromResult<IReadOnlyList<BookMetadataDto>>(
[
CreateMetadata("The Fellowship of the Ring", "3")
]
);
}
/// <inheritdoc/>
public Task<BookMetadataDto?> GetMetadataAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (lookup.Title is null)
return Task.FromResult<BookMetadataDto?>(null);
return Task.FromResult<BookMetadataDto?>(CreateMetadata(lookup.Title, "3"));
}
private static BookMetadataDto CreateMetadata(string title, string goodreadsId)
{
return new BookMetadataDto(
Title: title,
OriginalTitle: title,
Description: "A test description.",
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: new DateOnly(1954, 7, 29),
OriginalReleaseYear: 1954,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: "uk",
ReleaseVersion: null
),
Genres: [new GenreDto("fantasy")],
Tags: [new TagDto("epic fantasy")],
Language: new LanguageInfoDto("en", "English", "English"),
OriginalLanguage: null,
Publisher: "Houghton Mifflin",
PageCount: 398,
Format: BookFormat.Paperback,
Edition: null,
VolumeNumber: 1,
Series: null,
ASIN: null,
GoodreadsId: goodreadsId,
LCCN: null,
OCLCNumber: null,
OpenLibraryId: null,
LibraryThingId: null,
GoogleBooksId: null,
BarnesAndNobleId: null,
AppleBooksId: null,
Isbns: null,
Contributors: null,
Ratings: null,
CoverImageUrl: null
);
}
}
@@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.UnitTests.Fakes;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Contracts.UnitTests.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="IRemoteMetadataProvider"/> contracts.
/// </summary>
public class RemoteMetadataProviderTests
{
private readonly IRemoteMetadataProvider _provider = new FakeBookMetadataProvider();
[Fact]
public async Task GetMetadataAsync_WhenCalledThroughNonGenericInterface_ShouldReturnTypedMetadata()
{
// Arrange
MetadataLookupDto lookup = new BookMetadataLookupDto(
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Title: "The Fellowship of the Ring");
// Act
MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.NotNull(result);
BookMetadataDto bookMetadata = Assert.IsType<BookMetadataDto>(result);
Assert.Equal("The Fellowship of the Ring", bookMetadata.Title);
Assert.Equal("3", bookMetadata.GoodreadsId);
}
[Fact]
public async Task GetMetadataAsync_WhenNoMetadataFound_ShouldReturnNull()
{
// Arrange
MetadataLookupDto lookup = new BookMetadataLookupDto(
LibraryId: Guid.NewGuid(),
Path: "/books/unknown.epub");
// Act
MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetSearchResultsAsync_WhenCalledThroughNonGenericInterface_ShouldReturnTypedResults()
{
// Arrange
MetadataLookupDto lookup = new BookMetadataLookupDto(
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Title: "The Fellowship of the Ring");
// Act
IReadOnlyList<MetadataDto> result = await _provider.GetSearchResultsAsync(lookup, CancellationToken.None);
// Assert
Assert.Single(result);
BookMetadataDto bookMetadata = Assert.IsType<BookMetadataDto>(result[0]);
Assert.Equal("The Fellowship of the Ring", bookMetadata.Title);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins.Settings;
using Lumina.Plugins.Contracts.UnitTests.Fakes;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.Contracts.UnitTests.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="IPlugin"/> contract.
/// </summary>
public class PluginTests
{
private readonly IPlugin _plugin = new FakeBookMetadataProvider();
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldReturnDeclaredSettings()
{
// Act
IReadOnlyList<PluginSettingDescriptor> schema = _plugin.GetSettingsSchema();
// Assert
Assert.Equal(2, schema.Count);
Assert.Equal("preferredLanguage", schema[0].Key);
Assert.Equal(PluginSettingType.Text, schema[0].Type);
Assert.Equal("en", schema[0].DefaultValue);
Assert.Equal("selectionStrategy", schema[1].Key);
Assert.Equal(PluginSettingType.Select, schema[1].Type);
Assert.Contains("first", schema[1].AllowedValues!);
}
}