Returns the unit of work save changes result

This commit is contained in:
BinaryAlley committed 2026-09-26 12:59:17 +03:00
1 parent f3e465255e
commit 64ef3a1e22
141 files changed
+1388 -1151

No files matched your search

@@ -33,7 +33,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// </summary>
internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob
{
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 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<MediaLibraryScanArtworkEnrichmentJob> _logger;
@@ -62,30 +62,30 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
// 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
// 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
// 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:
// 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>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
// whether the providers that require access to the web are used during the enrichment
// Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
// whether the providers that require access to the web are used during the enrichment.
string libraryName = string.Empty;
bool canDownloadMetadataFromWeb = false;
if (unitOfWork.LibraryRepository is not null)
{
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
_logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
else
@@ -95,8 +95,8 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
}
// get the artwork providers configured for the media library, in their configured order, that support the media library type.
// the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding
// Get the artwork providers configured for the media library, in their configured order, that support the media library type.
// The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
List<IArtworkProvider> artworkProviders = [];
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
{
@@ -118,7 +118,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
}
// when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely
// When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely.
if (artworkProviders.Count > 0)
{
IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService<IBookArtworkService>();
@@ -129,7 +129,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
// set the initial progress of the scan job
// Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -138,7 +138,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
int minUpdateIntervalMs = 100;
int processedBooksCount = 0;
// process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size
// Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size.
string? lastPath = null;
while (true)
{
@@ -151,7 +151,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
if (booksPage.Count == 0)
break;
// load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory
// Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
@@ -162,11 +162,11 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
// check if enough time has passed since last update
// Check if enough time has passed since the last update.
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -174,24 +174,24 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
}
// persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
unitOfWork.ClearTrackedEntities();
lastPath = booksPage[^1].Path;
}
}
else
{
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value);
}
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -222,19 +222,17 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> authorsDisplayNamesByBookId, CancellationToken cancellationToken)
{
// when no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped
// When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
if (bookArtworkService is null || artworkProviders.Count == 0)
return;
ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
if (resolvedArtwork is null)
{
// no artwork provider returned usable artwork, mark the cover artwork of the book as failed to resolve
BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
// No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve.
BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
if (coverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
}
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
else
{
coverArtwork.Status = ArtworkStatus.Failed;
@@ -244,9 +242,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
return;
}
BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
// when the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
// When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
// is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it.
ulong contentHash = 0;
bool shouldStoreArtwork = true;
@@ -262,11 +260,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
Result<string> saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false);
if (saveArtworkResult.IsFailure)
{
// a failing artwork storage must not prevent the book from being tracked as failed to resolve
// A failing artwork storage must not prevent the book from being tracked as failed to resolve.
if (existingCoverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
}
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
else
{
existingCoverArtwork.Status = ArtworkStatus.Failed;
@@ -276,7 +272,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
return;
}
// for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one
// For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one.
if (contentHash == 0)
{
string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
@@ -284,9 +280,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
if (existingCoverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
}
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
else
{
existingCoverArtwork.FileName = saveArtworkResult.Value;
@@ -300,7 +294,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
else
{
// the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched
// The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched.
existingCoverArtwork!.Status = ArtworkStatus.Enriched;
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
@@ -338,13 +332,13 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
}
catch (Exception)
{
// a failing artwork provider must not prevent the other providers from being tried
// A failing artwork provider must not prevent the other providers from being tried.
}
if (artwork is null)
continue;
// a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract
// A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
continue;
@@ -4,7 +4,7 @@ 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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -17,9 +17,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
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.WrittenContentLibrary.BookLibrary.Metadata;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -38,7 +41,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// </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 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;
@@ -67,36 +70,36 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
// 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
// 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
// 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:
// 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>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment
// Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment.
bool canDownloadMetadataFromWeb = false;
if (unitOfWork.LibraryRepository is not null)
{
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
_logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used.");
else
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
}
// get the metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web
// Get the metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
@@ -112,7 +115,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
providers.AddRange(configuredProviders);
}
// read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
bool shouldAggregateMetadataWhenMissing = false;
if (unitOfWork.UserSettingsRepository is not null)
{
@@ -123,7 +126,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely
// When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely.
if (providers.Count > 0)
{
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
@@ -131,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
// set the initial progress of the scan job
// Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -140,11 +143,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
int minUpdateIntervalMs = 100;
int processedBooksCount = 0;
// the contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many books of the same page
// The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many books of the same page.
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
// Process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size.
string? lastPath = null;
while (true)
{
@@ -163,11 +166,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
// check if enough time has passed since last update
// Check if enough time has passed since the last update.
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -175,8 +178,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
}
// persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
unitOfWork.ClearTrackedEntities();
contributorsByNormalizedName.Clear();
@@ -184,16 +189,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
}
else
{
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value);
}
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -224,7 +227,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, CancellationToken cancellationToken)
{
// convert the book to a domain object
// Convert the book to a domain object.
Result<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
@@ -233,7 +236,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
BookMetadataLookupDto bookMetadataLookup = 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
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,
@@ -246,19 +249,20 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
if (resolvedMetadata is null)
{
// no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata
// No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata.
bookEntity.MetadataStatus = MetadataStatus.Failed;
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
bookEntity.UpdatedBy = Guid.NewGuid();
return;
}
// apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns
// Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns.
book.ApplyMetadata(resolvedMetadata.Metadata);
bookEntity.ApplyMetadataToEntity(book);
// link the media contributors discovered while enriching to the book, finding or creating a single contributor per person
// Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
List<BookMediaContributor> domainContributors = [];
foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? [])
{
if (contributor.Name?.DisplayName is null)
@@ -266,25 +270,26 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false);
string roleName = contributor.Role?.Name ?? "Contributor";
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author;
if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role))
continue;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = bookEntity.Id,
MediaContributorId = contributorEntity.Id,
RoleName = roleName,
RoleCategory = roleCategory,
Role = role,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
});
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
}
bookEntity.BookContributors.Clear();
bookEntity.BookContributors.AddRange(linkedContributors);
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]);
bookEntity.Contributors.Clear();
bookEntity.Contributors.AddRange(linkedContributors);
book.UpdateContributors(domainContributors);
// mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern
// Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern.
bookEntity.MetadataStatus = MetadataStatus.Enriched;
bookEntity.MetadataProvider = resolvedMetadata.ProviderName;
bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
@@ -340,7 +345,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
catch (Exception)
{
// a failing metadata provider must not prevent the other providers from being tried
// A failing metadata provider must not prevent the other providers from being tried.
}
}
return null;
@@ -369,12 +374,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
contributingProviders.Add(metadataProvider.Name);
// the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely
// The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely.
bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
}
catch (Exception)
{
// a failing metadata provider must not prevent the other providers from being tried
// A failing metadata provider must not prevent the other providers from being tried.
}
}
@@ -53,36 +53,36 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
// 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
// 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
// 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:
// 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>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state
// Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
// are compared against the current provider configuration to detect whether it changed since the last scan
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
// Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
// are compared against the current provider configuration to detect whether it changed since the last scan.
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
LibraryEntity library = getLibraryResult.Value;
// load the provider configurations of the media library, whose fingerprint is compared against the stored one
// Load the provider configurations of the media library, whose fingerprint is compared against the stored one.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getMetadataConfigurationsResult.IsFailure)
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
@@ -91,7 +91,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
if (getArtworkConfigurationsResult.IsFailure)
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
// read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
bool shouldAggregateMetadataWhenMissing = false;
if (unitOfWork.UserSettingsRepository is not null)
{
@@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
@@ -122,27 +122,29 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
}
// store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
// the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed
// Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
// The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed.
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
library.UpdatedOnUtc = DateTime.UtcNow;
library.UpdatedBy = Guid.NewGuid();
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
// increment the number of processed elements progress
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
@@ -52,17 +52,17 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
// 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
// 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
// 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:
// 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>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
@@ -70,27 +70,27 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium
// Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them
// Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them.
Result<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getDeletedPathsResult.IsFailure)
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
// get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched
// Get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched.
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getChangedPathsResult.IsFailure)
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
// Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan.
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
if (applySnapshotSwapResult.IsFailure)
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
// reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow
// Reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow.
if (getChangedPathsResult.Value.Count > 0)
{
Result<Updated> resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
@@ -98,14 +98,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
}
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
// Raise a deletion event for every media library scan snapshot item that is no longer present on disk.
foreach (string deletedPath in getDeletedPathsResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
await domainEventPublisher.PublishAsync(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
// Materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata.
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
@@ -124,19 +124,21 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (insertBookResult.IsFailure)
throw new InvalidOperationException(insertBookResult.FirstError.Description);
}
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
// increment the number of processed elements progress
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -2,6 +2,8 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
@@ -109,12 +111,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
// Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status,
// and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed.
IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService<IMediaLibraryProviderConfigurationStore>();
Result<IEnumerable<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
Result<PaginatedResultDto<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: stoppingToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
_logger.LogError("Failed to get the detected plugins while reconciling the plugin rows.");
else
{
foreach (PluginEntity plugin in getPluginsResult.Value)
foreach (PluginEntity plugin in getPluginsResult.Value.Data)
{
if (detectedPluginIds.Contains(plugin.Id))
continue;
@@ -128,12 +130,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}
// Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type.
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
Result<PaginatedResultDto<LibraryEntity>> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync<BaseFilterDto>(cancellationToken: stoppingToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
_logger.LogError("Failed to get the media libraries while seeding the provider configurations.");
else
{
foreach (LibraryEntity library in getLibrariesResult.Value)
foreach (LibraryEntity library in getLibrariesResult.Value.Data)
{
Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
if (ensureResult.IsFailure)
@@ -144,7 +146,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}
}
await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
}
/// <summary>
@@ -68,7 +68,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// <returns>A task that represents the asynchronous operation.</returns>
public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync();
RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately: true, cancellationToken).FireAndForgetSafeAsync();
return Task.CompletedTask;
}
@@ -174,8 +174,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
continue;
}
// A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution.
bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup;
RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync();
bool shouldRunImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup;
RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately, cancellationToken).FireAndForgetSafeAsync();
}
}
@@ -183,9 +183,9 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// Runs the execution cycle worker of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is run.</param>
/// <param name="runImmediately">Whether the task of the scheduled job is run immediately when the cycle starts.</param>
/// <param name="shouldRunImmediately">Whether the task of the scheduled job is run immediately when the cycle starts.</param>
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken)
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool shouldRunImmediately, CancellationToken stoppingToken)
{
// Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one
// scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread.
@@ -203,7 +203,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
CancellationToken cycleToken = linkedCancellationTokenSource.Token;
// An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is
// recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs.
if (runImmediately)
if (shouldRunImmediately)
await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false);
// The schedule is read from the storage medium for every cycle, so the delay until the next run is always
@@ -320,7 +320,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
IDomainEventPublisher domainEventPublisher = services.GetRequiredService<IDomainEventPublisher>();
// Load the scheduled job, and mark its task as started.
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return;
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
@@ -383,8 +383,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
// A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the
// running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job,
// whose active state is what makes it fire again at the next application startup.
bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup;
Result<Success> completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun);
bool doesCompleteTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup;
Result<Success> completeExecutionResult = scheduledJob.MarkExecutionCompleted(doesCompleteTheCycleRun);
if (completeExecutionResult.IsFailure)
return;
foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents())
@@ -412,7 +412,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return ScheduledJobStatus.Added;
ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
@@ -433,17 +433,19 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added;
Result<Updated> updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync(
CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
scheduledJob.ToUpdatedRepositoryEntity(reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
return ScheduledJobStatus.Added;
if (openExecution is not null)
{
Result<Updated> updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(
CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
openExecution.ToUpdatedRepositoryEntity(DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
if (updateExecutionResult.IsFailure)
return ScheduledJobStatus.Added;
}
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
return reconciledStatus;
}
@@ -468,7 +470,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return null;
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
@@ -488,57 +490,4 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local);
}
/// <summary>
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
/// </summary>
/// <param name="scheduledJob">The scheduled job to copy.</param>
/// <param name="status">The status of the copy.</param>
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
/// <returns>The copy of the scheduled job.</returns>
private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
{
return new ScheduledJobEntity
{
Id = scheduledJob.Id,
Name = scheduledJob.Name,
TaskType = scheduledJob.TaskType,
ScheduleType = scheduledJob.ScheduleType,
IntervalMinutes = scheduledJob.IntervalMinutes,
Hour = scheduledJob.Hour,
Minute = scheduledJob.Minute,
Status = status,
OwnerUserId = scheduledJob.OwnerUserId,
LastStartedOnUtc = lastStartedOnUtc,
LastCompletedOnUtc = lastCompletedOnUtc,
CreatedOnUtc = scheduledJob.CreatedOnUtc,
CreatedBy = scheduledJob.CreatedBy,
UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
UpdatedBy = scheduledJob.UpdatedBy
};
}
/// <summary>
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
/// </summary>
/// <param name="execution">The execution to copy.</param>
/// <param name="completedOnUtc">The completion time of the copy.</param>
/// <returns>The copy of the execution.</returns>
private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
{
return new ScheduledJobExecutionEntity
{
Id = execution.Id,
ScheduledJobId = execution.ScheduledJobId,
TaskType = execution.TaskType,
IsCycleRun = execution.IsCycleRun,
WasCycleActive = execution.WasCycleActive,
StartedOnUtc = execution.StartedOnUtc,
CompletedOnUtc = completedOnUtc,
CreatedOnUtc = execution.CreatedOnUtc,
CreatedBy = execution.CreatedBy,
UpdatedOnUtc = execution.UpdatedOnUtc,
UpdatedBy = execution.UpdatedBy
};
}
}
@@ -98,7 +98,9 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor
domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents());
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
// Publish the domain events of the queued media library scans.
foreach (IDomainEvent domainEvent in domainEvents)
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
@@ -30,7 +32,7 @@ internal static class ThemeSynchronizer
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken)
{
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
{
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
@@ -38,7 +40,7 @@ internal static class ThemeSynchronizer
}
// Themes that were soft deleted by the user must not be reinstalled automatically.
List<ThemeEntity> themes = [.. getThemesResult.Value];
List<ThemeEntity> themes = [.. getThemesResult.Value.Data];
foreach (string archivePath in themeService.GetBundledThemeArchivePaths())
{
@@ -107,7 +109,9 @@ internal static class ThemeSynchronizer
await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false);
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
}
/// <summary>