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

@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -101,7 +102,7 @@ public class AddBookRequestMappingTests
[
new(
_mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"),
_mediaContributorRoleDtoFixture.Create(name: "Author", category: "Writing")
_mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author)
)
],
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
@@ -7,7 +7,6 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -24,7 +23,7 @@ public class BookMetadataDtoMappingTests
private readonly GenreDtoFixture _genreDtoFixture = new();
[Fact]
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched()
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItToTheBook()
{
// Arrange
Book book = _bookFixture.Create();
@@ -37,7 +36,7 @@ public class BookMetadataDtoMappingTests
pageCount: 398);
// Act
Result<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
Result<Success> result = book.ApplyMetadata(metadata);
// Assert
Assert.False(result.IsFailure);
@@ -46,9 +45,6 @@ public class BookMetadataDtoMappingTests
Assert.Equal("The first part of J.R.R. Tolkien's epic adventure.", book.Metadata.Description.Value);
Assert.Equal(BookFormat.Paperback, book.Format.Value);
Assert.Equal("Houghton Mifflin", book.Metadata.Publisher.Value);
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal("Goodreads", book.MetadataProvider.Value);
Assert.True(book.LastMetadataUpdateUtc.HasValue);
}
[Fact]
@@ -64,10 +60,10 @@ public class BookMetadataDtoMappingTests
};
// Act
Result<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
Result<Success> result = book.ApplyMetadata(metadata);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(MetadataStatus.Pending, book.MetadataStatus);
Assert.NotEqual("The Fellowship of the Ring", book.Metadata.Title);
}
}
@@ -0,0 +1,218 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Application.Core.MediaLibrary.Management.Events;
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.Domain.Common.Exceptions;
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.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 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.Application.UnitTests.Core.MediaLibrary.Management.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryMediaItemDeletedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _mockLogger;
private readonly LibraryMediaItemDeletedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandlerTests"/> class.
/// </summary>
public LibraryMediaItemDeletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockLogger = Substitute.For<ILogger<LibraryMediaItemDeletedDomainEventHandler>>();
_sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger);
}
[Fact]
public async Task HandleAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title);
await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork"));
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
// a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged
await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetBookFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the book");
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteBookFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
Error error = Error.Failure("Database.Error", "Failed to delete the book");
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1765,20 +1765,6 @@ public class AddBookCommandValidatorTests
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
}
[Fact]
public void Validate_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor)] };
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
}
[Fact]
public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError()
{