#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
///
/// Observes the database transactions rolled back on each request through the .
///
[ExcludeFromCodeCoverage]
public sealed class TransactionProbe
{
private readonly Lock _signalLock = new();
private readonly Dictionary> _rollbackSignalsByPath = [];
///
/// Clears the recorded signals, so that a test observes only the rollbacks that happen after the reset.
///
public void Reset()
{
lock (_signalLock)
_rollbackSignalsByPath.Clear();
}
///
/// Records that the transaction of the request of was rolled back.
///
/// The path of the request whose transaction was rolled back.
public void RecordRolledBack(string path)
{
TaskCompletionSource signal;
lock (_signalLock)
{
if (!_rollbackSignalsByPath.TryGetValue(path, out signal!))
{
signal = CreateSignal();
_rollbackSignalsByPath[path] = signal;
}
}
signal.TrySetResult(true);
}
///
/// Waits until the transaction of the request of is rolled back.
///
/// The path of the request to observe.
/// The maximum time to wait.
/// A task that represents the asynchronous operation.
public async Task WaitForRollbackAsync(string path, TimeSpan timeout)
{
Task signal;
lock (_signalLock)
{
if (!_rollbackSignalsByPath.TryGetValue(path, out TaskCompletionSource? signalSource))
{
signalSource = CreateSignal();
_rollbackSignalsByPath[path] = signalSource;
}
signal = signalSource.Task;
}
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
if (completedTask != signal)
throw new TimeoutException($"The transaction of '{path}' was not rolled back within {timeout}.");
}
///
/// Creates a completion source that resumes its continuations asynchronously.
///
/// The created completion source.
private static TaskCompletionSource CreateSignal()
{
return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
}