diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs index a840329e..09478ec1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs @@ -96,7 +96,8 @@ internal sealed class TranscodingCacheLeaseStream : Stream /// The number of bytes read. public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); + // The memory based overload is the one the inner stream should implement, so the array overload only adapts to it. + return _innerStream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); } /// @@ -160,7 +161,8 @@ internal sealed class TranscodingCacheLeaseStream : Stream /// A task that represents the asynchronous write operation. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); + // The memory based overload is the one the inner stream should implement, so the array overload only adapts to it. + return _innerStream.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); } /// diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs new file mode 100644 index 00000000..c8a4087a --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional file name or path of the ffmpeg binary. + /// Optional maximum number of normalization jobs that may run at the same time. + /// Optional maximum number of normalization jobs a single user may have running at the same time. + /// Optional maximum total size of the normalized audio cache, in bytes. + /// Optional maximum duration of a single normalization job, in seconds. + /// Optional period during which a cache entry is protected from eviction, in seconds. + /// + /// Optional directory where normalized audio is cached. When it is not supplied, a generated directory is used. When + /// is , the property stays , which makes the pipeline use the + /// default temporary directory. + /// + /// Whether to generate the optional cache directory, defaulting to . + /// A configured instance. + public TranscodingSettingsDto Create( + string? ffmpegPath = null, + int? maxConcurrentJobs = null, + int? maxConcurrentJobsPerUser = null, + long? maxCacheBytes = null, + int? jobTimeoutSeconds = null, + int? evictionGraceSeconds = null, + string? cacheDirectory = null, + bool includeCacheDirectory = true) + { + return new TranscodingSettingsDto + { + FfmpegPath = ffmpegPath ?? _faker.System.FileName("exe"), + MaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16), + MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, 8), + MaxCacheBytes = maxCacheBytes ?? _faker.Random.Long(1_000_000_000, 8_589_934_592), + JobTimeoutSeconds = jobTimeoutSeconds ?? _faker.Random.Int(60, 3600), + EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(0, 600), + CacheDirectory = includeCacheDirectory ? cacheDirectory ?? _faker.System.DirectoryPath() : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDtoFixture.cs new file mode 100644 index 00000000..33ec5ba8 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDtoFixture.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class NormalizedTrackIndexDtoFixture +{ + private readonly Faker _faker = new(); + private readonly NormalizedTrackSegmentIndexDtoFixture _normalizedTrackSegmentIndexDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional version of the index layout. + /// Optional Id of the track the cached audio belongs to. + /// Optional way the audio is delivered. + /// Optional container of the delivered audio. + /// Optional codec of the delivered audio. + /// Optional duration of each segment, in seconds. + /// Optional duration of the produced and cached audio, in seconds. + /// + /// Optional segments that make up the delivered audio, in playback order. A caller can supply an explicit list, including an empty one; when it is not + /// supplied a random bounded list is generated. + /// + /// The created . + public NormalizedTrackIndexDto Create( + int? version = null, + Guid? trackId = null, + PlaybackDeliveryMode? mode = null, + string? container = null, + string? codec = null, + int? segmentDurationSeconds = null, + int? durationInSeconds = null, + IReadOnlyList? segments = null) + { + return new NormalizedTrackIndexDto( + version ?? _faker.Random.Int(1, 10), + trackId ?? _faker.Random.Guid(), + mode ?? _faker.PickRandom(PlaybackDeliveryMode.DirectPlay, PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode), + container ?? _faker.PickRandom("MP4", "OGG", "WAV", "FLAC"), + codec ?? _faker.PickRandom("AAC", "VORBIS", "PCM", "FLAC"), + segmentDurationSeconds ?? _faker.Random.Int(1, 60), + durationInSeconds ?? _faker.Random.Int(1, 100_000), + segments ?? [.. _normalizedTrackSegmentIndexDtoFixture.CreateMany(_faker.Random.Int(1, 5))] + ); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDtoFixture.cs new file mode 100644 index 00000000..4889dea0 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class NormalizedTrackSegmentIndexDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional zero based position of the segment in the delivered audio. + /// Optional time, in seconds from the start of the track, at which the segment starts. + /// Optional duration of the segment, in seconds. + /// Optional file name of the segment inside the cache entry. + /// Optional length of the segment, in bytes. + /// The created . + public NormalizedTrackSegmentIndexDto Create( + int? index = null, + decimal? startSeconds = null, + decimal? durationSeconds = null, + string? fileName = null, + long? length = null) + { + return new NormalizedTrackSegmentIndexDto( + index ?? _faker.Random.Int(0, 10_000), + startSeconds ?? _faker.Random.Decimal(0m, 100_000m), + durationSeconds ?? _faker.Random.Decimal(1m, 600m), + fileName ?? $"segment{_faker.Random.Int(0, 10_000):D6}{_faker.PickRandom(".m4s", ".mp4", ".ts")}", + length ?? _faker.Random.Long(1, 100_000_000) + ); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(segmentIndex => Create(index: segmentIndex))]; + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Common/Caching/TranscodingCachePathsTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Common/Caching/TranscodingCachePathsTests.cs new file mode 100644 index 00000000..d76ac1c3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Common/Caching/TranscodingCachePathsTests.cs @@ -0,0 +1,438 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Common.Caching; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingCachePathsTests : IDisposable +{ + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public TranscodingCachePathsTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-paths-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Theory] + [InlineData(null)] // no cache directory is configured + [InlineData("")] // an empty cache directory is configured + [InlineData(" ")] // a white space cache directory is configured + public void GetRootDirectory_WhenNoDirectoryIsConfigured_ShouldReturnTheDefaultDirectoryUnderTheTemporaryDirectory(string? configuredDirectory) + { + // Act + string result = TranscodingCachePaths.GetRootDirectory(configuredDirectory); + + // Assert + string directoryName = Path.GetFileName(result); + Assert.Equal(Path.Combine(Path.GetTempPath(), directoryName), result); + Assert.StartsWith(TranscodingCachePaths.DEFAULT_DIRECTORY_NAME + "-", directoryName, StringComparison.Ordinal); + string accountSuffix = directoryName[(TranscodingCachePaths.DEFAULT_DIRECTORY_NAME.Length + 1)..]; + Assert.Matches("^[0-9a-f]{16}$", accountSuffix); + } + + [Fact] + public void GetRootDirectory_WhenCalledRepeatedly_ShouldReturnTheSamePath() + { + // Act + string firstResult = TranscodingCachePaths.GetRootDirectory(null); + string secondResult = TranscodingCachePaths.GetRootDirectory(null); + + // Assert + Assert.Equal(firstResult, secondResult); + } + + [Fact] + public void GetRootDirectory_WhenTheConfiguredDirectoryIsRooted_ShouldReturnItsFullPath() + { + // Arrange + string configuredDirectory = Path.Combine(_temporaryDirectory, "configured-cache"); + + // Act + string result = TranscodingCachePaths.GetRootDirectory($" {configuredDirectory} "); + + // Assert + Assert.Equal(Path.GetFullPath(configuredDirectory), result); + } + + [Fact] + public void GetRootDirectory_WhenTheConfiguredDirectoryIsRelative_ShouldResolveItAgainstTheBaseDirectory() + { + // Arrange + string configuredDirectory = Path.Combine("relative", "cache"); + + // Act + string result = TranscodingCachePaths.GetRootDirectory(configuredDirectory); + + // Assert + Assert.Equal(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, configuredDirectory)), result); + } + + [Fact] + public void HasCacheMarker_WhenTheDirectoryHasNoMarker_ShouldReturnFalse() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "unmarked"); + Directory.CreateDirectory(directoryPath); + + // Act + bool result = TranscodingCachePaths.HasCacheMarker(directoryPath); + + // Assert + Assert.False(result); + } + + [Fact] + public void WriteCacheMarker_WhenTheDirectoryHasNoMarker_ShouldWriteTheDocumentedMarkerFile() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "marked"); + Directory.CreateDirectory(directoryPath); + + // Act + TranscodingCachePaths.WriteCacheMarker(directoryPath); + + // Assert + Assert.Equal(".lumina-transcoding-cache", TranscodingCachePaths.CACHE_MARKER_FILE_NAME); + Assert.True(TranscodingCachePaths.HasCacheMarker(directoryPath)); + Assert.True(File.Exists(Path.Combine(directoryPath, TranscodingCachePaths.CACHE_MARKER_FILE_NAME))); + } + + [Fact] + public void WriteCacheMarker_WhenCalledTwice_ShouldNotRewriteTheMarker() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "already-marked"); + Directory.CreateDirectory(directoryPath); + TranscodingCachePaths.WriteCacheMarker(directoryPath); + string markerPath = Path.Combine(directoryPath, TranscodingCachePaths.CACHE_MARKER_FILE_NAME); + File.WriteAllText(markerPath, "operator content"); + + // Act + TranscodingCachePaths.WriteCacheMarker(directoryPath); + + // Assert + Assert.Equal("operator content", File.ReadAllText(markerPath)); + } + + [Theory] + [InlineData(null)] // no identifier + [InlineData("")] // an empty identifier + [InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")] // 63 characters + [InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0")] // 65 characters + [InlineData("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal characters + [InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg")] // a character that is not hexadecimal + [InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde/")] // a directory separator + public void IsValidCacheId_WhenTheValueIsNotAWellFormedIdentifier_ShouldReturnFalse(string? cacheId) + { + // Act + bool result = TranscodingCachePaths.IsValidCacheId(cacheId!); + + // Assert + Assert.False(result); + } + + [Fact] + public void IsValidCacheId_WhenTheValueIsA64CharacterLowercaseHexIdentifier_ShouldReturnTrue() + { + // Arrange + string cacheId = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + // Act + bool result = TranscodingCachePaths.IsValidCacheId(cacheId); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] // no name + [InlineData("")] // an empty name + [InlineData("segment.m4s")] // an ordinary file name + [InlineData("not-a-cache-entry")] // an ordinary directory name + public void IsCacheEntryName_WhenTheNameIsNotInTheCacheNamespace_ShouldReturnFalse(string? entryName) + { + // Act + bool result = TranscodingCachePaths.IsCacheEntryName(entryName!); + + // Assert + Assert.False(result); + } + + [Theory] + [InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")] // a cache identifier + [InlineData("tmp-0123456789abcdef")] // a temporary directory + [InlineData("del-0123456789abcdef")] // a deletion tombstone + public void IsCacheEntryName_WhenTheNameIsInTheCacheNamespace_ShouldReturnTrue(string entryName) + { + // Act + bool result = TranscodingCachePaths.IsCacheEntryName(entryName); + + // Assert + Assert.True(result); + } + + [Fact] + public void ClearCacheEntries_WhenCalled_ShouldRemoveOnlyCacheEntriesAndKeepTheRoot() + { + // Arrange + string cacheRoot = Path.Combine(_temporaryDirectory, "clear-cache"); + Directory.CreateDirectory(cacheRoot); + string cacheEntryPath = Path.Combine(cacheRoot, CreateCacheId()); + Directory.CreateDirectory(Path.Combine(cacheEntryPath, "nested")); + File.WriteAllText(Path.Combine(cacheEntryPath, "nested", "segment.m4s"), "data"); + string temporaryEntryPath = Path.Combine(cacheRoot, "tmp-0123456789abcdef"); + Directory.CreateDirectory(temporaryEntryPath); + string deletionEntryPath = Path.Combine(cacheRoot, "del-0123456789abcdef"); + Directory.CreateDirectory(deletionEntryPath); + string unrelatedDirectoryPath = Path.Combine(cacheRoot, "unrelated"); + Directory.CreateDirectory(unrelatedDirectoryPath); + File.WriteAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt"), "keep"); + string unrelatedFilePath = Path.Combine(cacheRoot, "unrelated.txt"); + File.WriteAllText(unrelatedFilePath, "keep"); + + // Act + TranscodingCachePaths.ClearCacheEntries(cacheRoot, CancellationToken.None); + + // Assert + Assert.True(Directory.Exists(cacheRoot)); + Assert.False(Directory.Exists(cacheEntryPath)); + Assert.False(Directory.Exists(temporaryEntryPath)); + Assert.False(Directory.Exists(deletionEntryPath)); + Assert.True(Directory.Exists(unrelatedDirectoryPath)); + Assert.True(File.Exists(Path.Combine(unrelatedDirectoryPath, "keep.txt"))); + Assert.True(File.Exists(unrelatedFilePath)); + } + + [Fact] + public void ClearCacheEntries_WhenACacheEntryIsASymbolicLink_ShouldDeleteTheLinkAndKeepItsTarget() + { + // Arrange + string targetPath = Path.Combine(_temporaryDirectory, "link-target"); + Directory.CreateDirectory(targetPath); + File.WriteAllText(Path.Combine(targetPath, "keep.txt"), "keep"); + string cacheRoot = Path.Combine(_temporaryDirectory, "link-cache"); + Directory.CreateDirectory(cacheRoot); + string linkPath = Path.Combine(cacheRoot, CreateCacheId()); + if (!TryCreateJunction(linkPath, targetPath)) + { + // The environment does not support creating reparse points. + return; + } + + Assert.NotNull(new DirectoryInfo(linkPath).LinkTarget); + + // Act + TranscodingCachePaths.ClearCacheEntries(cacheRoot, CancellationToken.None); + + // Assert + Assert.False(Directory.Exists(linkPath)); + Assert.True(Directory.Exists(targetPath)); + Assert.True(File.Exists(Path.Combine(targetPath, "keep.txt"))); + } + + [Fact] + public void EnsureDirectoryExists_WhenTheDirectoryDoesNotExist_ShouldCreateItAndMarkIt() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "created-cache"); + + // Act + TranscodingCachePaths.EnsureDirectoryExists(directoryPath); + + // Assert + Assert.True(Directory.Exists(directoryPath)); + Assert.True(TranscodingCachePaths.HasCacheMarker(directoryPath)); + } + + [Fact] + public void EnsureDirectoryExists_WhenTheDirectoryExistsWithoutAMarker_ShouldNotMarkIt() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "existing-cache"); + Directory.CreateDirectory(directoryPath); + + // Act + TranscodingCachePaths.EnsureDirectoryExists(directoryPath); + + // Assert + Assert.True(Directory.Exists(directoryPath)); + Assert.False(TranscodingCachePaths.HasCacheMarker(directoryPath)); + } + + [Fact] + public void TryDeleteDirectory_WhenTheDirectoryExists_ShouldDeleteItAndReturnTrue() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "deletable-cache"); + Directory.CreateDirectory(Path.Combine(directoryPath, "nested")); + File.WriteAllBytes(Path.Combine(directoryPath, "nested", "segment.m4s"), new byte[8]); + + // Act + bool result = TranscodingCachePaths.TryDeleteDirectory(directoryPath); + + // Assert + Assert.True(result); + Assert.False(Directory.Exists(directoryPath)); + } + + [Fact] + public void TryDeleteDirectory_WhenTheDirectoryDoesNotExist_ShouldReturnTrue() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "absent-cache"); + + // Act + bool result = TranscodingCachePaths.TryDeleteDirectory(directoryPath); + + // Assert + Assert.True(result); + } + + [Fact] + public void TryDeleteDirectory_WhenTheDirectoryContainsAnOpenFile_ShouldReportWhetherThePlatformDeletedIt() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "open-file-cache"); + Directory.CreateDirectory(directoryPath); + string openFilePath = Path.Combine(directoryPath, "open.bin"); + File.WriteAllBytes(openFilePath, new byte[8]); + + // Act + bool result; + using (FileStream openStream = new(openFilePath, FileMode.Open, FileAccess.Read, FileShare.None)) + result = TranscodingCachePaths.TryDeleteDirectory(directoryPath); + + // Assert + if (OperatingSystem.IsWindows()) + { + // Windows refuses to delete a file that another handle holds without delete sharing. + Assert.False(result); + Assert.True(Directory.Exists(directoryPath)); + Assert.True(File.Exists(openFilePath)); + } + else + { + // Unix-like platforms allow deleting a file that is still open. + Assert.True(result); + Assert.False(Directory.Exists(directoryPath)); + } + } + + [Fact] + public void RestrictPermissions_WhenTheDirectoryIsASymbolicLink_ShouldThrowIOException() + { + // Arrange + string targetPath = Path.Combine(_temporaryDirectory, "permissions-target"); + Directory.CreateDirectory(targetPath); + string linkPath = Path.Combine(_temporaryDirectory, "permissions-link"); + if (!TryCreateJunction(linkPath, targetPath)) + { + // The environment does not support creating reparse points. + return; + } + + Assert.NotNull(new DirectoryInfo(linkPath).LinkTarget); + + // Act + IOException exception = Assert.Throws(() => TranscodingCachePaths.RestrictPermissions(linkPath)); + + // Assert + Assert.Contains("symbolic link", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void RestrictPermissions_WhenTheDirectoryIsNotASymbolicLink_ShouldNotThrow() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "plain-cache"); + Directory.CreateDirectory(directoryPath); + + // Act + Exception? exception = Record.Exception(() => TranscodingCachePaths.RestrictPermissions(directoryPath)); + + // Assert + Assert.Null(exception); + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + using (Process process = Process.Start(startInfo)!) + { + process.WaitForExit(5000); + return process.ExitCode == 0; + } + } + catch (Exception) + { + return false; + } + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A symbolic link may keep a target alive on some platforms; the directory is under the process temporary directory. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinatorTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinatorTests.cs new file mode 100644 index 00000000..eb08063b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinatorTests.cs @@ -0,0 +1,738 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingCacheCoordinatorTests : IDisposable +{ + private readonly string _temporaryDirectory; + private readonly string _cacheRoot; + private readonly TranscodingCacheCoordinator _sut; + private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TranscodingCacheCoordinatorTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-coordinator-{Guid.NewGuid():N}"); + _cacheRoot = Path.Combine(_temporaryDirectory, "cache"); + Directory.CreateDirectory(_cacheRoot); + _sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + } + + [Fact] + public void AcquireForRoot_WhenCalledTwiceForTheSameRoot_ShouldReturnTheSameInstance() + { + // Arrange + string cacheRoot = Path.Combine(_temporaryDirectory, "shared-cache"); + + // Act + TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + + // Assert + try + { + Assert.Same(firstCoordinator, secondCoordinator); + } + finally + { + firstCoordinator.Release(); + secondCoordinator.Release(); + } + } + + [Fact] + public void Release_WhenOneReferenceRemains_ShouldKeepTheCoordinatorRegistered() + { + // Arrange + string cacheRoot = Path.Combine(_temporaryDirectory, "partially-released-cache"); + TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + + try + { + // Act + firstCoordinator.Release(); + TranscodingCacheCoordinator acquiredAfterRelease = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + + // Assert + try + { + Assert.Same(firstCoordinator, acquiredAfterRelease); + } + finally + { + acquiredAfterRelease.Release(); + } + } + finally + { + firstCoordinator.Release(); + secondCoordinator.Release(); + } + } + + [Fact] + public void Release_WhenTheLastReferenceIsReleased_ShouldMakeALaterAcquireReturnANewInstance() + { + // Arrange + string cacheRoot = Path.Combine(_temporaryDirectory, "fully-released-cache"); + TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + + // Act + firstCoordinator.Release(); + secondCoordinator.Release(); + TranscodingCacheCoordinator laterCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot); + + // Assert + try + { + Assert.NotSame(firstCoordinator, laterCoordinator); + } + finally + { + laterCoordinator.Release(); + } + } + + [Theory] + [InlineData(0)] // a zero sized output + [InlineData(-1)] // a negative sized output + public void TryReserve_WhenTheRequestedSizeIsNotPositive_ShouldReturnFalse(int requestedBytes) + { + // Act + bool result = _sut.TryReserve(requestedBytes, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.False(result); + Assert.Null(reservation); + } + + [Theory] + [InlineData(0)] // a zero maximum cache size + [InlineData(-1)] // a negative maximum cache size + public void TryReserve_WhenTheMaximumCacheSizeIsNotPositive_ShouldReturnFalse(int maxCacheBytes) + { + // Act + bool result = _sut.TryReserve(50, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.False(result); + Assert.Null(reservation); + } + + [Fact] + public void TryReserve_WhenTheRequestExceedsTheMaximum_ShouldReturnFalse() + { + // Act + bool result = _sut.TryReserve(101, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.False(result); + Assert.Null(reservation); + } + + [Fact] + public void TryReserve_WhenTheRequestFits_ShouldReserveCapacity() + { + // Act + bool result = _sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.True(result); + Assert.NotNull(reservation); + reservation!.Dispose(); + } + + [Fact] + public void TryReserve_WhenTheCacheAlreadyHoldsAReservation_ShouldCountItAgainstTheLimit() + { + // Arrange + Assert.True(_sut.TryReserve(60, 100, TimeSpan.Zero, out TranscodingCacheReservation? firstReservation)); + Assert.NotNull(firstReservation); + + try + { + // Act + bool result = _sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? secondReservation); + + // Assert + Assert.False(result); + Assert.Null(secondReservation); + } + finally + { + firstReservation.Dispose(); + } + } + + [Fact] + public void TryGrow_WhenTheReservationIsUnknown_ShouldReturnFalse() + { + // Act + bool result = _sut.TryGrow(Guid.NewGuid().ToString("N"), 50, 100, TimeSpan.Zero); + + // Assert + Assert.False(result); + } + + [Fact] + public void TryGrow_WhenTheActualSizeIsNotLargerThanTheReservation_ShouldKeepTheReservedSize() + { + // Arrange + Assert.True(_sut.TryReserve(100, 150, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + try + { + // Act + bool result = _sut.TryGrow(reservation.Id, 50, 150, TimeSpan.Zero); + + // Assert + Assert.True(result); + Assert.False(_sut.TryReserve(60, 150, TimeSpan.Zero, out _)); + } + finally + { + reservation!.Dispose(); + } + } + + [Fact] + public void TryGrow_WhenTheGrownSizeFits_ShouldIncreaseTheReservation() + { + // Arrange + Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + try + { + // Act + bool result = _sut.TryGrow(reservation.Id, 80, 100, TimeSpan.Zero); + + // Assert + Assert.True(result); + Assert.False(_sut.TryReserve(30, 100, TimeSpan.Zero, out _)); + Assert.True(_sut.TryReserve(20, 100, TimeSpan.Zero, out TranscodingCacheReservation? remainingReservation)); + remainingReservation!.Dispose(); + } + finally + { + reservation!.Dispose(); + } + } + + [Fact] + public void TryGrow_WhenTheGrownSizeExceedsTheMaximum_ShouldReturnFalse() + { + // Arrange + Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + try + { + // Act + bool result = _sut.TryGrow(reservation.Id, 101, 100, TimeSpan.Zero); + + // Assert + Assert.False(result); + } + finally + { + reservation!.Dispose(); + } + } + + [Fact] + public void TryGrow_WhenTheActualSizeIsNegative_ShouldReturnFalse() + { + // Arrange + Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + try + { + // Act + bool result = _sut.TryGrow(reservation.Id, -1, 100, TimeSpan.Zero); + + // Assert + Assert.False(result); + } + finally + { + reservation!.Dispose(); + } + } + + [Fact] + public void TryPublish_WhenTheEntryFits_ShouldMoveTheProducedEntryAndRegisterIt() + { + // Arrange + string cacheId = CreateCacheId(); + string temporaryPath = CreateTemporaryOutput(128); + NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create(); + Assert.True(_sut.TryReserve(128, 1024, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + // Act + bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 128, index, 1024, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.True(result); + Assert.False(isKeptOverCapacity); + Assert.False(isEntryInUse); + string cachePath = Path.Combine(_cacheRoot, cacheId); + Assert.True(Directory.Exists(cachePath)); + Assert.False(Directory.Exists(temporaryPath)); + Assert.Equal(128, TranscodingCacheCoordinator.GetDirectorySize(cachePath)); + Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex)); + Assert.Same(index, cachedIndex); + } + + [Fact] + public void TryPublish_WhenTheSameCacheIdIsPublishedAgain_ShouldReplaceThePreviousEntry() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 30, 100); + string replacementPath = CreateTemporaryOutput(40, "replacement.m4s"); + NormalizedTrackIndexDto replacementIndex = _normalizedTrackIndexDtoFixture.Create(); + Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + // Act + bool result = _sut.TryPublish(reservation.Id, cacheId, replacementPath, 40, replacementIndex, 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.True(result); + Assert.False(isKeptOverCapacity); + Assert.False(isEntryInUse); + string cachePath = Path.Combine(_cacheRoot, cacheId); + Assert.True(File.Exists(Path.Combine(cachePath, "replacement.m4s"))); + Assert.False(File.Exists(Path.Combine(cachePath, "segment.m4s"))); + Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex)); + Assert.Same(replacementIndex, cachedIndex); + Assert.True(_sut.TryReserve(60, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? accountingProbe)); + accountingProbe!.Dispose(); + } + + [Fact] + public void TryPublish_WhenAReaderHoldsThePreviousEntry_ShouldReturnFalseAndKeepThePreviousEntry() + { + // Arrange + string cacheId = CreateCacheId(); + NormalizedTrackIndexDto originalIndex = PublishEntry(cacheId, 50, 200); + using (TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId)) + { + string temporaryPath = CreateTemporaryOutput(50); + Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + // Act + bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.False(result); + Assert.True(isEntryInUse); + Assert.False(isKeptOverCapacity); + Assert.True(Directory.Exists(temporaryPath)); + Assert.True(Directory.Exists(Path.Combine(_cacheRoot, cacheId))); + Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex)); + Assert.Same(originalIndex, cachedIndex); + } + } + + [Fact] + public void TryPublish_WhenTheProducedEntryAloneExceedsTheMaximum_ShouldKeepItOverCapacity() + { + // Arrange + string cacheId = CreateCacheId(); + string temporaryPath = CreateTemporaryOutput(150); + Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + // Act + bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 150, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.True(result); + Assert.True(isKeptOverCapacity); + Assert.False(isEntryInUse); + Assert.True(Directory.Exists(Path.Combine(_cacheRoot, cacheId))); + Assert.True(_sut.TryGetIndex(cacheId, out _)); + } + + [Fact] + public void TryPublish_WhenTheTemporaryDirectoryDoesNotExist_ShouldReturnFalseAndConsumeTheReservation() + { + // Arrange + Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + string missingTemporaryPath = Path.Combine(_temporaryDirectory, "missing-output"); + + // Act + bool result = _sut.TryPublish(reservation.Id, CreateCacheId(), missingTemporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.False(result); + Assert.False(isKeptOverCapacity); + Assert.False(isEntryInUse); + Assert.False(reservation.TryUpdate(50, 100, TimeSpan.Zero)); + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? replacementReservation)); + replacementReservation!.Dispose(); + } + + [Fact] + public void ReleaseReservation_WhenCalled_ShouldFreeTheReservedCapacity() + { + // Arrange + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? firstReservation)); + Assert.NotNull(firstReservation); + Assert.False(_sut.TryReserve(100, 100, TimeSpan.Zero, out _)); + + // Act + _sut.ReleaseReservation(firstReservation.Id); + + // Assert + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? secondReservation)); + secondReservation!.Dispose(); + firstReservation.Dispose(); + } + + [Fact] + public void Touch_WhenTheCacheIdIsUnknown_ShouldBeIgnored() + { + // Act + Exception? exception = Record.Exception(() => _sut.Touch(CreateCacheId(), TimeSpan.Zero)); + + // Assert + Assert.Null(exception); + } + + [Fact] + public void Touch_WhenTheThrottleIntervalHasNotElapsed_ShouldNotChangeTheEntry() + { + // Arrange + string cacheId = CreateCacheId(); + string cachePath = Path.Combine(_cacheRoot, cacheId); + PublishEntry(cacheId, 50, 100); + Thread.Sleep(200); + + // Act + _sut.Touch(cacheId, TimeSpan.FromDays(1)); + bool result = _sut.TryReserve(80, 100, TimeSpan.FromMilliseconds(100), out _); + + // Assert + Assert.True(result); + Assert.False(Directory.Exists(cachePath)); + } + + [Fact] + public void Touch_WhenTheThrottleIntervalHasElapsed_ShouldUpdateTheEntry() + { + // Arrange + string cacheId = CreateCacheId(); + string cachePath = Path.Combine(_cacheRoot, cacheId); + PublishEntry(cacheId, 50, 100); + Thread.Sleep(200); + + // Act + _sut.Touch(cacheId, TimeSpan.Zero); + bool result = _sut.TryReserve(80, 100, TimeSpan.FromMilliseconds(100), out _); + + // Assert + Assert.False(result); + Assert.True(Directory.Exists(cachePath)); + } + + [Fact] + public void TryReserve_WhenTheOnlyEntryIsLeased_ShouldNotEvictItUntilTheLeaseIsReleased() + { + // Arrange + string cacheId = CreateCacheId(); + string cachePath = Path.Combine(_cacheRoot, cacheId); + PublishEntry(cacheId, 50, 100); + TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId); + + try + { + // Act + bool result = _sut.TryReserve(80, 100, TimeSpan.Zero, out _); + + // Assert + Assert.False(result); + Assert.True(Directory.Exists(cachePath)); + } + finally + { + lease.Dispose(); + } + Assert.False(Directory.Exists(cachePath)); + Assert.True(_sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + reservation!.Dispose(); + } + + [Fact] + public void TryReserve_WhenTheCacheIsFull_ShouldEvictTheLeastRecentlyUsedEntriesInOrder() + { + // Arrange + string firstCacheId = CreateCacheId(); + string secondCacheId = CreateCacheId(); + string thirdCacheId = CreateCacheId(); + PublishEntry(firstCacheId, 50, 150); + Thread.Sleep(30); + PublishEntry(secondCacheId, 50, 150); + Thread.Sleep(30); + PublishEntry(thirdCacheId, 50, 150); + + // Act + bool result = _sut.TryReserve(60, 150, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.True(result); + Assert.False(Directory.Exists(Path.Combine(_cacheRoot, firstCacheId))); + Assert.False(Directory.Exists(Path.Combine(_cacheRoot, secondCacheId))); + Assert.True(Directory.Exists(Path.Combine(_cacheRoot, thirdCacheId))); + reservation!.Dispose(); + } + + [Fact] + public void TryReserve_WhenAnEntryIsInsideTheGracePeriod_ShouldNotEvictIt() + { + // Arrange + string cacheId = CreateCacheId(); + string cachePath = Path.Combine(_cacheRoot, cacheId); + PublishEntry(cacheId, 50, 100); + + // Act + bool result = _sut.TryReserve(80, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation); + + // Assert + Assert.False(result); + Assert.Null(reservation); + Assert.True(Directory.Exists(cachePath)); + } + + [Fact] + public void TryReserve_WhenTheGracePeriodHasElapsed_ShouldEvictTheEntry() + { + // Arrange + string cacheId = CreateCacheId(); + string cachePath = Path.Combine(_cacheRoot, cacheId); + PublishEntry(cacheId, 50, 100); + + // Act + bool result = _sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation); + + // Assert + Assert.True(result); + Assert.False(Directory.Exists(cachePath)); + reservation!.Dispose(); + } + + [Fact] + public void TryPublish_WhenOnlyUnprotectedEntriesAreLeased_ShouldNeverEvictThePublishedEntry() + { + // Arrange + string firstCacheId = CreateCacheId(); + string secondCacheId = CreateCacheId(); + string publishedCacheId = CreateCacheId(); + PublishEntry(firstCacheId, 50, 200); + PublishEntry(secondCacheId, 50, 200); + Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + TranscodingCacheReaderLease firstLease = _sut.AcquireReaderLease(firstCacheId); + TranscodingCacheReaderLease secondLease = _sut.AcquireReaderLease(secondCacheId); + + try + { + // Act + bool result = _sut.TryPublish(reservation.Id, publishedCacheId, CreateTemporaryOutput(50), 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.True(result); + Assert.True(isKeptOverCapacity); + Assert.False(isEntryInUse); + Assert.True(Directory.Exists(Path.Combine(_cacheRoot, publishedCacheId))); + } + finally + { + firstLease.Dispose(); + secondLease.Dispose(); + } + Assert.False(Directory.Exists(Path.Combine(_cacheRoot, firstCacheId))); + Assert.False(Directory.Exists(Path.Combine(_cacheRoot, secondCacheId))); + Assert.True(Directory.Exists(Path.Combine(_cacheRoot, publishedCacheId))); + } + + [Fact] + public void TryReserve_WhenTheRootAlreadyHoldsEntries_ShouldAccountForThem() + { + // Arrange + string existingCacheId = CreateCacheId(); + string entryPath = Path.Combine(_cacheRoot, existingCacheId); + Directory.CreateDirectory(entryPath); + File.WriteAllBytes(Path.Combine(entryPath, "segment.m4s"), new byte[60]); + + // Act + bool result = _sut.TryReserve(50, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation); + + // Assert + Assert.False(result); + Assert.Null(reservation); + } + + [Fact] + public void TryReserve_WhenTheRootHoldsNamesThatAreNotCacheIds_ShouldIgnoreThem() + { + // Arrange + string unrelatedDirectoryPath = Path.Combine(_cacheRoot, "not-a-cache-id"); + Directory.CreateDirectory(unrelatedDirectoryPath); + File.WriteAllBytes(Path.Combine(unrelatedDirectoryPath, "payload.bin"), new byte[200]); + + // Act + bool result = _sut.TryReserve(100, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation); + + // Assert + Assert.True(result); + reservation!.Dispose(); + } + + [Fact] + public void TryReserve_WhenTheRootHoldsTombstones_ShouldHandThemToTheSweeper() + { + // Arrange + string tombstonePath = Path.Combine(_cacheRoot, TranscodingCachePaths.DELETION_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tombstonePath); + File.WriteAllBytes(Path.Combine(tombstonePath, "segment.m4s"), new byte[200]); + + // Act + bool result = _sut.TryReserve(100, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation); + + // Assert + Assert.True(result); + reservation!.Dispose(); + Assert.True(WaitUntil(() => !Directory.Exists(tombstonePath), TimeSpan.FromSeconds(2))); + } + + [Fact] + public void GetDirectorySize_WhenTheDirectoryHasNestedFiles_ShouldReturnTheirTotalSize() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "size-root"); + Directory.CreateDirectory(Path.Combine(directoryPath, "nested", "deeper")); + File.WriteAllBytes(Path.Combine(directoryPath, "first.bin"), new byte[10]); + File.WriteAllBytes(Path.Combine(directoryPath, "nested", "second.bin"), new byte[20]); + File.WriteAllBytes(Path.Combine(directoryPath, "nested", "deeper", "third.bin"), new byte[30]); + + // Act + long result = TranscodingCacheCoordinator.GetDirectorySize(directoryPath); + + // Assert + Assert.Equal(60, result); + } + + [Fact] + public void GetDirectorySize_WhenTheDirectoryDoesNotExist_ShouldReturnZero() + { + // Arrange + string directoryPath = Path.Combine(_temporaryDirectory, "missing-size-root"); + + // Act + long result = TranscodingCacheCoordinator.GetDirectorySize(directoryPath); + + // Assert + Assert.Equal(0, result); + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Creates a temporary output directory with a single file of the requested size. + /// + /// The size of the produced file, in bytes. + /// The name of the produced file. + /// The path of the created temporary output directory. + private string CreateTemporaryOutput(int size, string fileName = "segment.m4s") + { + string temporaryPath = Path.Combine(_temporaryDirectory, TranscodingCachePaths.TEMPORARY_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(temporaryPath); + File.WriteAllBytes(Path.Combine(temporaryPath, fileName), new byte[size]); + return temporaryPath; + } + + /// + /// Reserves capacity and publishes a produced entry under the requested cache identifier. + /// + /// The identifier of the produced cache entry. + /// The total size of the produced cache entry, in bytes. + /// The maximum total size of the cache, in bytes. + /// The index that was published with the entry. + private NormalizedTrackIndexDto PublishEntry(string cacheId, int size, long maxCacheBytes) + { + string temporaryPath = CreateTemporaryOutput(size); + NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create(); + Assert.True(_sut.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(_sut.TryPublish(reservation.Id, cacheId, temporaryPath, size, index, maxCacheBytes, TimeSpan.Zero, out _, out _)); + return index; + } + + /// + /// Waits, for a bounded period, until the condition becomes true. + /// + /// The condition to wait for. + /// The maximum period to wait. + /// when the condition became true within the timeout, otherwise . + private static bool WaitUntil(Func condition, TimeSpan timeout) + { + DateTime deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + if (condition()) + return true; + Thread.Sleep(20); + } + return condition(); + } + + /// + /// Releases the coordinator and removes the temporary directory created for the test. + /// + public void Dispose() + { + _sut.Release(); + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A background sweeper can still be removing a tombstone that was detached by the test. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStreamTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStreamTests.cs new file mode 100644 index 00000000..76456ccc --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStreamTests.cs @@ -0,0 +1,479 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingCacheLeaseStreamTests : IDisposable +{ + private readonly string _temporaryDirectory; + private readonly string _cacheRoot; + private readonly TranscodingCacheCoordinator _coordinator; + private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TranscodingCacheLeaseStreamTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-stream-{Guid.NewGuid():N}"); + _cacheRoot = Path.Combine(_temporaryDirectory, "cache"); + Directory.CreateDirectory(_cacheRoot); + _coordinator = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + } + + [Fact] + public void CanRead_WhenAccessed_ShouldReturnTheInnerValue() + { + // Arrange + Stream innerStream = Substitute.For(); + innerStream.CanRead.Returns(true); + + // Act + bool result; + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + result = leaseStream.CanRead; + + // Assert + Assert.True(result); + } + + [Fact] + public void CanSeek_WhenAccessed_ShouldReturnTheInnerValue() + { + // Arrange + Stream innerStream = Substitute.For(); + innerStream.CanSeek.Returns(false); + + // Act + bool result; + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + result = leaseStream.CanSeek; + + // Assert + Assert.False(result); + } + + [Fact] + public void CanWrite_WhenAccessed_ShouldReturnTheInnerValue() + { + // Arrange + Stream innerStream = Substitute.For(); + innerStream.CanWrite.Returns(true); + + // Act + bool result; + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + result = leaseStream.CanWrite; + + // Assert + Assert.True(result); + } + + [Fact] + public void Length_WhenAccessed_ShouldReturnTheInnerValue() + { + // Arrange + using (MemoryStream innerStream = new([1, 2, 3, 4, 5])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + long result = leaseStream.Length; + + // Assert + Assert.Equal(5L, result); + } + } + + [Fact] + public void Position_WhenAccessed_ShouldReturnAndSetTheInnerValue() + { + // Arrange + using (MemoryStream innerStream = new([1, 2, 3, 4, 5, 6, 7, 8])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + innerStream.Position = 5L; + + // Act + long position = leaseStream.Position; + leaseStream.Position = 7L; + + // Assert + Assert.Equal(5L, position); + Assert.Equal(7L, innerStream.Position); + } + } + + [Fact] + public void Flush_WhenCalled_ShouldFlushTheInnerStream() + { + // Arrange + Stream innerStream = Substitute.For(); + + // Act + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + leaseStream.Flush(); + + // Assert + innerStream.Received(1).Flush(); + } + + [Fact] + public void Read_WhenCalled_ShouldReadFromTheInnerStream() + { + // Arrange + byte[] buffer = new byte[8]; + using (MemoryStream innerStream = new([1, 2, 3, 4, 5])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + int result = leaseStream.Read(buffer, 1, 4); + + // Assert + Assert.Equal(4, result); + Assert.Equal(new byte[] { 0, 1, 2, 3, 4, 0, 0, 0 }, buffer); + Assert.Equal(4L, innerStream.Position); + } + } + + [Fact] + public void Read_WhenCalledWithASpan_ShouldReadFromTheInnerStream() + { + // Arrange + using (MemoryStream innerStream = new([1, 2, 3, 4])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + Span buffer = stackalloc byte[2]; + + // Act + int result = leaseStream.Read(buffer); + + // Assert + Assert.Equal(2, result); + Assert.Equal(1, buffer[0]); + Assert.Equal(2, buffer[1]); + } + } + + [Fact] + public async Task ReadAsync_WhenCalledWithMemory_ShouldReadFromTheInnerStream() + { + // Arrange + byte[] buffer = new byte[8]; + using (MemoryStream innerStream = new([4, 5, 6, 7])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + int result = await leaseStream.ReadAsync(buffer.AsMemory(), CancellationToken.None); + + // Assert + Assert.Equal(4, result); + Assert.Equal(new byte[] { 4, 5, 6, 7, 0, 0, 0, 0 }, buffer); + Assert.Equal(4L, innerStream.Position); + } + } + + [Fact] + public void Seek_WhenCalled_ShouldSeekTheInnerStream() + { + // Arrange + using (MemoryStream innerStream = new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + long result = leaseStream.Seek(3L, SeekOrigin.Begin); + + // Assert + Assert.Equal(3L, result); + Assert.Equal(3L, innerStream.Position); + } + } + + [Fact] + public void SetLength_WhenCalled_ShouldSetTheInnerLength() + { + // Arrange + using (MemoryStream innerStream = new()) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + leaseStream.SetLength(10L); + + // Assert + Assert.Equal(10L, innerStream.Length); + } + } + + [Fact] + public void Write_WhenCalled_ShouldWriteToTheInnerStream() + { + // Arrange + using (MemoryStream innerStream = new()) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + byte[] buffer = [1, 2, 3, 4, 5, 6]; + + // Act + leaseStream.Write(buffer, 1, 4); + + // Assert + Assert.Equal(new byte[] { 2, 3, 4, 5 }, innerStream.ToArray()); + } + } + + [Fact] + public void Write_WhenCalledWithASpan_ShouldWriteToTheInnerStream() + { + // Arrange + using (MemoryStream innerStream = new()) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + leaseStream.Write([5, 6, 7]); + + // Assert + Assert.Equal(3L, innerStream.Length); + Assert.Equal(new byte[] { 5, 6, 7 }, innerStream.ToArray()); + } + } + + [Fact] + public async Task WriteAsync_WhenCalledWithMemory_ShouldWriteToTheInnerStream() + { + // Arrange + using (MemoryStream innerStream = new()) + using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream)) + { + // Act + await leaseStream.WriteAsync(new byte[] { 1, 2 }.AsMemory(), CancellationToken.None); + + // Assert + Assert.Equal(new byte[] { 1, 2 }, innerStream.ToArray()); + } + } + + [Fact] + public void Dispose_WhenCalled_ShouldDisposeTheInnerStreamAndReleaseTheLease() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId); + using (MemoryStream innerStream = new()) + { + TranscodingCacheLeaseStream leaseStream = new(innerStream, lease); + Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _)); + Assert.True(Directory.Exists(cachePath)); + + // Act + leaseStream.Dispose(); + + // Assert + Assert.Throws(() => + { + _ = innerStream.Length; + }); + Assert.False(Directory.Exists(cachePath)); + Assert.True(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + reservation!.Dispose(); + } + } + + [Fact] + public void Dispose_WhenCalledTwice_ShouldDisposeTheInnerStreamAndReleaseTheLeaseOnce() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease firstLease = _coordinator.AcquireReaderLease(cacheId); + TranscodingCacheReaderLease secondLease = _coordinator.AcquireReaderLease(cacheId); + using (MemoryStream firstInnerStream = new()) + using (MemoryStream secondInnerStream = new()) + { + TranscodingCacheLeaseStream firstStream = new(firstInnerStream, firstLease); + TranscodingCacheLeaseStream secondStream = new(secondInnerStream, secondLease); + + // Act + firstStream.Dispose(); + firstStream.Dispose(); + + // Assert + Assert.Throws(() => + { + _ = firstInnerStream.Length; + }); + Assert.Equal(0L, secondInnerStream.Length); + Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _)); + Assert.True(Directory.Exists(cachePath)); + + secondStream.Dispose(); + + Assert.False(Directory.Exists(cachePath)); + Assert.Throws(() => + { + _ = secondInnerStream.Length; + }); + } + } + + [Fact] + public void Dispose_WhenDisposingTheInnerStreamThrows_ShouldStillReleaseTheLease() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId); + Stream innerStream = new ThrowingDisposeStream(new IOException("The inner stream cannot be disposed.")); + TranscodingCacheLeaseStream leaseStream = new(innerStream, lease); + Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _)); + + // Act + Assert.Throws(() => leaseStream.Dispose()); + + // Assert + Assert.False(Directory.Exists(cachePath)); + } + + [Fact] + public async Task DisposeAsync_WhenCalled_ShouldDisposeTheInnerStreamAndReleaseTheLease() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId); + Stream innerStream = Substitute.For(); + TranscodingCacheLeaseStream leaseStream = new(innerStream, lease); + Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _)); + + // Act + await leaseStream.DisposeAsync(); + + // Assert + await innerStream.Received(1).DisposeAsync(); + Assert.False(Directory.Exists(cachePath)); + } + + [Fact] + public async Task DisposeAsync_WhenDisposingTheInnerStreamThrows_ShouldStillReleaseTheLease() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId); + Stream innerStream = new ThrowingDisposeStream(new IOException("The inner stream cannot be disposed.")); + TranscodingCacheLeaseStream leaseStream = new(innerStream, lease); + Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _)); + + // Act + await Assert.ThrowsAsync(async () => await leaseStream.DisposeAsync()); + + // Assert + Assert.False(Directory.Exists(cachePath)); + } + + /// + /// Creates the stream under test over the provided inner stream. + /// + /// The stream over the cached segment. + /// The created . + private TranscodingCacheLeaseStream CreateSut(Stream innerStream) + { + TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(CreateCacheId()); + return new TranscodingCacheLeaseStream(innerStream, lease); + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Reserves capacity and publishes a produced entry under the requested cache identifier. + /// + /// The identifier of the produced cache entry. + /// The total size of the produced cache entry, in bytes. + /// The maximum total size of the cache, in bytes. + private void PublishEntry(string cacheId, int size, long maxCacheBytes) + { + string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}"); + Directory.CreateDirectory(temporaryPath); + File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]); + Assert.True(_coordinator.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(_coordinator.TryPublish(reservation.Id, cacheId, temporaryPath, size, _normalizedTrackIndexDtoFixture.Create(), maxCacheBytes, TimeSpan.Zero, out _, out _)); + } + + /// + /// Releases the coordinator and removes the temporary directory created for the test. + /// + public void Dispose() + { + _coordinator.Release(); + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A background sweeper can still be removing a tombstone that was detached by the test. + } + GC.SuppressFinalize(this); + } + + /// + /// A memory stream whose disposal always fails, used to verify that a cache entry lease is released even when the inner stream cannot be disposed. + /// + private sealed class ThrowingDisposeStream : MemoryStream + { + private readonly IOException _exception; + + /// + /// Initializes a new instance of the class. + /// + /// The exception thrown when the stream is disposed. + internal ThrowingDisposeStream(IOException exception) + { + _exception = exception; + } + + /// + /// Releases the resources of the stream and then throws the configured exception. + /// + /// Whether the method is called from the method. + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + throw _exception; + } + + /// + /// Gets a failed value task that carries the configured exception. + /// + /// A failed . + public override ValueTask DisposeAsync() + { + return ValueTask.FromException(_exception); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLeaseTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLeaseTests.cs new file mode 100644 index 00000000..83b89c59 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLeaseTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingCacheReaderLeaseTests : IDisposable +{ + private readonly string _temporaryDirectory; + private readonly string _cacheRoot; + private readonly TranscodingCacheCoordinator _sut; + private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TranscodingCacheReaderLeaseTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-lease-{Guid.NewGuid():N}"); + _cacheRoot = Path.Combine(_temporaryDirectory, "cache"); + Directory.CreateDirectory(_cacheRoot); + _sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + } + + [Fact] + public void Dispose_WhenCalled_ShouldReleaseTheLeaseSoTheEntryCanBeEvicted() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId); + Assert.False(_sut.TryReserve(80, 100, TimeSpan.Zero, out _)); + Assert.True(Directory.Exists(cachePath)); + + // Act + lease.Dispose(); + + // Assert + Assert.False(Directory.Exists(cachePath)); + Assert.True(_sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + reservation!.Dispose(); + } + + [Fact] + public void Dispose_WhenCalledTwiceAcrossTwoLeases_ShouldReleaseOnlyOncePerLease() + { + // Arrange + string cacheId = CreateCacheId(); + PublishEntry(cacheId, 50, 100); + string cachePath = Path.Combine(_cacheRoot, cacheId); + TranscodingCacheReaderLease firstLease = _sut.AcquireReaderLease(cacheId); + TranscodingCacheReaderLease secondLease = _sut.AcquireReaderLease(cacheId); + + try + { + // Act + firstLease.Dispose(); + firstLease.Dispose(); + + // Assert + Assert.False(_sut.TryReserve(80, 100, TimeSpan.Zero, out _)); + Assert.True(Directory.Exists(cachePath)); + } + finally + { + firstLease.Dispose(); + secondLease.Dispose(); + } + Assert.False(Directory.Exists(cachePath)); + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Reserves capacity and publishes a produced entry under the requested cache identifier. + /// + /// The identifier of the produced cache entry. + /// The total size of the produced cache entry, in bytes. + /// The maximum total size of the cache, in bytes. + private void PublishEntry(string cacheId, int size, long maxCacheBytes) + { + string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}"); + Directory.CreateDirectory(temporaryPath); + File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]); + Assert.True(_sut.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(_sut.TryPublish(reservation.Id, cacheId, temporaryPath, size, _normalizedTrackIndexDtoFixture.Create(), maxCacheBytes, TimeSpan.Zero, out _, out _)); + } + + /// + /// Releases the coordinator and removes the temporary directory created for the test. + /// + public void Dispose() + { + _sut.Release(); + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A background sweeper can still be removing a tombstone that was detached by the test. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservationTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservationTests.cs new file mode 100644 index 00000000..2e72a50d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservationTests.cs @@ -0,0 +1,230 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingCacheReservationTests : IDisposable +{ + private readonly string _temporaryDirectory; + private readonly string _cacheRoot; + private readonly TranscodingCacheCoordinator _sut; + private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TranscodingCacheReservationTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-reservation-{Guid.NewGuid():N}"); + _cacheRoot = Path.Combine(_temporaryDirectory, "cache"); + Directory.CreateDirectory(_cacheRoot); + _sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + } + + [Fact] + public void TryUpdate_WhenTheReservationIsUnfinished_ShouldGrowTheReservation() + { + // Arrange + Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + try + { + // Act + bool result = reservation.TryUpdate(80, 100, TimeSpan.Zero); + + // Assert + Assert.True(result); + Assert.False(_sut.TryReserve(30, 100, TimeSpan.Zero, out _)); + } + finally + { + reservation.Dispose(); + } + } + + [Fact] + public void TryUpdate_WhenTheReservationIsCompleted_ShouldReturnFalse() + { + // Arrange + Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(reservation.TryComplete(CreateCacheId(), CreateTemporaryOutput(50), 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out _, out _)); + + try + { + // Act + bool result = reservation.TryUpdate(60, 200, TimeSpan.Zero); + + // Assert + Assert.False(result); + } + finally + { + reservation.Dispose(); + } + } + + [Fact] + public void TryUpdate_WhenTheReservationIsDisposed_ShouldReturnFalse() + { + // Arrange + Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + reservation.Dispose(); + + // Act + bool result = reservation.TryUpdate(50, 100, TimeSpan.Zero); + + // Assert + Assert.False(result); + } + + [Fact] + public void TryComplete_WhenTheReservationIsCompleted_ShouldReturnFalse() + { + // Arrange + string cacheId = CreateCacheId(); + NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create(); + Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(reservation.TryComplete(cacheId, CreateTemporaryOutput(50), 50, index, 200, TimeSpan.Zero, out _, out _)); + string secondTemporaryPath = CreateTemporaryOutput(50); + + try + { + // Act + bool result = reservation.TryComplete(cacheId, secondTemporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse); + + // Assert + Assert.False(result); + Assert.False(isKeptOverCapacity); + Assert.False(isEntryInUse); + Assert.True(Directory.Exists(secondTemporaryPath)); + Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex)); + Assert.Same(index, cachedIndex); + } + finally + { + reservation.Dispose(); + } + } + + [Fact] + public void TryComplete_WhenTheReservationIsDisposed_ShouldReturnFalse() + { + // Arrange + Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + reservation.Dispose(); + string temporaryPath = CreateTemporaryOutput(50); + + // Act + bool result = reservation.TryComplete(CreateCacheId(), temporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out _, out _); + + // Assert + Assert.False(result); + Assert.True(Directory.Exists(temporaryPath)); + } + + [Fact] + public void Dispose_WhenTheReservationIsNotCompleted_ShouldReleaseTheReservedCapacity() + { + // Arrange + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.False(_sut.TryReserve(100, 100, TimeSpan.Zero, out _)); + + // Act + reservation.Dispose(); + + // Assert + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? laterReservation)); + laterReservation!.Dispose(); + } + + [Fact] + public void Dispose_WhenTheReservationIsCompleted_ShouldKeepThePublishedEntryAccounted() + { + // Arrange + string cacheId = CreateCacheId(); + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + Assert.True(reservation.TryComplete(cacheId, CreateTemporaryOutput(100), 100, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out _, out _)); + + // Act + reservation.Dispose(); + reservation.Dispose(); + + // Assert + Assert.True(_sut.TryGetIndex(cacheId, out _)); + Assert.False(_sut.TryReserve(100, 100, TimeSpan.FromHours(1), out _)); + } + + [Fact] + public void Dispose_WhenCalledTwice_ShouldReleaseTheReservedCapacityOnce() + { + // Arrange + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation)); + Assert.NotNull(reservation); + + // Act + reservation.Dispose(); + reservation.Dispose(); + + // Assert + Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? laterReservation)); + laterReservation!.Dispose(); + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Creates a temporary output directory with a single file of the requested size. + /// + /// The size of the produced file, in bytes. + /// The path of the created temporary output directory. + private string CreateTemporaryOutput(int size) + { + string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}"); + Directory.CreateDirectory(temporaryPath); + File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]); + return temporaryPath; + } + + /// + /// Releases the coordinator and removes the temporary directory created for the test. + /// + public void Dispose() + { + _sut.Release(); + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A background sweeper can still be removing a tombstone that was detached by the test. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTrackerTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTrackerTests.cs new file mode 100644 index 00000000..0b89077d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTrackerTests.cs @@ -0,0 +1,216 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingOutputSizeTrackerTests : IDisposable +{ + private const string SEGMENT_FILE_PREFIX = "segment"; + private const string SEGMENT_FILE_EXTENSION = ".m4s"; + private const string SEGMENT_LIST_FILE_NAME = "index.m3u8"; + + private readonly string _temporaryDirectory; + private readonly TranscodingOutputSizeTracker _sut; + + /// + /// Initializes a new instance of the class. + /// + public TranscodingOutputSizeTrackerTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-output-size-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + _sut = new TranscodingOutputSizeTracker(_temporaryDirectory, SEGMENT_FILE_PREFIX, SEGMENT_FILE_EXTENSION, SEGMENT_LIST_FILE_NAME); + } + + [Fact] + public void GetCurrentSize_WhenCalledForTheFirstTime_ShouldCountTheSegmentListAndTheExistingSegments() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 100); + CreateSegment(1, 50); + + // Act + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(160L, result); + } + + [Fact] + public void GetCurrentSize_WhenTheCurrentSegmentGrows_ShouldCountOnlyTheGrowth() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 100); + Assert.Equal(110L, _sut.GetCurrentSize()); + + // Act + AppendToSegment(0, 40); + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(150L, result); + } + + [Fact] + public void GetCurrentSize_WhenTheSegmentListGrows_ShouldCountOnlyTheGrowth() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 10); + Assert.Equal(20L, _sut.GetCurrentSize()); + + // Act + AppendToFile(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME), 5); + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(25L, result); + } + + [Fact] + public void GetCurrentSize_WhenASegmentIsFinishedAndANewOneStarts_ShouldDiscoverEachSegmentOnce() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 100); + Assert.Equal(110L, _sut.GetCurrentSize()); + AppendToSegment(0, 50); + CreateSegment(1, 30); + + // Act + long resultAfterTheNewSegment = _sut.GetCurrentSize(); + AppendToSegment(1, 20); + long resultAfterTheNewSegmentGrows = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(190L, resultAfterTheNewSegment); + Assert.Equal(210L, resultAfterTheNewSegmentGrows); + } + + [Fact] + public void GetCurrentSize_WhenFilesDoNotFollowTheSegmentNamePattern_ShouldIgnoreThem() + { + // Arrange + CreateSegmentList(5); + CreateSegment(0, 10); + File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment000001.bak"), new byte[1000]); + File.WriteAllBytes(Path.Combine(_temporaryDirectory, "other000000.m4s"), new byte[1000]); + File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment-1.m4s"), new byte[1000]); + File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment000000.txt"), new byte[1000]); + + // Act + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(15L, result); + } + + [Fact] + public void GetCurrentSize_WhenTheLastSegmentDisappears_ShouldKeepItsLastMeasuredLength() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 100); + Assert.Equal(110L, _sut.GetCurrentSize()); + + // Act + File.Delete(GetSegmentPath(0)); + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(110L, result); + } + + [Fact] + public void GetCurrentSize_WhenTheSegmentListDisappears_ShouldKeepItsLastMeasuredLength() + { + // Arrange + CreateSegmentList(10); + CreateSegment(0, 100); + Assert.Equal(110L, _sut.GetCurrentSize()); + + // Act + File.Delete(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME)); + long result = _sut.GetCurrentSize(); + + // Assert + Assert.Equal(110L, result); + } + + /// + /// Creates the segment list file with the requested size. + /// + /// The size of the segment list, in bytes. + private void CreateSegmentList(int size) + { + File.WriteAllBytes(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME), new byte[size]); + } + + /// + /// Creates a segment file with the requested zero based index and size. + /// + /// The zero based index of the segment. + /// The size of the segment, in bytes. + private void CreateSegment(int segmentIndex, int size) + { + File.WriteAllBytes(GetSegmentPath(segmentIndex), new byte[size]); + } + + /// + /// Appends the requested number of bytes to a segment file. + /// + /// The zero based index of the segment. + /// The number of bytes to append. + private void AppendToSegment(int segmentIndex, int size) + { + AppendToFile(GetSegmentPath(segmentIndex), size); + } + + /// + /// Appends the requested number of bytes to a file. + /// + /// The file to append to. + /// The number of bytes to append. + private static void AppendToFile(string filePath, int size) + { + using (FileStream stream = new(filePath, FileMode.Append, FileAccess.Write)) + stream.Write(new byte[size], 0, size); + } + + /// + /// Gets the path of the segment file of the requested zero based index. + /// + /// The zero based index of the segment. + /// The path of the segment file. + private string GetSegmentPath(int segmentIndex) + { + return Path.Combine(_temporaryDirectory, $"{SEGMENT_FILE_PREFIX}{segmentIndex:D6}{SEGMENT_FILE_EXTENSION}"); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The directory is under the process temporary directory. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs new file mode 100644 index 00000000..1e89b336 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingStartupInitializerTests : IDisposable +{ + private readonly string _temporaryDirectory; + private readonly string _cacheDirectory; + private readonly TranscodingSettingsDto _settings; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly ILogger _mockLogger; + private readonly TranscodingStartupInitializer _sut; + private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TranscodingStartupInitializerTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-startup-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + _cacheDirectory = Path.Combine(_temporaryDirectory, "cache"); + string missingFfmpegPath = Path.Combine(_temporaryDirectory, "missing-ffmpeg-binary"); + _settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory); + _toolchainStatus = new TranscodingToolchainStatus(); + _mockLogger = Substitute.For>(); + _sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger); + } + + [Fact] + public async Task StartAsync_WhenTheConfiguredDirectoryDoesNotExist_ShouldCreateAndMarkItAndRecordTheToolchainUnavailable() + { + // Act + await _sut.StartAsync(CancellationToken.None); + + // Assert + Assert.True(Directory.Exists(_cacheDirectory)); + Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory)); + Assert.False(_toolchainStatus.IsTranscoderAvailable); + } + + [Fact] + public async Task StartAsync_WhenTheDirectoryExistsButIsEmptyWithoutTheMarker_ShouldAdoptItByWritingTheMarker() + { + // Arrange + Directory.CreateDirectory(_cacheDirectory); + Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory)); + + // Act + await _sut.StartAsync(CancellationToken.None); + + // Assert + Assert.True(Directory.Exists(_cacheDirectory)); + Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory)); + } + + [Fact] + public async Task StartAsync_WhenTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldLeaveItUntouchedAndLogAnError() + { + // Arrange + Directory.CreateDirectory(_cacheDirectory); + string operatorFilePath = Path.Combine(_cacheDirectory, "operator-data.txt"); + File.WriteAllText(operatorFilePath, "operator data"); + string operatorDirectoryPath = Path.Combine(_cacheDirectory, "operator-directory"); + Directory.CreateDirectory(operatorDirectoryPath); + string nestedFilePath = Path.Combine(operatorDirectoryPath, "nested.txt"); + File.WriteAllText(nestedFilePath, "nested data"); + + // Act + await _sut.StartAsync(CancellationToken.None); + + // Assert + Assert.True(Directory.Exists(_cacheDirectory)); + Assert.Equal("operator data", File.ReadAllText(operatorFilePath)); + Assert.True(File.Exists(nestedFilePath)); + Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory)); + Assert.False(_toolchainStatus.IsTranscoderAvailable); + _mockLogger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + + [Fact] + public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace() + { + // Arrange + Directory.CreateDirectory(_cacheDirectory); + TranscodingCachePaths.WriteCacheMarker(_cacheDirectory); + string cacheEntryPath = Path.Combine(_cacheDirectory, CreateCacheId()); + Directory.CreateDirectory(Path.Combine(cacheEntryPath, "nested")); + File.WriteAllText(Path.Combine(cacheEntryPath, "nested", "segment.m4s"), "cache data"); + string temporaryEntryPath = Path.Combine(_cacheDirectory, "tmp-0123456789abcdef"); + Directory.CreateDirectory(temporaryEntryPath); + string deletionEntryPath = Path.Combine(_cacheDirectory, "del-0123456789abcdef"); + Directory.CreateDirectory(deletionEntryPath); + string unrelatedDirectoryPath = Path.Combine(_cacheDirectory, "operator-directory"); + Directory.CreateDirectory(unrelatedDirectoryPath); + File.WriteAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt"), "keep"); + string unrelatedFilePath = Path.Combine(_cacheDirectory, "operator-note.txt"); + File.WriteAllText(unrelatedFilePath, "keep"); + + // Act + await _sut.StartAsync(CancellationToken.None); + + // Assert + Assert.True(Directory.Exists(_cacheDirectory)); + Assert.False(Directory.Exists(cacheEntryPath)); + Assert.False(Directory.Exists(temporaryEntryPath)); + Assert.False(Directory.Exists(deletionEntryPath)); + Assert.True(Directory.Exists(unrelatedDirectoryPath)); + Assert.Equal("keep", File.ReadAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt"))); + Assert.Equal("keep", File.ReadAllText(unrelatedFilePath)); + Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory)); + } + + [Fact] + public async Task StartAsync_WhenTheCacheDirectoryIsAReparsePoint_ShouldNotThrowAndShouldRecordTheToolchainUnavailable() + { + // Arrange + string junctionTargetPath = Path.Combine(_temporaryDirectory, "junction-target"); + Directory.CreateDirectory(junctionTargetPath); + string targetFilePath = Path.Combine(junctionTargetPath, "keep.txt"); + File.WriteAllText(targetFilePath, "keep"); + if (!TryCreateJunction(_cacheDirectory, junctionTargetPath)) // The platform refused to create a reparse point, so the scenario cannot be exercised here. + return; + Assert.NotNull(new DirectoryInfo(_cacheDirectory).LinkTarget); + + // Act + Exception? exception = await Record.ExceptionAsync(() => _sut.StartAsync(CancellationToken.None)); + + // Assert + Assert.Null(exception); + Assert.False(_toolchainStatus.IsTranscoderAvailable); + Assert.True(Directory.Exists(junctionTargetPath)); + Assert.Equal("keep", File.ReadAllText(targetFilePath)); + } + + [Fact] + public async Task StartAsync_WhenTheProbeFails_ShouldRecordTheOutcomeInTheProvidedToolchainStatusInstance() + { + // Act + await _sut.StartAsync(CancellationToken.None); + + // Assert + // The instance passed to the initializer is the one that changes. A copied status would leave this instance available. + Assert.False(_toolchainStatus.IsTranscoderAvailable); + Assert.All( + [.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)], + encoderName => Assert.False(_toolchainStatus.IsEncoderAvailable(encoderName))); + } + + [Fact] + public async Task StopAsync_WhenCalled_ShouldReturnACompletedTask() + { + // Act + Task result = _sut.StopAsync(CancellationToken.None); + + // Assert + Assert.True(result.IsCompletedSuccessfully); + await result; + } + + /// + /// Creates a well formed opaque cache identifier. + /// + /// A 64 character lowercase hexadecimal identifier. + private static string CreateCacheId() + { + return $"{Guid.NewGuid():N}{Guid.NewGuid():N}"; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + using (Process process = Process.Start(startInfo)!) + { + process.WaitForExit(5000); + return process.ExitCode == 0; + } + } + catch (Exception) + { + return false; + } + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_cacheDirectory) && new DirectoryInfo(_cacheDirectory).LinkTarget is not null) + Directory.Delete(_cacheDirectory); + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A reparse point may be held by the platform on some systems; the directory is under the process temporary directory. + } + GC.SuppressFinalize(this); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalogTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalogTests.cs new file mode 100644 index 00000000..034f69fc --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalogTests.cs @@ -0,0 +1,199 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackFormatCatalogTests +{ + [Fact] + public void Formats_WhenRead_ShouldExposeTheDocumentedCanonicalContainerAndCodecPairsInPreferenceOrder() + { + // Arrange + (string Container, string Codec)[] expectedPairs = + [ + ("MP4", "AAC"), // the preferred container of the preferred codec + ("AAC", "AAC"), // the second container of the preferred codec + ("OGG", "OPUS"), // the preferred lossy codec after AAC + ("MP3", "MP3"), // the compatibility codec + ("OGG", "VORBIS"), // the second lossy codec in OGG + ("FLAC", "FLAC"), // the lossless codec + ("WAV", "PCM") // the uncompressed codec + ]; + + // Act + IReadOnlyList result = PlaybackFormatCatalog.Formats; + + // Assert + Assert.Equal(expectedPairs, result.Select(format => (format.Container, format.Codec))); + } + + [Fact] + public void TranscodeCodecPreference_WhenRead_ShouldListEachCodecOnceInOrderOfFirstAppearanceInFormats() + { + // Arrange + List expectedCodecs = []; + foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats) + if (!expectedCodecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase)) + expectedCodecs.Add(format.Codec); + + // Act + IReadOnlyList result = PlaybackFormatCatalog.TranscodeCodecPreference; + + // Assert + Assert.Equal(expectedCodecs, result); + Assert.Equal(["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"], result); + Assert.Equal(result.Count, result.Distinct(StringComparer.OrdinalIgnoreCase).Count()); + } + + [Fact] + public void ProducibleContainersByCodec_WhenRead_ShouldGroupTheContainersPerCodecInCatalogOrder() + { + // Arrange + Dictionary> expectedContainersByCodec = new(StringComparer.OrdinalIgnoreCase); + foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats) + { + if (!expectedContainersByCodec.TryGetValue(format.Codec, out List? containers)) + { + containers = []; + expectedContainersByCodec[format.Codec] = containers; + } + containers.Add(format.Container); + } + + // Act + IReadOnlyDictionary> result = PlaybackFormatCatalog.ProducibleContainersByCodec; + + // Assert + Assert.Equal(expectedContainersByCodec.Count, result.Count); + foreach (KeyValuePair> expectedEntry in expectedContainersByCodec) + { + Assert.True(result.TryGetValue(expectedEntry.Key, out IReadOnlyList? containers)); + Assert.Equal(expectedEntry.Value, containers); + } + Assert.Equal(["MP4", "AAC"], result["AAC"]); // the preferred codec has two producible containers, in preference order + Assert.Equal(["OGG"], result["OPUS"]); + Assert.Equal(["OGG"], result["VORBIS"]); + Assert.Equal(["MP3"], result["MP3"]); + Assert.Equal(["FLAC"], result["FLAC"]); + Assert.Equal(["WAV"], result["PCM"]); + } + + [Fact] + public void ProducibleContainersByCodec_WhenRead_ShouldNotRepeatAContainerWithinACodec() + { + // Act + IReadOnlyDictionary> result = PlaybackFormatCatalog.ProducibleContainersByCodec; + + // Assert + foreach (IReadOnlyList containers in result.Values) + Assert.Equal(containers.Count, containers.Distinct(StringComparer.OrdinalIgnoreCase).Count()); + } + + [Fact] + public void ProducibleContainersByCodec_WhenRead_ShouldOnlyContainPairsThatExistInTheCatalog() + { + // Act + IReadOnlyDictionary> result = PlaybackFormatCatalog.ProducibleContainersByCodec; + + // Assert + foreach (KeyValuePair> entry in result) + foreach (string container in entry.Value) + Assert.Contains(PlaybackFormatCatalog.Formats, format => + string.Equals(format.Codec, entry.Key, StringComparison.OrdinalIgnoreCase) && + string.Equals(format.Container, container, StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void FormatsByPair_WhenRead_ShouldContainExactlyOneEntryPerCatalogFormat() + { + // Act + IReadOnlyDictionary result = PlaybackFormatCatalog.FormatsByPair; + + // Assert + Assert.Equal(PlaybackFormatCatalog.Formats.Count, result.Count); + Assert.All(PlaybackFormatCatalog.Formats, format => + { + string pairKey = PlaybackFormatCatalog.BuildPairKey(format.Container, format.Codec); + Assert.True(result.TryGetValue(pairKey, out NormalizedAudioFormatDto? indexedFormat)); + Assert.Equal(format, indexedFormat); + }); + } + + [Theory] + [InlineData("mp4/aac", "MP4", "AAC")] // the canonical pair in lower case + [InlineData("Mp4/Aac", "MP4", "AAC")] // the canonical pair in mixed case + [InlineData("aac/aac", "AAC", "AAC")] // the second format in the catalog, in lower case + public void FormatsByPair_WhenLookedUpWithDifferentCasing_ShouldReturnTheCatalogFormat(string pairKey, string expectedContainer, string expectedCodec) + { + // Act + bool found = PlaybackFormatCatalog.FormatsByPair.TryGetValue(pairKey, out NormalizedAudioFormatDto? result); + + // Assert + Assert.True(found); + Assert.NotNull(result); + Assert.Equal(expectedContainer, result.Container); + Assert.Equal(expectedCodec, result.Codec); + } + + [Fact] + public void BuildPairKey_WhenTheInputsArePaddedAndDifferentlyCased_ShouldTrimAndUppercaseThem() + { + // Act + string result = PlaybackFormatCatalog.BuildPairKey(" mp4 ", "\taAc "); + + // Assert + Assert.Equal("MP4/AAC", result); + } + + [Fact] + public void BuildPairKey_WhenTheInputsDifferOnlyInCasingAndPadding_ShouldProduceTheSameKey() + { + // Act + string firstResult = PlaybackFormatCatalog.BuildPairKey("mp4", "aac"); + string secondResult = PlaybackFormatCatalog.BuildPairKey(" MP4 ", " AAC "); + + // Assert + Assert.Equal(firstResult, secondResult); + } + + [Theory] + [InlineData(null, null, "/")] // both parts are absent + [InlineData("", "", "/")] // both parts are empty + [InlineData(" ", " ", "/")] // both parts are white space + [InlineData(null, "aac", "/AAC")] // only the container is absent + [InlineData("mp4", null, "MP4/")] // only the codec is absent + public void BuildPairKey_WhenAContainerOrCodecIsNullOrEmpty_ShouldProduceTheSlashSeparatedFormWithoutThrowing(string? container, string? codec, string expectedKey) + { + // Act + string result = PlaybackFormatCatalog.BuildPairKey(container!, codec!); + + // Assert + Assert.Equal(expectedKey, result); + } + + [Fact] + public void Formats_WhenRead_ShouldExposeANonEmptyMuxerALeadingDotExtensionAndANonEmptyEncoderForEveryFormat() + { + // Act + IReadOnlyList result = PlaybackFormatCatalog.Formats; + + // Assert + Assert.All(result, format => + { + Assert.False(string.IsNullOrWhiteSpace(format.MuxerName)); + Assert.StartsWith(".", format.FileExtension, StringComparison.Ordinal); + Assert.True(format.FileExtension.Length > 1); + Assert.False(string.IsNullOrWhiteSpace(format.EncoderName)); + }); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatusTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatusTests.cs new file mode 100644 index 00000000..66d6bfac --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatusTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingToolchainStatusTests +{ + private readonly TranscodingToolchainStatus _sut; + private readonly IReadOnlyList _catalogEncoderNames; + + /// + /// Initializes a new instance of the class. + /// + public TranscodingToolchainStatusTests() + { + _sut = new TranscodingToolchainStatus(); + _catalogEncoderNames = [.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + [Fact] + public void IsTranscoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrue() + { + // Act + bool result = _sut.IsTranscoderAvailable; + + // Assert + Assert.True(result); + } + + [Fact] + public void IsEncoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrueForEveryCatalogEncoder() + { + // Act + IReadOnlyList results = [.. _catalogEncoderNames.Select(_sut.IsEncoderAvailable)]; + + // Assert + Assert.All(results, result => Assert.True(result)); + } + + [Fact] + public void RecordUnavailable_WhenCalled_ShouldReportTheTranscoderAndEveryCatalogEncoderUnavailable() + { + // Act + _sut.RecordUnavailable(); + + // Assert + Assert.False(_sut.IsTranscoderAvailable); + Assert.All(_catalogEncoderNames, encoderName => Assert.False(_sut.IsEncoderAvailable(encoderName))); + } + + [Fact] + public void RecordMissingEncoders_WhenCalled_ShouldKeepTheTranscoderAvailableAndReportOnlyTheListedEncodersUnavailable() + { + // Arrange + string missingEncoderName = _catalogEncoderNames[0]; + string availableEncoderName = _catalogEncoderNames[1]; + + // Act + _sut.RecordMissingEncoders([missingEncoderName]); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.False(_sut.IsEncoderAvailable(missingEncoderName)); + Assert.True(_sut.IsEncoderAvailable(availableEncoderName)); + } + + [Theory] + [InlineData("AAC")] // an encoder name in upper case + [InlineData("Aac")] // an encoder name in mixed case + public void RecordMissingEncoders_WhenTheNameDiffersInCase_ShouldReportTheEncoderUnavailable(string missingEncoderName) + { + // Act + _sut.RecordMissingEncoders([missingEncoderName]); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.False(_sut.IsEncoderAvailable("aac")); + } + + [Fact] + public void RecordMissingEncoders_WhenCalledTwice_ShouldReplaceThePreviousMissingSetInsteadOfAccumulatingIt() + { + // Act + _sut.RecordMissingEncoders(["aac"]); + _sut.RecordMissingEncoders(["libopus"]); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.True(_sut.IsEncoderAvailable("aac")); + Assert.False(_sut.IsEncoderAvailable("libopus")); + } + + [Fact] + public void RecordMissingEncoders_WhenTheListIsEmpty_ShouldKeepEveryCatalogEncoderAvailable() + { + // Act + _sut.RecordMissingEncoders([]); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName))); + } + + [Fact] + public void RecordAvailable_WhenTheTranscoderWasUnavailable_ShouldRestoreTheTranscoderAndEveryCatalogEncoder() + { + // Arrange + _sut.RecordUnavailable(); + + // Act + _sut.RecordAvailable(); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName))); + } + + [Fact] + public void RecordAvailable_WhenEncodersWereMissing_ShouldClearTheMissingSet() + { + // Arrange + _sut.RecordMissingEncoders(["aac", "libopus"]); + + // Act + _sut.RecordAvailable(); + + // Assert + Assert.True(_sut.IsTranscoderAvailable); + Assert.True(_sut.IsEncoderAvailable("aac")); + Assert.True(_sut.IsEncoderAvailable("libopus")); + } +}