Replaces ErrorOr library with a custom implementation.

This commit is contained in:
BinaryAlley committed 2026-08-14 03:04:28 -07:00
1 parent 8fe90a4dde
commit 3b772d68ca
436 files changed
+4234 -3922

No files matched your search

@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -64,18 +64,18 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// mark the staging results against the media library scan snapshot of the previous scan
ErrorOr<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (markChangesResult.IsError)
Result<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (markChangesResult.IsFailure)
throw new InvalidOperationException(markChangesResult.FirstError.Description);
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// this job finished, increment the number of processed jobs progress
@@ -108,11 +108,11 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
@@ -69,14 +69,14 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// count the files that need hashing, for progress reporting purposes
ErrorOr<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getFilesToHashCountResult.IsError)
Result<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getFilesToHashCountResult.IsFailure)
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
int totalFilesToHash = getFilesToHashCountResult.Value;
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
DateTime lastUpdateTime = DateTime.UtcNow;
@@ -89,8 +89,8 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getFilesToHashPageResult.IsError)
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getFilesToHashPageResult.IsFailure)
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
IReadOnlyList<HashedFileSystemFileDto> filesToHashPage = getFilesToHashPageResult.Value;
if (filesToHashPage.Count == 0)
@@ -105,15 +105,15 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
}
}, cancellationToken).ConfigureAwait(false);
// write the computed hashes back to the staging results
ErrorOr<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
if (updateHashesResult.IsError)
Result<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
if (updateHashesResult.IsFailure)
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
lastPath = filesToHashPage[^1].Path;
@@ -149,11 +149,11 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents");
if (scanJobProgressResult.IsError)
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Books;
@@ -81,8 +81,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the metadata providers configured for the media library, in their configured order, that support the media library type
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsError)
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IRemoteMetadataProvider> providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
@@ -96,14 +96,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
// count the books that need their metadata enriched, for progress reporting purposes
ErrorOr<int> getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getBooksToEnrichCountResult.IsError)
Result<int> getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getBooksToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
DateTime lastUpdateTime = DateTime.UtcNow;
@@ -116,8 +116,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<IReadOnlyList<BookEntity>> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getBooksPageResult.IsError)
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getBooksPageResult.IsFailure)
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
if (booksPage.Count == 0)
@@ -135,7 +135,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
}
@@ -178,8 +178,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IRemoteMetadataProvider> providers, IBookRepository bookRepository, CancellationToken cancellationToken)
{
// convert the book to a domain object
ErrorOr<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsError)
Result<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
Book book = getBookResult.Value;
@@ -202,12 +202,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
ErrorOr<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
if (applyMetadataResult.IsError)
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
if (applyMetadataResult.IsFailure)
continue;
ErrorOr<Updated> updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateBookResult.IsError)
Result<Updated> updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateBookResult.IsFailure)
continue;
return;
@@ -247,11 +247,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata");
if (scanJobProgressResult.IsError)
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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.MediaLibrary;
@@ -71,18 +71,18 @@ 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
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
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
ErrorOr<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getDeletedPathsResult.IsError)
Result<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getDeletedPathsResult.IsFailure)
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
ErrorOr<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
if (applySnapshotSwapResult.IsError)
Result<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
if (applySnapshotSwapResult.IsFailure)
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
@@ -93,29 +93,29 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
}
// materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
ErrorOr<IReadOnlyList<string>> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsError)
Result<IReadOnlyList<string>> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
foreach (string path in getPathsResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<BookEntity?> getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
if (getExistingBookResult.IsError)
Result<BookEntity?> getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
if (getExistingBookResult.IsFailure)
throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
if (getExistingBookResult.Value is not null)
continue;
ErrorOr<Created> insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsError)
Result<Created> insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
throw new InvalidOperationException(insertBookResult.FirstError.Description);
}
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
Status = LibraryScanJobStatus.Completed;
@@ -149,11 +149,11 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
if (scanJobProgressResult.IsError)
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -86,28 +86,28 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsError ? getLibraryResult.FirstError.Description : "The media library was not found.");
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
// convert it to a domain object
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure)
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
// when the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
{
ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getFingerprintsResult.IsError)
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getFingerprintsResult.IsFailure)
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
fingerprintsByPath = getFingerprintsResult.Value;
}
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
@@ -139,7 +139,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
{
publishJobProgressResult = await PublishJobProgressAsync(
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastHeartbeat = now;
}
@@ -148,14 +148,14 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size
if (stagingBatch.Count > 0)
{
ErrorOr<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertResult.IsError)
Result<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
throw new InvalidOperationException(insertResult.FirstError.Description);
}
if (fingerprintBatch.Count > 0)
{
ErrorOr<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsError)
Result<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
throw new InvalidOperationException(upsertResult.FirstError.Description);
}
@@ -235,8 +235,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
// flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has
if (fingerprintBatch.Count >= STAGING_BATCH_SIZE)
{
ErrorOr<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertFingerprintsResult.IsError)
Result<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertFingerprintsResult.IsFailure)
throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description);
fingerprintBatch.Clear();
}
@@ -275,8 +275,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
});
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
{
ErrorOr<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsError)
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
}
@@ -326,11 +326,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using DebounceThrottle;
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Contracts.Responses.MediaLibrary.Management;
@@ -54,8 +54,8 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
if (cancellationToken.IsCancellationRequested)
return;
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId);
if (progressResult.IsError)
Result<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId);
if (progressResult.IsFailure)
return;
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
@@ -72,11 +72,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
{
if (cancellationToken.IsCancellationRequested)
return;
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
Result<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
CleanupDebouncer(mediaLibraryScanCompositeId);
if (!progressResult.IsError)
if (!progressResult.IsFailure)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(
@@ -93,11 +93,11 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
{
if (cancellationToken.IsCancellationRequested)
return;
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
Result<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
CleanupDebouncer(mediaLibraryScanCompositeId);
if (!progressResult.IsError)
if (!progressResult.IsFailure)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(