From 45c1d1bd44ea6e4ea6720dfcdde1ad80a4c4f5b3 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 30 Oct 2026 22:40:41 +0200 Subject: [PATCH] Covers the SSD content setting with tests Adds domain, mapping, endpoint, persistence, discovery, and hashing coverage, including parallel and sequential read behavior. --- .../Management/LibraryEntityFixture.cs | 3 + .../AddLibrary/AddLibraryCommandFixture.cs | 4 + .../UpdateLibraryCommandFixture.cs | 4 + .../Management/AddLibraryRequestFixture.cs | 3 + .../Management/UpdateLibraryRequestFixture.cs | 3 + .../Management/LibraryResponseFixture.cs | 3 + .../LibraryAggregate/LibraryFixture.cs | 4 + .../Libraries/LibraryRepositoryTests.cs | 25 ++++++ .../Books/BooksFileSystemDiscoveryJobTests.cs | 5 +- .../Core/Security/FileHashServiceTests.cs | 46 ++++++++-- .../AddMediaLibraryRequestMappingTests.cs | 2 + .../Management/LibraryEntityMappingTests.cs | 6 +- .../Management/LibraryMappingTests.cs | 1 + .../UpdateLibraryRequestMappingTests.cs | 2 + .../LibraryConfigurationTests.cs | 18 ++++ .../LibraryAggregate/LibraryTests.cs | 6 ++ .../Music/MusicFileSystemDiscoveryJobTests.cs | 69 ++++++++++++++- .../Common/MediaLibraryScanHashJobTests.cs | 80 +++++++++++++++-- .../Books/BooksFileSystemDiscoveryJobTests.cs | 88 ++++++++++++++++++- .../AddLibrary/AddLibraryEndpointTests.cs | 2 + .../UpdateLibraryEndpointTests.cs | 2 + 21 files changed, 354 insertions(+), 22 deletions(-) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index 8f2d84cc..33455760 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -33,6 +33,7 @@ public class LibraryEntityFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Whether the content of the media library is stored on a solid state drive. /// Whether the consumption progress of the media library items is tracked. /// The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The fingerprint of the metadata provider configuration of the media library. @@ -52,6 +53,7 @@ public class LibraryEntityFixture bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false, + bool isContentOnSsd = false, bool shouldTrackConsumptionProgress = false, int? completionThresholdPercentage = null, string? metadataProvidersConfigurationFingerprint = null, @@ -75,6 +77,7 @@ public class LibraryEntityFixture CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, + IsContentOnSsd = isContentOnSsd, ShouldTrackConsumptionProgress = shouldTrackConsumptionProgress, CompletionThresholdPercentage = completionThresholdPercentage, MetadataProvidersConfigurationFingerprint = metadataProvidersConfigurationFingerprint, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs index d79c7a77..f773e3b5 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs @@ -28,6 +28,7 @@ public class AddLibraryCommandFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Whether the content of the media library is stored on a solid state drive. /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. @@ -42,6 +43,7 @@ public class AddLibraryCommandFixture bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false, + bool isContentOnSsd = false, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, LibraryPathTemplatePartDto[]? pathTemplateParts = null) @@ -57,6 +59,7 @@ public class AddLibraryCommandFixture true, true, false, + false, shouldTrackConsumptionProgress, completionThresholdPercentage, null @@ -70,6 +73,7 @@ public class AddLibraryCommandFixture .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) + .RuleFor(x => x.IsContentOnSsd, isContentOnSsd) .RuleFor(x => x.PathTemplateParts, pathTemplateParts) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs index 8e46d17e..84bb39e0 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs @@ -31,6 +31,7 @@ public class UpdateLibraryCommandFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Whether the content of the media library is stored on a solid state drive. /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. @@ -47,6 +48,7 @@ public class UpdateLibraryCommandFixture bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false, + bool isContentOnSsd = false, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, LibraryPathTemplatePartDto[]? pathTemplateParts = null) @@ -64,6 +66,7 @@ public class UpdateLibraryCommandFixture true, true, false, + false, shouldTrackConsumptionProgress, completionThresholdPercentage, null @@ -79,6 +82,7 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) + .RuleFor(x => x.IsContentOnSsd, isContentOnSsd) .RuleFor(x => x.PathTemplateParts, pathTemplateParts) .Generate(); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index e4028f25..c705b5a7 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -28,6 +28,7 @@ public class AddLibraryRequestFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. Whether the content of the media library is stored on a solid state drive. /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. @@ -42,6 +43,7 @@ public class AddLibraryRequestFixture bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, + bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, LibraryPathTemplatePartRequest[]? pathTemplateParts = null) @@ -56,6 +58,7 @@ public class AddLibraryRequestFixture canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, pathTemplateParts diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index 289ebfd7..44208473 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -31,6 +31,7 @@ public class UpdateLibraryRequestFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. Whether the content of the media library is stored on a solid state drive. /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. @@ -47,6 +48,7 @@ public class UpdateLibraryRequestFixture bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, + bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, LibraryPathTemplatePartRequest[]? pathTemplateParts = null) @@ -63,6 +65,7 @@ public class UpdateLibraryRequestFixture canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, pathTemplateParts diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs index d1dcb2dd..f90ad79c 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs @@ -32,6 +32,7 @@ public class LibraryResponseFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. Whether the content of the media library is stored on a solid state drive. /// Optional. Whether the consumption progress of the media library items is tracked. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. @@ -50,6 +51,7 @@ public class LibraryResponseFixture bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, + bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, List? pathTemplateParts = null, @@ -70,6 +72,7 @@ public class LibraryResponseFixture canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + isContentOnSsd ?? false, resolvedShouldTrackConsumptionProgress, resolvedCompletionThresholdPercentage, pathTemplateParts ?? [], diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs index e1d9489b..949d8c20 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -43,6 +43,7 @@ public class LibraryFixture /// Whether metadata download from the web is enabled. /// Whether metadata should be saved in the media directories. /// Whether unchanged directories should be skipped during scan. + /// Whether the content of the library is stored on a solid state drive. /// Optional. The consumption settings of the library. /// Optional. The scan Ids associated with the library. /// Optional. The path template of the library. @@ -60,6 +61,7 @@ public class LibraryFixture bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = false, bool shouldSkipUnchangedDirectoriesDuringScan = false, + bool isContentOnSsd = false, LibraryConsumptionSettings? consumptionSettings = null, IEnumerable? scanIds = null, LibraryPathTemplate? pathTemplate = null, @@ -91,6 +93,7 @@ public class LibraryFixture canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + isContentOnSsd, resolvedConsumptionSettings, pathTemplate ?? LibraryPathTemplate.Empty(), resolvedScanIds @@ -107,6 +110,7 @@ public class LibraryFixture canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + isContentOnSsd, resolvedConsumptionSettings, pathTemplate ?? LibraryPathTemplate.Empty(), resolvedScanIds diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs index 8fb7b783..86f95e34 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -148,6 +148,31 @@ public class LibraryRepositoryTests Assert.Null(storedLibrary.CompletionThresholdPercentage); } + [Fact] + public async Task InsertAsync_WhenLibraryContentIsOnSsd_ShouldPersistTheSetting() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-ssd-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + LibraryRepository sut = new(context); + context.Users.Add(_userEntityFixture.Create(id: userId)); + LibraryEntity library = _libraryEntityFixture.Create(userId: userId, isContentOnSsd: true, contentLocations: []); + + // Act + Result result = await sut.InsertAsync(library, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id); + Assert.NotNull(storedLibrary); + Assert.True(storedLibrary!.IsContentOnSsd); + } + [Fact] public async Task UpdateAsync_WhenConsumptionSettingsAreEnabled_ShouldPersistTheTrackingAndThreshold() { diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs index cdd3a0e8..f63063e6 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -81,7 +81,7 @@ public class BooksFileSystemDiscoveryJobTests _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory) + _sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, Substitute.For>()) { ScanId = _scanId, UserId = _userId, @@ -105,7 +105,8 @@ public class BooksFileSystemDiscoveryJobTests title: "Test Library", libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], - shouldSkipUnchangedDirectoriesDuringScan: false); + shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: true); _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs index bdd99113..88795640 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs @@ -40,6 +40,7 @@ public class FileHashServiceTests // Act List result = await _sut.HashFilesAsync( inputFiles, + shouldParallelizeReads: true, () => { callbackInvocationCount++; @@ -66,7 +67,7 @@ public class FileHashServiceTests List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; // Act - List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + List result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); // Assert HashedFileSystemFileDto hashedFile = Assert.Single(result); @@ -83,10 +84,10 @@ public class FileHashServiceTests List firstInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; // Act - List firstResult = await _sut.HashFilesAsync(firstInputFiles, () => Task.CompletedTask, CancellationToken.None); + List firstResult = await _sut.HashFilesAsync(firstInputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); await File.WriteAllTextAsync(filePath, "changed content"); List secondInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; - List secondResult = await _sut.HashFilesAsync(secondInputFiles, () => Task.CompletedTask, CancellationToken.None); + List secondResult = await _sut.HashFilesAsync(secondInputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); // Assert Assert.NotEqual(firstResult[0].CurrentHash, secondResult[0].CurrentHash); @@ -100,7 +101,7 @@ public class FileHashServiceTests List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: nonExistentFilePath, size: 100, currentHash: 0, oldHash: 0, ticks: 0)]; // Act - List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + List result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); // Assert Assert.Empty(result); @@ -119,7 +120,7 @@ public class FileHashServiceTests ]; // Act - List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + List result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); // Assert HashedFileSystemFileDto hashedFile = Assert.Single(result); @@ -127,6 +128,37 @@ public class FileHashServiceTests Assert.NotEqual(0UL, hashedFile.CurrentHash); } + [Fact] + public async Task HashFilesAsync_WhenReadsAreNotParallelized_ShouldHashAllFilesSequentially() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath1 = temporaryTestDirectory.CreateFile("book1.pdf", "content of the first book"); + string filePath2 = temporaryTestDirectory.CreateFile("book2.pdf", "content of the second book"); + List inputFiles = + [ + _hashedFileSystemFileDtoFixture.Create(path: filePath1, size: new FileInfo(filePath1).Length, currentHash: 0, oldHash: 0, ticks: 0), + _hashedFileSystemFileDtoFixture.Create(path: filePath2, size: new FileInfo(filePath2).Length, currentHash: 0, oldHash: 0, ticks: 0) + ]; + int callbackInvocationCount = 0; + + // Act + List result = await _sut.HashFilesAsync( + inputFiles, + shouldParallelizeReads: false, + () => + { + callbackInvocationCount++; + return Task.CompletedTask; + }, + CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(2, callbackInvocationCount); + Assert.All(result, file => Assert.NotEqual(0UL, file.CurrentHash)); + } + [Fact] public async Task HashFilesAsync_WhenCancellationRequested_ShouldCancelOperation() { @@ -138,7 +170,7 @@ public class FileHashServiceTests cancellationTokenSource.Cancel(); // Act - Task> operation = _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, cancellationTokenSource.Token); + Task> operation = _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, cancellationTokenSource.Token); // Assert await Assert.ThrowsAnyAsync(() => operation); @@ -182,7 +214,7 @@ public class FileHashServiceTests List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; // Act - List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + List result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None); // Assert HashedFileSystemFileDto hashedFile = Assert.Single(result); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index e351c41c..427a8c83 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -32,6 +32,7 @@ public class AddMediaLibraryRequestMappingTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: true, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 90 ); @@ -49,6 +50,7 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.IsLocked, result.IsLocked); Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); + Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd); Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress); Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs index a4957fe7..e3c122de 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -32,7 +32,8 @@ public class LibraryEntityMappingTests title: "My Library", libraryType: LibraryType.Book, contentLocations: ["C:/Books", "D:/Media/Books"], - coverImage: "D:/myPoster.jpg"); + coverImage: "D:/myPoster.jpg", + isContentOnSsd: true); // Act LibraryResponse result = entity.ToResponse(); @@ -45,6 +46,7 @@ public class LibraryEntityMappingTests Assert.Equal(entity.LibraryType, result.LibraryType); Assert.Equal(entity.ContentLocations.Select(l => l.Path), result.ContentLocations); Assert.Equal(entity.CoverImage, result.CoverImage); + Assert.Equal(entity.IsContentOnSsd, result.IsContentOnSsd); Assert.Equal(entity.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress); Assert.Equal(entity.CompletionThresholdPercentage, result.CompletionThresholdPercentage); Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc); @@ -188,6 +190,7 @@ public class LibraryEntityMappingTests libraryType: LibraryType.Book, contentLocations: ["C:/Books"], coverImage: "D:/cover.jpg", + isContentOnSsd: true, pathTemplateParts: [firstPart, secondPart]); // Act @@ -200,6 +203,7 @@ public class LibraryEntityMappingTests Assert.Equal(entity.Title, result.Value.Title); Assert.Equal(entity.LibraryType, result.Value.LibraryType); Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value); + Assert.Equal(entity.IsContentOnSsd, result.Value.IsContentOnSsd); Assert.Equal(entity.ShouldTrackConsumptionProgress, result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress); Assert.Equal(entity.CompletionThresholdPercentage, result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? result.Value.ConsumptionSettings.CompletionThresholdPercentage.Value : null); Assert.Equal(2, result.Value.PathTemplate.Parts.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 6bb3f6a8..b7d84932 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -60,6 +60,7 @@ public class LibraryMappingTests Assert.False(result.IsLocked); Assert.True(result.CanDownloadMetadataFromWeb); Assert.False(result.ShouldSaveMetadataInMediaDirectories); + Assert.Equal(library.IsContentOnSsd, result.IsContentOnSsd); Assert.Equal(library.ConsumptionSettings.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress); Assert.Equal(library.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? library.ConsumptionSettings.CompletionThresholdPercentage.Value : null, result.CompletionThresholdPercentage); Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs index 96d39b4b..9675c2b9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -32,6 +32,7 @@ public class UpdateLibraryRequestMappingTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: true, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 90); @@ -49,6 +50,7 @@ public class UpdateLibraryRequestMappingTests Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan); + Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd); Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress); Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs index 0dbca57b..440b7bc7 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -62,6 +62,7 @@ public class LibraryConfigurationTests IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb)); IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress)); IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage)); + IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd)); // Assert Assert.False(titleProperty.IsNullable); @@ -76,6 +77,23 @@ public class LibraryConfigurationTests Assert.Equal(typeof(int?), completionThresholdPercentageProperty.ClrType); Assert.True(completionThresholdPercentageProperty.IsNullable); Assert.Null(completionThresholdPercentageProperty.GetDefaultValue()); + Assert.Equal(typeof(bool), isContentOnSsdProperty.ClrType); + Assert.False(isContentOnSsdProperty.IsNullable); + Assert.Equal(false, isContentOnSsdProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureSsdContentColumnOrder() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!; + + // Act + IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd)); + + // Assert + Assert.Equal(18, isContentOnSsdProperty.GetColumnOrder()); + Assert.Equal(nameof(LibraryEntity.IsContentOnSsd), isContentOnSsdProperty.GetColumnName()); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index bd183108..32f879d2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -56,6 +56,7 @@ public class LibraryTests canDownloadMetadataFromWeb: false, shouldSaveMetadataInMediaDirectories: true, shouldSkipUnchangedDirectoriesDuringScan: true, + isContentOnSsd: true, consumptionSettings, LibraryPathTemplate.Empty(), scanIds); @@ -73,6 +74,7 @@ public class LibraryTests Assert.False(result.Value.CanDownloadMetadataFromWeb); Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories); Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan); + Assert.True(result.Value.IsContentOnSsd); Assert.Equal(consumptionSettings, result.Value.ConsumptionSettings); Assert.Equal(scanIds, result.Value.ScanIds); } @@ -97,6 +99,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: false, _libraryConsumptionSettingsFixture.Create(), LibraryPathTemplate.Empty(), scanIds); @@ -125,6 +128,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: false, _libraryConsumptionSettingsFixture.Create(), LibraryPathTemplate.Empty(), []); @@ -162,6 +166,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: false, _libraryConsumptionSettingsFixture.Create(), LibraryPathTemplate.Empty(), []); @@ -191,6 +196,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + isContentOnSsd: false, _libraryConsumptionSettingsFixture.Create(), LibraryPathTemplate.Empty(), []); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs index 00981ae7..a89be224 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs @@ -19,10 +19,12 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.U using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -38,6 +40,7 @@ public class MusicFileSystemDiscoveryJobTests { private const string ROOT_PATH = @"C:\Music"; private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3"; + private const string SECOND_AUDIO_FILE_PATH = @"C:\Music\other.mp3"; private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg"; private readonly IServiceScopeFactory _mockServiceScopeFactory; @@ -50,6 +53,7 @@ public class MusicFileSystemDiscoveryJobTests private readonly IFileProviderService _mockFileProviderService; private readonly IDirectoryProviderService _mockDirectoryProviderService; private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; private readonly MusicFileSystemDiscoveryJob _sut; private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new(); @@ -101,7 +105,9 @@ public class MusicFileSystemDiscoveryJobTests _libraryId = _libraryIdFixture.Create(); _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); - _sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory) + _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); + _sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger) { ScanId = _scanId, UserId = _userId, @@ -182,6 +188,45 @@ public class MusicFileSystemDiscoveryJobTests Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldReadInParallelAndSkipFilesThatBecomeInaccessible() + { + // Arrange + SetupLibrary(isContentOnSsd: true); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, SECOND_AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Is(path => path.Path == AUDIO_FILE_PATH)) + .Returns(_ => throw new IOException("The file vanished between enumeration and processing")); + _mockFileProviderService.GetSize(Arg.Is(path => path.Path == SECOND_AUDIO_FILE_PATH)).Returns(Result.From(1234L)); + _mockFileProviderService.GetLastWriteTime(Arg.Is(path => path.Path == SECOND_AUDIO_FILE_PATH)) + .Returns(Result.From(Optional.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // The sequential path does not catch per-file IO exceptions, so completing here proves the parallel path was taken. + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().Path == SECOND_AUDIO_FILE_PATH + && entities.First().Size == 1234 + && entities.First().LibraryScanId == _scanId.Value + && entities.First().NeedsRehash), + Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Debug, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)), + Arg.Any(), + Arg.Any>()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains(AUDIO_FILE_PATH, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt() { @@ -301,6 +346,22 @@ public class MusicFileSystemDiscoveryJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenAFileMetadataReadThrowsAnUnexpectedException_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(isContentOnSsd: true); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Any()).Returns(_ => throw new InvalidOperationException("Unexpected defect")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + [Fact] public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed() { @@ -342,13 +403,15 @@ public class MusicFileSystemDiscoveryJobTests /// Stubs the media library reader with a library whose single content location is the test root path. /// /// Whether the library skips the directories that have not changed since the last scan. - private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false) + /// Whether the content of the library is stored on a solid state drive. + private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool isContentOnSsd = false) { LibraryEntity library = _libraryEntityFixture.Create( id: _libraryId.Value, libraryType: LibraryType.Music, contentLocations: [ROOT_PATH], - shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan); + shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan, + isContentOnSsd: isContentOnSsd); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(library)); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs index 8630e88d..3934edea 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; @@ -13,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; @@ -38,6 +40,7 @@ public class MediaLibraryScanHashJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; private readonly IDomainEventPublisher _mockDomainEventPublisher; private readonly IFileHashService _mockFileHashService; @@ -46,6 +49,7 @@ public class MediaLibraryScanHashJobTests private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -63,7 +67,9 @@ public class MediaLibraryScanHashJobTests _mockUnitOfWork = Substitute.For(); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); @@ -84,6 +90,9 @@ public class MediaLibraryScanHashJobTests UserId = _userId, LibraryId = _libraryId }; + + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: true))); } [Fact] @@ -97,7 +106,7 @@ public class MediaLibraryScanHashJobTests .Returns( Result.From>(filesToHash), Result.From>([])); - _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()) .Returns(callInfo => Task.FromResult(callInfo.Arg>() .Select(file => file with { CurrentHash = 42UL }) .ToList())); @@ -111,6 +120,7 @@ public class MediaLibraryScanHashJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); await _mockFileHashService.Received(1).HashFilesAsync( Arg.Any>(), + Arg.Is(shouldParallelizeReads => shouldParallelizeReads), Arg.Any>(), Arg.Any()); await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync( @@ -120,6 +130,59 @@ public class MediaLibraryScanHashJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenLibraryIsNotOnSsd_ShouldHashTheFilesSequentially() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: false))); + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(filesToHash), + Result.From>([])); + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(callInfo => Task.FromResult(callInfo.Arg>() + .Select(file => file with { CurrentHash = 42UL }) + .ToList())); + _mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockFileHashService.Received(1).HashFilesAsync( + Arg.Any>(), + Arg.Is(shouldParallelizeReads => !shouldParallelizeReads), + Arg.Any>(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + [Fact] public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing() { @@ -134,7 +197,8 @@ public class MediaLibraryScanHashJobTests // Assert Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()); await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any(), Arg.Any>(), Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); } @@ -151,7 +215,7 @@ public class MediaLibraryScanHashJobTests // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId @@ -187,7 +251,7 @@ public class MediaLibraryScanHashJobTests // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId @@ -205,7 +269,7 @@ public class MediaLibraryScanHashJobTests .Returns( Result.From>(filesToHash), Result.From>([])); - _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()) .Returns(callInfo => Task.FromResult(callInfo.Arg>() .Select(file => file with { CurrentHash = 42UL }) .ToList())); @@ -217,7 +281,7 @@ public class MediaLibraryScanHashJobTests // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId @@ -235,7 +299,7 @@ public class MediaLibraryScanHashJobTests .Returns( Result.From>(filesToHash), Result.From>([])); - _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()) .Returns(async callInfo => { await callInfo.Arg>()(); @@ -268,7 +332,7 @@ public class MediaLibraryScanHashJobTests .Returns( Result.From>(filesToHash), Result.From>([])); - _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any(), Arg.Any>(), Arg.Any()) .Returns(async callInfo => { await Task.Delay(150); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs index 665e6cd0..c313f6f3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; @@ -15,10 +16,13 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.U using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -38,7 +42,9 @@ public class BooksFileSystemDiscoveryJobTests private readonly ILibraryRepository _mockLibraryRepository; private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; private readonly BooksFileSystemDiscoveryJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); @@ -73,7 +79,9 @@ public class BooksFileSystemDiscoveryJobTests _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory) + _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); + _sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger) { ScanId = _scanId, UserId = _userId, @@ -130,4 +138,82 @@ public class BooksFileSystemDiscoveryJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldLogThatTheFileSystemReadsRunInParallel() + { + // Arrange + string temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-books-ssd-{Guid.NewGuid()}"); + Directory.CreateDirectory(temporaryDirectoryPath); + File.WriteAllText(Path.Combine(temporaryDirectoryPath, "book.pdf"), "book content"); + try + { + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + libraryType: LibraryType.Book, + contentLocations: [temporaryDirectoryPath], + isContentOnSsd: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Created)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && Path.GetFileName(entities.First().Path) == "book.pdf"), + Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Debug, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)), + Arg.Any(), + Arg.Any>()); + } + finally + { + Directory.Delete(temporaryDirectoryPath, recursive: true); + } + } + + [Fact] + public async Task StageFilesInParallelAsync_WhenAFileVanishesBeforeItsMetadataIsRead_ShouldSkipItAndLogAWarning() + { + // Arrange + FileInfo vanishedFile = new(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(), "vanished.pdf")); + List stagingBatch = []; + + // Act + await _sut.StageFilesInParallelAsync([vanishedFile], stagingBatch, _mockStagingResultsRepository, CancellationToken.None); + + // Assert + Assert.Empty(stagingBatch); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("vanished.pdf", StringComparison.Ordinal)), + Arg.Any(), + Arg.Any>()); + } + + [Fact] + public async Task StageFilesInParallelAsync_WhenAFileReadThrowsAnUnexpectedException_ShouldRethrowTheRealCause() + { + // Arrange + List stagingBatch = []; + List files = [null!]; + + // Act + Exception exception = await Assert.ThrowsAsync(() => + _sut.StageFilesInParallelAsync(files, stagingBatch, _mockStagingResultsRepository, CancellationToken.None)); + + // Assert + // Parallel.For wraps the body exception in an AggregateException, which would otherwise be reported as "One or more errors occurred.". + Assert.IsType(exception); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index c9712bca..6c2f6de8 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -87,6 +87,7 @@ public class AddLibraryEndpointTests { // Arrange AddLibraryRequest request = _addLibraryRequestFixture.Create( + isContentOnSsd: true, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 65); CancellationToken cancellationToken = CancellationToken.None; @@ -108,6 +109,7 @@ public class AddLibraryEndpointTests command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb && command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan && + command.IsContentOnSsd == request.IsContentOnSsd && command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress && command.CompletionThresholdPercentage == request.CompletionThresholdPercentage), Arg.Is(cancellationToken)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index dd90a0f8..ee1570b5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -87,6 +87,7 @@ public class UpdateLibraryEndpointTests { // Arrange UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + isContentOnSsd: true, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 65); CancellationToken cancellationToken = CancellationToken.None; @@ -110,6 +111,7 @@ public class UpdateLibraryEndpointTests command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb && command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan && + command.IsContentOnSsd == request.IsContentOnSsd && command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress && command.CompletionThresholdPercentage == request.CompletionThresholdPercentage), Arg.Is(cancellationToken));