Merge pull request #254 from BinaryAlley/bugfix/fix-too-many-sql-variables-during-scan

Fixes large library scans hitting the SQLite parameter limit
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-10-29 21:21:49 +02:00
commit 3d22c05e55
23 files changed
+544 -96

No files matched your search

@@ -30,7 +30,7 @@ public interface ILibraryScanSnapshotRepository : IRepository<LibraryScanSnapsho
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
Task<Result<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken);
Task<Result<IReadOnlySet<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
@@ -43,4 +43,14 @@ public interface ILibraryScanSnapshotRepository : IRepository<LibraryScanSnapsho
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Removes the media library scan snapshot entries that the scan identified by <paramref name="scanId"/> added or modified, restoring the snapshot to
/// the state it had before the scan was applied.
/// </summary>
/// <param name="libraryId">The unique identifier of the library whose scan snapshot is rolled back.</param>
/// <param name="scanId">The unique identifier of the media library scan whose snapshot entries are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> RollbackSnapshotForScanAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken);
}
@@ -25,6 +25,14 @@ public interface IMusicLibraryScanItemMetadataRepository : IRepository<MusicLibr
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByScanIdAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Gets all the staged music metadata items of the media library identified by <paramref name="libraryId"/>, regardless of the scan that staged them.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
@@ -77,7 +77,14 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
// Cancelling the scan cancels its own token, so the cleanup must not observe it, otherwise the staged results of the cancelled scan would survive the cancellation.
// A scan that was cancelled after its snapshot was applied has not materialized its items yet, so its snapshot entries are rolled back, allowing the next
// scan to treat the files as new and extract their metadata again instead of skipping them as unchanged.
Result<Deleted> rollbackSnapshotResult = await _unitOfWork.LibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(
domainEvent.LibraryId.Value, domainEvent.ScanId.Value, CancellationToken.None).ConfigureAwait(false);
if (rollbackSnapshotResult.IsFailure)
throw new EventualConsistencyException(rollbackSnapshotResult.FirstError, rollbackSnapshotResult.Errors);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, CancellationToken.None).ConfigureAwait(false);
if (clearStagingResult.IsFailure)
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
}
@@ -86,11 +86,19 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
// Release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job.
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
// Releasing the resources cancels the scan's own token, so the cleanup that follows must not observe it, otherwise the staged results of a failed scan
// would survive the failure and leak into the storage medium.
// A scan that failed after its snapshot was applied has not materialized its items yet, so its snapshot entries are rolled back, allowing the next
// scan to treat the files as new and extract their metadata again instead of skipping them as unchanged.
Result<Deleted> rollbackSnapshotResult = await _unitOfWork.LibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(
domainEvent.LibraryId.Value, domainEvent.MediaLibraryScanCompositeId.ScanId.Value, CancellationToken.None).ConfigureAwait(false);
if (rollbackSnapshotResult.IsFailure)
throw new EventualConsistencyException(rollbackSnapshotResult.FirstError, rollbackSnapshotResult.Errors);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, CancellationToken.None).ConfigureAwait(false);
if (clearStagingResult.IsFailure)
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
// Notify SignalR clients that the library scan failed.
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, CancellationToken.None).ConfigureAwait(false);
}
}
@@ -73,10 +73,15 @@ internal static class SharedReferenceResolver
List<string> unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))];
if (unresolvedNames.Count > 0)
{
// Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key.
List<TEntity> storedEntities = await context.Set<TEntity>()
.Where(entity => unresolvedNames.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// A large request can reference more shared names than the storage medium accepts as the parameters of a single statement, so the lookup
// is split into bounded chunks and the stored rows of every chunk are accumulated.
const int LOOKUP_CHUNK_SIZE = 20_000;
List<TEntity> storedEntities = [];
foreach (string[] chunk in unresolvedNames.Chunk(LOOKUP_CHUNK_SIZE))
// Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key.
storedEntities.AddRange(await context.Set<TEntity>()
.Where(entity => chunk.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
.ToListAsync(cancellationToken).ConfigureAwait(false));
foreach (TEntity storedEntity in storedEntities)
resolvedByName[NormalizeName(storedEntity.Name!)] = storedEntity;
@@ -320,10 +320,15 @@ internal sealed class BookRepository : IBookRepository
// The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium.
List<string> distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)];
List<string> existingPaths = await _luminaDbContext.Books
.Where(repositoryBook => repositoryBook.LibraryId == libraryId && distinctPaths.Contains(repositoryBook.Path))
.Select(repositoryBook => repositoryBook.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false);
// A large library stages far more paths than the storage medium accepts as the parameters of a single statement, so the lookup is split into
// bounded chunks and the matches of every chunk are accumulated, which keeps a scan of any size within the parameter limit.
const int LOOKUP_CHUNK_SIZE = 20_000;
List<string> existingPaths = [];
foreach (string[] chunk in distinctPaths.Chunk(LOOKUP_CHUNK_SIZE))
existingPaths.AddRange(await _luminaDbContext.Books
.Where(repositoryBook => repositoryBook.LibraryId == libraryId && chunk.Contains(repositoryBook.Path))
.Select(repositoryBook => repositoryBook.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false));
return Result.From<IReadOnlyCollection<string>>(existingPaths);
}
@@ -413,15 +418,25 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
await _luminaDbContext.Books
.Where(book => book.LibraryId == libraryId && paths.Contains(book.Path))
.ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken)
.ConfigureAwait(false);
List<string> pathList = [.. paths.Distinct(StringComparer.Ordinal)];
if (pathList.Count == 0)
return Result.Updated;
await _luminaDbContext.Set<BookArtworkEntity>()
.Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId && paths.Contains(book.Path)))
.ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken)
.ConfigureAwait(false);
// A scan can change more paths than the storage medium accepts as the parameters of a single statement, so the reset is split into bounded
// chunks, keeping the operation within the parameter limit regardless of the library size.
const int LOOKUP_CHUNK_SIZE = 20_000;
foreach (string[] chunk in pathList.Chunk(LOOKUP_CHUNK_SIZE))
{
await _luminaDbContext.Books
.Where(book => book.LibraryId == libraryId && chunk.Contains(book.Path))
.ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken)
.ConfigureAwait(false);
await _luminaDbContext.Set<BookArtworkEntity>()
.Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId && chunk.Contains(book.Path)))
.ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken)
.ConfigureAwait(false);
}
return Result.Updated;
}
@@ -70,7 +70,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
public async Task<Result<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken)
public async Task<Result<IReadOnlySet<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken)
{
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
const string GET_PATHS_SQL = """
@@ -82,7 +82,8 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
CommandDefinition command = new(GET_PATHS_SQL, new { libraryId }, cancellationToken: cancellationToken);
IEnumerable<string> paths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
return paths.ToList();
// The snapshot is keyed by path, so the paths are unique, and a set answers the membership checks of the materializers without another copy.
return Result.From<IReadOnlySet<string>>(paths.ToHashSet(StringComparer.Ordinal));
}
/// <summary>
@@ -182,6 +183,36 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
return Result.Updated;
}
/// <summary>
/// Removes the media library scan snapshot entries that the scan identified by <paramref name="scanId"/> added or modified, restoring the snapshot to
/// the state it had before the scan was applied.
/// </summary>
/// <param name="libraryId">The unique identifier of the library whose scan snapshot is rolled back.</param>
/// <param name="scanId">The unique identifier of the media library scan whose snapshot entries are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> RollbackSnapshotForScanAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken)
{
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
// The audit rows of the scan identify the paths that its snapshot swap added or updated, so removing those snapshot rows makes the next scan
// treat the files as new again, instead of skipping the re-extraction of the metadata that never made it into materialized items.
const string ROLLBACK_SQL = """
DELETE FROM LibraryScanSnapshots
WHERE LibraryId = @libraryId
AND Path IN (
SELECT Path
FROM LibraryScanResults
WHERE LibraryScanId = @scanId
AND Status IN ('New', 'Modified')
);
""";
CommandDefinition command = new(ROLLBACK_SQL, new { libraryId, scanId }, cancellationToken: cancellationToken);
await connection.ExecuteAsync(command).ConfigureAwait(false);
return Result.Deleted;
}
/// <summary>
/// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking.
/// </summary>
@@ -58,6 +58,22 @@ internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScan
return Result.From(items);
}
/// <summary>
/// Gets all the staged music metadata items of the media library identified by <paramref name="libraryId"/>, regardless of the scan that staged them.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
IReadOnlyList<MusicLibraryScanItemMetadataEntity> items = await _luminaDbContext.MusicLibraryScanItemMetadata
.AsNoTracking()
.Where(musicMetadata => musicMetadata.LibraryId == libraryId)
.OrderBy(musicMetadata => musicMetadata.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From(items);
}
/// <summary>
/// Deletes all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
@@ -84,10 +84,15 @@ internal sealed class TrackRepository : ITrackRepository
// The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium.
List<string> distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)];
List<string> existingPaths = await _luminaDbContext.Tracks
.Where(repositoryTrack => repositoryTrack.LibraryId == libraryId && distinctPaths.Contains(repositoryTrack.Path))
.Select(repositoryTrack => repositoryTrack.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false);
// A large library stages far more paths than the storage medium accepts as the parameters of a single statement, so the lookup is split into
// bounded chunks and the matches of every chunk are accumulated, which keeps a scan of any size within the parameter limit.
const int LOOKUP_CHUNK_SIZE = 20_000;
List<string> existingPaths = [];
foreach (string[] chunk in distinctPaths.Chunk(LOOKUP_CHUNK_SIZE))
existingPaths.AddRange(await _luminaDbContext.Tracks
.Where(repositoryTrack => repositoryTrack.LibraryId == libraryId && chunk.Contains(repositoryTrack.Path))
.Select(repositoryTrack => repositoryTrack.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false));
return Result.From<IReadOnlyCollection<string>>(existingPaths);
}
@@ -463,38 +468,54 @@ internal sealed class TrackRepository : ITrackRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
List<string> pathList = [.. paths];
List<string> pathList = [.. paths.Distinct(StringComparer.Ordinal)];
if (pathList.Count == 0)
return Result.Updated;
// A scan can change more paths and reach more tracks than the storage medium accepts as the parameters of a single statement, so every lookup
// and every update is split into bounded chunks, keeping the whole operation within the parameter limit regardless of the library size.
const int LOOKUP_CHUNK_SIZE = 20_000;
// The tracks stored at the changed paths are reset, together with the albums and the artists they belong to, because the metadata of the whole release is re-evaluated.
List<Guid> trackIds = await _luminaDbContext.Tracks
.Where(track => track.LibraryId == libraryId && pathList.Contains(track.Path))
.Select(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> trackIds = [];
foreach (string[] chunk in pathList.Chunk(LOOKUP_CHUNK_SIZE))
trackIds.AddRange(await _luminaDbContext.Tracks
.Where(track => track.LibraryId == libraryId && chunk.Contains(track.Path))
.Select(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false));
if (trackIds.Count == 0)
return Result.Updated;
List<Guid> albumIds = await _luminaDbContext.Tracks
.Where(track => trackIds.Contains(track.Id))
.Select(track => track.AlbumId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> artistIds = await _luminaDbContext.Albums
.Where(album => albumIds.Contains(album.Id))
.Select(album => album.ArtistId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false);
HashSet<Guid> albumIdSet = [];
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
albumIdSet.UnionWith(await _luminaDbContext.Tracks
.Where(track => chunk.Contains(track.Id))
.Select(track => track.AlbumId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false));
List<Guid> albumIds = [.. albumIdSet];
await _luminaDbContext.Tracks
.Where(track => trackIds.Contains(track.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
await _luminaDbContext.Albums
.Where(album => albumIds.Contains(album.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
await _luminaDbContext.Artists
.Where(artist => artistIds.Contains(artist.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
HashSet<Guid> artistIdSet = [];
foreach (Guid[] chunk in albumIds.Chunk(LOOKUP_CHUNK_SIZE))
artistIdSet.UnionWith(await _luminaDbContext.Albums
.Where(album => chunk.Contains(album.Id))
.Select(album => album.ArtistId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false));
List<Guid> artistIds = [.. artistIdSet];
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
await _luminaDbContext.Tracks
.Where(track => chunk.Contains(track.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
foreach (Guid[] chunk in albumIds.Chunk(LOOKUP_CHUNK_SIZE))
await _luminaDbContext.Albums
.Where(album => chunk.Contains(album.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
foreach (Guid[] chunk in artistIds.Chunk(LOOKUP_CHUNK_SIZE))
await _luminaDbContext.Artists
.Where(artist => chunk.Contains(artist.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
@@ -63,13 +63,21 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
/// <param name="paths">The file system paths of the media library scan snapshot.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken)
public async Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlySet<string> paths, CancellationToken cancellationToken)
{
// The staged metadata of the scan holds everything needed to materialize the music library items, grouped by artist and by release.
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> getStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.GetByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
// The staged metadata of the media library holds everything needed to materialize the music library items, grouped by artist and by release.
// It is read for the whole library, so the metadata that a failed earlier scan left behind is reused for the files that are still in the current
// snapshot, allowing a retried scan to complete without extracting the metadata of the whole library again. The metadata of the current scan wins
// over the metadata of an earlier scan for the same path, and the snapshot filters out the files that were deleted in the meantime.
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> getStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getStagedMetadataResult.IsFailure)
return getStagedMetadataResult.Errors;
IReadOnlyList<MusicLibraryScanItemMetadataEntity> stagedMetadata = getStagedMetadataResult.Value;
Dictionary<string, MusicLibraryScanItemMetadataEntity> stagedMetadataByPath = new(StringComparer.Ordinal);
foreach (MusicLibraryScanItemMetadataEntity stagedItem in getStagedMetadataResult.Value)
if (!stagedMetadataByPath.TryGetValue(stagedItem.Path, out _) || stagedItem.LibraryScanId == scanId)
stagedMetadataByPath[stagedItem.Path] = stagedItem;
List<MusicLibraryScanItemMetadataEntity> stagedMetadata = [.. stagedMetadataByPath.Values.Where(stagedItem => paths.Contains(stagedItem.Path))];
if (stagedMetadata.Count == 0)
return Result.Success;
@@ -171,14 +179,23 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
}
}
// The staged metadata of the scan was consumed, so it is removed, keeping the storage medium bounded across scans.
Result<Deleted> deleteStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
if (deleteStagedMetadataResult.IsFailure)
return deleteStagedMetadataResult.Errors;
return Result.Success;
}
/// <summary>
/// Clears the data that the media library scan staged for the media library, after its items were successfully saved.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose staged data is cleared.</param>
/// <param name="scanId">The Id of the media library scan whose staged data is cleared.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> ClearStagedDataAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, CancellationToken cancellationToken)
{
// The delete covers the whole library, so the staged metadata that an earlier failed scan of the same library left behind is discarded as well.
return await unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resets the metadata enrichment status of all the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
@@ -36,10 +36,20 @@ internal interface IMediaLibraryScanItemMaterializer
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are materialized.</param>
/// <param name="scanId">The Id of the media library scan whose results are materialized.</param>
/// <param name="paths">The file system paths of the media library scan snapshot.</param>
/// <param name="paths">The set of file system paths of the media library scan snapshot.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken);
Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlySet<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Clears the data that the media library scan staged for the media library, after its items were successfully saved.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose staged data is cleared.</param>
/// <param name="scanId">The Id of the media library scan whose staged data is cleared.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> ClearStagedDataAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Resets the metadata enrichment status of all the media library items of the media library identified by <paramref name="libraryId"/>.
@@ -113,7 +113,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
}
// Materialize the media library items 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);
Result<IReadOnlySet<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
@@ -125,6 +125,11 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
// The staged data is only cleared once the materialized items are safely stored, so a failed save can be retried from the same staged data.
Result<Deleted> clearStagedDataResult = await materializer.ClearStagedDataAsync(unitOfWork, LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
if (clearStagedDataResult.IsFailure)
throw new InvalidOperationException(clearStagedDataResult.FirstError.Description);
// Increment the number of processed elements progress.
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
@@ -68,7 +68,7 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
/// <param name="paths">The file system paths of the media library scan snapshot.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken)
public async Task<Result<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlySet<string> paths, CancellationToken cancellationToken)
{
// The library holds the path template that describes the structure of the library on disk, used to derive the metadata of each book from its path.
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -87,8 +87,7 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
// Books that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its book. The existing paths are
// loaded in a single query, instead of one existence check per path, so that the number of round trips does not scale with the size of the library.
List<string> stagedPaths = [.. paths];
Result<IReadOnlyCollection<string>> getExistingPathsResult = await unitOfWork.BookRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyCollection<string>> getExistingPathsResult = await unitOfWork.BookRepository.GetExistingPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false);
if (getExistingPathsResult.IsFailure)
return getExistingPathsResult.Errors;
HashSet<string> existingPaths = [.. getExistingPathsResult.Value];
@@ -107,6 +106,20 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
return Result.Success;
}
/// <summary>
/// Clears the data that the media library scan staged for the media library, after its items were successfully saved.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose staged data is cleared.</param>
/// <param name="scanId">The Id of the media library scan whose staged data is cleared.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Task<Result<Deleted>> ClearStagedDataAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, CancellationToken cancellationToken)
{
// The books materialize directly from the paths of the snapshot, so they do not stage any data of their own to clear.
return Task.FromResult<Result<Deleted>>(Result.Deleted);
}
/// <summary>
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
@@ -82,6 +82,35 @@ public class BookRepositoryTests
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
}
[Fact]
public async Task GetExistingPathsAsync_WhenMorePathsAreRequestedThanTheStorageAccepts_ShouldReturnTheExistingPaths()
{
// Arrange
// A scan of a very large library stages more paths than SQLite accepts as the parameters of one statement, which used to fail the whole scan.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-existingpaths-large-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Path = "/books/tolkien/the-hobbit.epub";
context.Books.Add(book);
await context.SaveChangesAsync();
List<string> requestedPaths = [.. Enumerable.Range(0, 120_000).Select(index => $"/books/tolkien/book-{index}.epub")];
requestedPaths.Add("/books/tolkien/the-hobbit.epub");
// Act
Result<IReadOnlyCollection<string>> result = await sut.GetExistingPathsAsync(libraryId, requestedPaths, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string existingPath = Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", existingPath);
}
[Fact]
public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary()
{
@@ -102,8 +102,8 @@ public class DirectoryScanFingerprintRepositoryTests : IDisposable
(Guid libraryId, _) = await SeedLibraryGraphAsync();
List<DirectoryScanFingerprintEntity> fingerprints =
[
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId),
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId)
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1"),
_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2")
];
// Act
@@ -36,6 +36,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable
private readonly LibraryScanSnapshotRepository _sut;
private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new();
private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new();
private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
@@ -128,7 +129,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
Result<IReadOnlySet<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -144,7 +145,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable
(_, LibraryEntity library, _) = await SeedScanGraphAsync();
// Act
Result<IReadOnlyList<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
Result<IReadOnlySet<string>> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -224,6 +225,36 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable
Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId));
}
[Fact]
public async Task RollbackSnapshotForScanAsync_WhenCalled_ShouldRemoveOnlyTheSnapshotEntriesTheScanAddedOrModified()
{
// Arrange
(_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync();
LibraryScanSnapshotEntity untouchedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/untouched.epub");
LibraryScanSnapshotEntity newSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/new.epub");
LibraryScanSnapshotEntity modifiedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/modified.epub");
_context.LibraryScanSnapshots.AddRange(untouchedSnapshot, newSnapshot, modifiedSnapshot);
LibraryScanResultEntity newResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.New, path: "/books/new.epub");
LibraryScanResultEntity modifiedResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.Modified, path: "/books/modified.epub");
LibraryScanResultEntity deletedResult = _libraryScanResultEntityFixture.Create(libraryScanId: scanId, status: LibraryScanFileStatus.Deleted, path: "/books/deleted.epub");
_context.LibraryScanResults.AddRange(newResult, modifiedResult, deletedResult);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.RollbackSnapshotForScanAsync(library.Id, scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
List<LibraryScanSnapshotEntity> snapshots = await _context.LibraryScanSnapshots.AsNoTracking()
.Where(snapshot => snapshot.LibraryId == library.Id)
.ToListAsync();
LibraryScanSnapshotEntity remainingSnapshot = Assert.Single(snapshots);
Assert.Equal("/books/untouched.epub", remainingSnapshot.Path);
// The audit results are kept: they describe what the failed scan found, and only the snapshot is rolled back.
Assert.Equal(3, await _context.LibraryScanResults.AsNoTracking().CountAsync(scanResult => scanResult.LibraryScanId == scanId));
}
/// <summary>
/// Seeds the user, media library and media library scan required by the foreign keys of the snapshot and staging tables.
/// </summary>
@@ -99,6 +99,39 @@ public class MusicLibraryScanItemMetadataRepositoryTests : IDisposable
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnAllTheItemsOfTheLibraryOrderedByPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfFirstScan = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: libraryId, libraryScanId: Guid.NewGuid(), path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfSecondScan = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: libraryId, libraryScanId: Guid.NewGuid(), path: "/music/queen/bicycle-race.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherLibrary = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: Guid.NewGuid(), path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfFirstScan, itemOfSecondScan, itemOfAnotherLibrary);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([itemOfSecondScan.Id, itemOfFirstScan.Id], result.Value.Select(item => item.Id));
}
[Fact]
public async Task GetByLibraryIdAsync_WhenNoItemsExistForTheLibrary_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByLibraryIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByScanIdAsync_WhenCalled_ShouldDeleteOnlyTheItemsOfTheScan()
{
@@ -189,6 +189,34 @@ public class TrackRepositoryTests
Assert.Equal("/music/Queen/Love-Of-My-Life.flac", existingPath);
}
[Fact]
public async Task GetExistingPathsAsync_WhenMorePathsAreRequestedThanTheStorageAccepts_ShouldReturnTheExistingPaths()
{
// Arrange
// A scan of a very large library stages more paths than SQLite accepts as the parameters of one statement, which used to fail the whole scan.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-existingpaths-large-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
context.Tracks.Add(track);
await context.SaveChangesAsync();
List<string> requestedPaths = [.. Enumerable.Range(0, 120_000).Select(index => $"/music/queen/track-{index}.flac")];
requestedPaths.Add("/music/queen/bohemian-rhapsody.flac");
// Act
Result<IReadOnlyCollection<string>> result = await sut.GetExistingPathsAsync(libraryId, requestedPaths, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string existingPath = Assert.Single(result.Value);
Assert.Equal("/music/queen/bohemian-rhapsody.flac", existingPath);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
{
@@ -33,6 +33,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository;
private readonly ILibraryScanSnapshotRepository _mockLibraryScanSnapshotRepository;
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
@@ -49,14 +50,18 @@ public class LibraryScanCancelledDomainEventHandlerTests
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
_mockLibraryScanStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockLibraryScanSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository);
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockLibraryScanSnapshotRepository);
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
_mockMediaLibrariesScanProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
_mockMediaLibrariesScanCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
// default stubs: the cancellation service and the staging results clearing succeed
// default stubs: the cancellation service, the snapshot rollback and the staging results clearing succeed
_mockMediaLibraryScanningService.CancelScan(Arg.Any<LibraryScan>()).Returns(Result.Success);
_mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
@@ -81,7 +86,8 @@ public class LibraryScanCancelledDomainEventHandlerTests
_mockMediaLibraryScanningService.Received(1).CancelScan(Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == scan.Id));
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
_mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any<CancellationToken>());
await _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, domainEvent.ScanId.Value, CancellationToken.None);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None);
}
[Fact]
@@ -99,6 +105,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
@@ -139,6 +146,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
_mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any<MediaLibraryScanCompositeId>());
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
@@ -163,4 +171,26 @@ public class LibraryScanCancelledDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
}
[Fact]
public async Task HandleAsync_WhenTheScanTokenIsCanceled_ShouldStillClearTheStagingResults()
{
// Arrange
// Cancelling the scan cancels its own token, so the cleanup must not be skipped because of it.
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
using CancellationTokenSource canceledTokenSource = new();
canceledTokenSource.Cancel();
// Act
await _sut.HandleAsync(domainEvent, canceledTokenSource.Token);
// Assert
await _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, domainEvent.ScanId.Value, CancellationToken.None);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None);
}
}
@@ -34,6 +34,7 @@ public class LibraryScanFailedDomainEventHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository;
private readonly ILibraryScanSnapshotRepository _mockLibraryScanSnapshotRepository;
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
@@ -50,15 +51,19 @@ public class LibraryScanFailedDomainEventHandlerTests
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
_mockLibraryScanStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockLibraryScanSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository);
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockLibraryScanSnapshotRepository);
_mockMediaLibrariesScanProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
_mockMediaLibrariesScanCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
_mockDebouncedLibraryScanProgressNotifier = Substitute.For<IMediaLibraryScanProgressNotifier>();
// default stubs: the library scan update and the staging results clearing succeed
// default stubs: the library scan update, the snapshot rollback and the staging results clearing succeed
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
@@ -85,8 +90,9 @@ public class LibraryScanFailedDomainEventHandlerTests
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(compositeId);
_mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(compositeId);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any<CancellationToken>());
await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, Arg.Any<CancellationToken>());
await _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, scan.Id, CancellationToken.None);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None);
await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
}
[Fact]
@@ -110,8 +116,9 @@ public class LibraryScanFailedDomainEventHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(compositeId);
_mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(compositeId);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any<CancellationToken>());
await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, Arg.Any<CancellationToken>());
await _mockLibraryScanSnapshotRepository.Received(1).RollbackSnapshotForScanAsync(domainEvent.LibraryId.Value, scan.Id, CancellationToken.None);
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None);
await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
}
[Fact]
@@ -129,6 +136,7 @@ public class LibraryScanFailedDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockLibraryScanSnapshotRepository.DidNotReceive().RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
@@ -173,6 +181,31 @@ public class LibraryScanFailedDomainEventHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRollbackSnapshotFails_ShouldThrowEventualConsistencyExceptionAndNotClearTheStagingResults()
{
// Arrange
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to rollback the scan snapshot");
_mockLibraryScanSnapshotRepository.RollbackSnapshotForScanAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDebouncedLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanFailedEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException()
{
@@ -196,4 +229,27 @@ public class LibraryScanFailedDomainEventHandlerTests
Assert.Equal(error, exception.EventualConsistencyError);
await _mockDebouncedLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanFailedEventAsync(Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheScanTokenIsCanceled_ShouldStillClearTheStagingResults()
{
// Arrange
// Releasing the scan resources cancels the scan's own token, so the cleanup must not be skipped because of it.
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
using CancellationTokenSource canceledTokenSource = new();
canceledTokenSource.Cancel();
// Act
await _sut.HandleAsync(domainEvent, canceledTokenSource.Token);
// Assert
await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, CancellationToken.None);
await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
}
}
@@ -62,8 +62,10 @@ public class MusicMediaLibraryScanItemMaterializerTests
.Returns(Result.From(new Created()));
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Deleted()));
_mockStagedMetadataRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockStagedMetadataRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([]));
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('/');
@@ -99,11 +101,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
musicBrainzReleaseArtistId: releaseArtistId,
musicBrainzReleaseId: secondReleaseId,
musicBrainzRecordingId: secondRecordingId);
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
@@ -131,11 +133,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
path: "/music/some-artist/some-release/track.mp3",
includeMusicBrainzTags: false,
includeContainer: false);
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [stagedItem.Path], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
@@ -167,11 +169,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
musicBrainzArtistId: Guid.NewGuid(),
musicBrainzReleaseArtistId: variousArtistsId,
musicBrainzReleaseId: compilationReleaseId);
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
@@ -199,11 +201,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
releaseName: "Shared Release Title",
path: "/music/shared-artist/shared-release/second.mp3",
includeMusicBrainzTags: false);
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
@@ -214,4 +216,57 @@ public class MusicMediaLibraryScanItemMaterializerTests
Assert.Null(album.MusicBrainzReleaseId);
Assert.Equal(2, album.Tracks.Count);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheCurrentScanStagedNothing_ShouldMaterializeTheMetadataLeftBehindByAnEarlierScanForTheCurrentSnapshotPaths()
{
// Arrange
MusicLibraryScanItemMetadataEntity stagedItemInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Recovered Artist",
releaseName: "Recovered Release",
path: "/music/recovered-artist/recovered-release/first.mp3",
includeMusicBrainzTags: false);
MusicLibraryScanItemMetadataEntity stagedItemNoLongerInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Deleted Artist",
releaseName: "Deleted Release",
path: "/music/deleted-artist/deleted-release/deleted.mp3",
includeMusicBrainzTags: false);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItemInSnapshot, stagedItemNoLongerInSnapshot]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItemInSnapshot.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
// The metadata left behind by the earlier scan is reused only for the files that are still in the current snapshot.
ArtistEntity artist = Assert.Single(_insertedArtists);
Assert.Equal("Recovered Artist", artist.Name);
AlbumEntity album = Assert.Single(artist.Albums);
Assert.Equal(stagedItemInSnapshot.Path, Assert.Single(album.Tracks).Path);
}
[Fact]
public async Task ClearStagedDataAsync_WhenCalled_ShouldDeleteTheStagedMetadataOfTheWholeLibrary()
{
// Act
Result<Deleted> result = await _sut.ClearStagedDataAsync(_mockUnitOfWork, _libraryId, _scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await _mockStagedMetadataRepository.Received(1).DeleteByLibraryIdAsync(_libraryId, CancellationToken.None);
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the media library scan produces.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}
@@ -128,7 +128,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf", "book2.pdf"]));
.Returns(Result.From(CreatePathSet("book1.pdf", "book2.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
@@ -159,7 +159,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
@@ -184,7 +184,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
@@ -207,7 +207,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["existing.pdf"]));
.Returns(Result.From(CreatePathSet("existing.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>(["existing.pdf"]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
@@ -354,7 +354,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
.Returns(Result.From(CreatePathSet("book1.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the existing paths"));
@@ -380,7 +380,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
.Returns(Result.From(CreatePathSet("book1.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
@@ -407,7 +407,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
@@ -436,7 +436,7 @@ public class MediaLibraryScanResultsSaveJobTests
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["_.pdf"]));
.Returns(Result.From(CreatePathSet("_.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
@@ -451,4 +451,14 @@ public class MediaLibraryScanResultsSaveJobTests
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the snapshot repository returns.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}
@@ -79,7 +79,7 @@ public class BooksMediaLibraryScanItemMaterializerTests
_mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub");
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\MusicBackup\\track.epub"), CancellationToken.None);
// Assert
// A sibling directory whose name only starts with the content location name is not inside the library, so the item is not parsed against
@@ -99,11 +99,21 @@ public class BooksMediaLibraryScanItemMaterializerTests
_mockPathService.IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music").Returns(true);
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\Music\\Artist\\track.epub"], CancellationToken.None);
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\Artist\\track.epub"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music");
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "Artist\\track.epub", '\\');
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the media library scan produces.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}