Adds independent metadata and artwork enrichment

Splits the single combined enrichment phase of the media library scan into
independent, modular jobs, so that the metadata and the artwork of a book
are enriched separately and only when their respective triggers fire.

- Adds the MediaContributorRoleCategory enum (Other first, then Author,
  Translator, Illustrator, Publisher and Narrator) and makes the role
  category canonical, so that roles describing the same kind of
  contribution are never treated as distinct.
- Realizes the media contributor bounded context: a MediaContributor is a
  person, unique by display name, without a role. The role moves to the
  per-work participation (BookContributors), so that a single contributor
  can play multiple roles. Contributors are created and linked by the
  metadata enrichment job, and exposed to subsequent jobs.
- Makes the Book aggregate pure: the enrichment tracking state (metadata
  status, providers, timestamps and covers) no longer lives on the domain
  aggregate, but stays in the Books table, managed directly by the jobs.
- Models artwork generically as a BookArtwork child table (type, ordinal,
  content hash, status and provider), so that each piece of artwork is
  tracked independently and a change of one does not require the others to
  be re-fetched.
- Splits the scan DAG into ResultsSave, ProviderConfigurationInvalidation,
  MetadataEnrichment and ArtworkEnrichment jobs. The invalidation job
  fingerprints the provider configuration of a library and resets the
  enrichment state of the affected channel when it changed. The artwork job
  resolves the missing artwork, hashing it to detect identical covers and
  skip re-copying. Content-changed books are reset by the results save job.
- Deletes the book and its stored artwork when the file disappears from the
  library.
- Adds the migration creating the new tables, backfilling the existing
  covers into the artwork table, and adding the configuration fingerprints.
- Localizes the new scan job stages, and fixes the invalidation job wiping
  the library content locations by persisting the fingerprints through the
  change tracker instead of the repository update action.
This commit is contained in:
BinaryAlley committed 2026-08-27 14:41:49 +03:00
1 parent 4ee2976806
commit 565fe68239
98 files changed
+5845 -630

No files matched your search

@@ -0,0 +1,299 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanArtworkEnrichmentJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _mockLogger;
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJobTests"/> class.
/// </summary>
public MediaLibraryScanArtworkEnrichmentJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_mockLogger = Substitute.For<ILogger<MediaLibraryScanArtworkEnrichmentJob>>();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched()
{
// Arrange
Guid artworkPluginId = Guid.NewGuid();
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title");
SetupSingleBookPage(book, artworkPluginId);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
_libraryId.Value,
book.Id,
"My Library",
"Frank Herbert",
"Test Title",
Arg.Any<ArtworkDto>(),
Arg.Any<CancellationToken>());
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
Assert.Equal(0, coverArtwork.Ordinal);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName);
Assert.Equal(123ul, coverArtwork.ContentHash);
Assert.Equal("Artwork Provider", coverArtwork.Provider);
Assert.NotNull(coverArtwork.LastUpdateUtc);
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched()
{
// Arrange
Guid artworkPluginId = Guid.NewGuid();
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
// the book already has a stored cover with the same content hash as the resolved artwork
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))];
SetupSingleBookPage(book, artworkPluginId);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName);
Assert.Equal("Artwork Provider", coverArtwork.Provider);
Assert.NotNull(coverArtwork.LastUpdateUtc);
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed()
{
// Arrange
Guid artworkPluginId = Guid.NewGuid();
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((ArtworkDto?)null);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, artworkPluginId);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
Assert.Equal(0, coverArtwork.Ordinal);
Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status);
Assert.Null(coverArtwork.FileName);
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed()
{
// Arrange
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
/// <summary>
/// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container.
/// </summary>
/// <param name="artworkPluginId">The Id of the plugin providing the artwork.</param>
/// <param name="artworkProvider">The artwork provider to resolve.</param>
/// <param name="bookArtworkService">The service used to store the artwork of the books.</param>
/// <param name="fileHashService">The service used to hash the artwork.</param>
private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService)
{
ServiceCollection services = new();
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
services.AddSingleton(bookArtworkService);
services.AddSingleton(fileHashService);
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
}
/// <summary>
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider.
/// </summary>
/// <param name="book">The book whose artwork the job must resolve.</param>
/// <param name="artworkPluginId">The Id of the plugin configured as artwork provider for the library.</param>
private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId)
{
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)
]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
}
}
@@ -1,21 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
@@ -27,6 +31,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Plugins.Contracts.Core.Metadata;
@@ -55,6 +60,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _mockLogger;
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
@@ -62,11 +68,11 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
@@ -86,8 +92,10 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
@@ -125,7 +133,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
}
@@ -145,8 +153,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -285,116 +292,125 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the enrichment tracking columns are managed directly on the entity by the enrichment job
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal("First Provider", book.MetadataProvider);
Assert.NotNull(book.LastMetadataUpdateUtc);
Assert.Equal("First Title", book.Title);
Assert.Equal("First Publisher", book.Publisher);
}
[Fact]
public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author);
MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator]));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator");
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(authorEntity));
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(translatorEntity));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>());
// the participation rows are replaced on the entity, carrying the role and the category of each contributor
Assert.Equal(2, book.BookContributors.Count);
BookContributorEntity linkedAuthor = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == authorEntity.Id);
Assert.Equal("Author", linkedAuthor.RoleName);
Assert.Equal(MediaContributorRoleCategory.Author, linkedAuthor.RoleCategory);
Assert.Equal(book.Id, linkedAuthor.BookId);
BookContributorEntity linkedTranslator = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == translatorEntity.Id);
Assert.Equal("Translator", linkedTranslator.RoleName);
Assert.Equal(MediaContributorRoleCategory.Translator, linkedTranslator.RoleCategory);
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
}
[Fact]
public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author]));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub");
BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub");
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([
_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)
]));
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
.Returns(Result.From(2));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockBookRepository.Received(1).UpdateAsync(
Arg.Is<BookEntity>(entity => entity.MetadataStatus == MetadataStatus.Failed),
Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get the artwork provider configurations"));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(authorEntity));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
Guid artworkPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
ServiceCollection services = new();
services.AddKeyedSingleton(firstPluginId, firstProvider);
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
services.AddSingleton(mockBookArtworkService);
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
_libraryId.Value,
book.Id,
Arg.Any<string>(),
Arg.Any<string>(),
"First Title",
Arg.Any<ArtworkDto>(),
Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).UpdateAsync(
Arg.Is<BookEntity>(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"),
Arg.Any<CancellationToken>());
// the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
Assert.Single(firstBook.BookContributors);
Assert.Single(secondBook.BookContributors);
Assert.Equal(authorEntity.Id, firstBook.BookContributors[0].MediaContributorId);
Assert.Equal(authorEntity.Id, secondBook.BookContributors[0].MediaContributorId);
}
[Fact]
@@ -472,63 +488,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess()
{
// Arrange
Guid localPluginId = Guid.NewGuid();
Guid artworkPluginId = Guid.NewGuid();
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
localProvider.Name.Returns("Local Provider");
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
localProvider.RequiresWebAccess.Returns(false);
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Local Title"));
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Web Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.RequiresWebAccess.Returns(true);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
ServiceCollection services = new();
services.AddKeyedSingleton(localPluginId, localProvider);
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, localPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web
await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
/// </summary>
@@ -570,8 +529,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
}
}
@@ -0,0 +1,291 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanProviderConfigurationInvalidationJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _mockLogger;
private readonly MediaLibraryScanProviderConfigurationInvalidationJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJobTests"/> class.
/// </summary>
public MediaLibraryScanProviderConfigurationInvalidationJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProviderConfigurationInvalidationJob>>();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanProviderConfigurationInvalidationJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenNoFingerprintIsStored_ShouldSeedTheFingerprintsWithoutResettingAnything()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: null);
SetupLibraryAndConfigurations(library);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE", artworkProvidersConfigurationFingerprint: null);
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenArtworkFingerprintDiffers_ShouldResetTheArtworkStatus()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE");
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenFingerprintsMatch_ShouldNotResetAnythingButStillPersistTheFingerprints()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
List<LibraryMetadataProviderConfigurationEntity> metadataConfigurations = _metadataConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
List<LibraryArtworkProviderConfigurationEntity> artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations);
// the stored fingerprints match the ones computed from the current provider configuration
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb);
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb);
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly()
{
// Arrange
// both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the media library"));
SetupConfigurations();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
/// <summary>
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
/// </summary>
/// <param name="library">The media library the job must read.</param>
/// <param name="metadataConfigurations">The metadata provider configurations of the media library.</param>
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
{
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
SetupConfigurations(metadataConfigurations, artworkConfigurations);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
}
/// <summary>
/// Stubs the provider configuration repositories and the user settings repository used by the job.
/// </summary>
/// <param name="metadataConfigurations">The metadata provider configurations of the media library, if already created by the caller.</param>
/// <param name="artworkConfigurations">The artwork provider configurations of the media library, if already created by the caller.</param>
private void SetupConfigurations(List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
{
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
metadataConfigurations ?? [
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
artworkConfigurations ?? [
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
]));
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
}
}
@@ -21,6 +21,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -38,6 +39,7 @@ public class MediaLibraryScanResultsSaveJobTests
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanResultsSaveJob _sut;
@@ -62,8 +64,10 @@ public class MediaLibraryScanResultsSaveJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
@@ -89,6 +93,10 @@ public class MediaLibraryScanResultsSaveJobTests
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
@@ -105,18 +113,44 @@ public class MediaLibraryScanResultsSaveJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is<IReadOnlyCollection<string>>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// no book content changed since the last scan, so the enrichment state of the books must not be reset
await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())