Implements tests for commit 4e13b23f16

Covers the normalized audio cache with integration tests for the cache paths, the coordinator, the reader lease, the reservation, the lease stream, the output size tracker and the startup initializer, and unit tests for the playback format catalog and the transcoding toolchain status, with fixtures for the index DTOs and the transcoding settings. Makes the array based asynchronous overloads of the lease stream adapt to the memory based overloads of the inner stream.
This commit is contained in:
BinaryAlley committed 2026-10-28 15:32:52 +02:00
1 parent cf3855ec12
commit d61a114d80
13 files changed
+3011 -2

No files matched your search

@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheCoordinator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheCoordinatorTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheCoordinatorTests"/> class.
/// </summary>
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);
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Creates a temporary output directory with a single file of the requested size.
/// </summary>
/// <param name="size">The size of the produced file, in bytes.</param>
/// <param name="fileName">The name of the produced file.</param>
/// <returns>The path of the created temporary output directory.</returns>
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;
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <returns>The index that was published with the entry.</returns>
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;
}
/// <summary>
/// Waits, for a bounded period, until the condition becomes true.
/// </summary>
/// <param name="condition">The condition to wait for.</param>
/// <param name="timeout">The maximum period to wait.</param>
/// <returns><see langword="true"/> when the condition became true within the timeout, otherwise <see langword="false"/>.</returns>
private static bool WaitUntil(Func<bool> condition, TimeSpan timeout)
{
DateTime deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (condition())
return true;
Thread.Sleep(20);
}
return condition();
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheLeaseStream"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheLeaseStreamTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _coordinator;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheLeaseStreamTests"/> class.
/// </summary>
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<Stream>();
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<Stream>();
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<Stream>();
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<Stream>();
// 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<byte> 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<ObjectDisposedException>(() =>
{
_ = 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<ObjectDisposedException>(() =>
{
_ = 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<ObjectDisposedException>(() =>
{
_ = 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<IOException>(() => 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<Stream>();
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<IOException>(async () => await leaseStream.DisposeAsync());
// Assert
Assert.False(Directory.Exists(cachePath));
}
/// <summary>
/// Creates the stream under test over the provided inner stream.
/// </summary>
/// <param name="innerStream">The stream over the cached segment.</param>
/// <returns>The created <see cref="TranscodingCacheLeaseStream"/>.</returns>
private TranscodingCacheLeaseStream CreateSut(Stream innerStream)
{
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(CreateCacheId());
return new TranscodingCacheLeaseStream(innerStream, lease);
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
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 _));
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
private sealed class ThrowingDisposeStream : MemoryStream
{
private readonly IOException _exception;
/// <summary>
/// Initializes a new instance of the <see cref="ThrowingDisposeStream"/> class.
/// </summary>
/// <param name="exception">The exception thrown when the stream is disposed.</param>
internal ThrowingDisposeStream(IOException exception)
{
_exception = exception;
}
/// <summary>
/// Releases the resources of the stream and then throws the configured exception.
/// </summary>
/// <param name="disposing">Whether the method is called from the <see cref="IDisposable.Dispose"/> method.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
throw _exception;
}
/// <summary>
/// Gets a failed value task that carries the configured exception.
/// </summary>
/// <returns>A failed <see cref="ValueTask"/>.</returns>
public override ValueTask DisposeAsync()
{
return ValueTask.FromException(_exception);
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheReaderLease"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheReaderLeaseTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReaderLeaseTests"/> class.
/// </summary>
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));
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
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 _));
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheReservation"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheReservationTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReservationTests"/> class.
/// </summary>
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();
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Creates a temporary output directory with a single file of the requested size.
/// </summary>
/// <param name="size">The size of the produced file, in bytes.</param>
/// <returns>The path of the created temporary output directory.</returns>
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;
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingOutputSizeTracker"/> class.
/// </summary>
[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;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingOutputSizeTrackerTests"/> class.
/// </summary>
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);
}
/// <summary>
/// Creates the segment list file with the requested size.
/// </summary>
/// <param name="size">The size of the segment list, in bytes.</param>
private void CreateSegmentList(int size)
{
File.WriteAllBytes(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME), new byte[size]);
}
/// <summary>
/// Creates a segment file with the requested zero based index and size.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <param name="size">The size of the segment, in bytes.</param>
private void CreateSegment(int segmentIndex, int size)
{
File.WriteAllBytes(GetSegmentPath(segmentIndex), new byte[size]);
}
/// <summary>
/// Appends the requested number of bytes to a segment file.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <param name="size">The number of bytes to append.</param>
private void AppendToSegment(int segmentIndex, int size)
{
AppendToFile(GetSegmentPath(segmentIndex), size);
}
/// <summary>
/// Appends the requested number of bytes to a file.
/// </summary>
/// <param name="filePath">The file to append to.</param>
/// <param name="size">The number of bytes to append.</param>
private static void AppendToFile(string filePath, int size)
{
using (FileStream stream = new(filePath, FileMode.Append, FileAccess.Write))
stream.Write(new byte[size], 0, size);
}
/// <summary>
/// Gets the path of the segment file of the requested zero based index.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <returns>The path of the segment file.</returns>
private string GetSegmentPath(int segmentIndex)
{
return Path.Combine(_temporaryDirectory, $"{SEGMENT_FILE_PREFIX}{segmentIndex:D6}{SEGMENT_FILE_EXTENSION}");
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingStartupInitializer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingStartupInitializerTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheDirectory;
private readonly TranscodingSettingsDto _settings;
private readonly TranscodingToolchainStatus _toolchainStatus;
private readonly ILogger<TranscodingStartupInitializer> _mockLogger;
private readonly TranscodingStartupInitializer _sut;
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingStartupInitializerTests"/> class.
/// </summary>
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<ILogger<TranscodingStartupInitializer>>();
_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<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[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;
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
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;
}
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
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);
}
}