#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
///
/// Controls and observes the domain events handled through the .
///
[ExcludeFromCodeCoverage]
public sealed class DomainEventsQueueProbe
{
private readonly Lock _signalLock = new();
private readonly ConcurrentDictionary _dequeueAttemptsByPath = new();
private readonly ConcurrentDictionary> _dequeueSignalsByPath = new();
private TaskCompletionSource _enqueuedSignal = CreateSignal();
private TaskCompletionSource _enqueueReleaseSignal = CreateSignal();
private volatile bool _shouldBlockOnEnqueue;
private volatile bool _shouldThrowOnEnqueue;
private int _enqueueCount;
private int _dequeueCount;
///
/// Gets or sets whether enqueuing a domain event waits until the test releases it.
///
public bool ShouldBlockOnEnqueue
{
get { return _shouldBlockOnEnqueue; }
set { _shouldBlockOnEnqueue = value; }
}
///
/// Gets or sets whether enqueuing a domain event fails after the event is queued.
///
public bool ShouldThrowOnEnqueue
{
get { return _shouldThrowOnEnqueue; }
set { _shouldThrowOnEnqueue = value; }
}
///
/// Gets or sets how long a blocked enqueuing request waits for the test to release it.
///
public TimeSpan BlockTimeout { get; set; } = TimeSpan.FromSeconds(5);
///
/// Gets the number of domain events that were enqueued.
///
public int EnqueueCount => Volatile.Read(ref _enqueueCount);
///
/// Gets the number of domain events that were dequeued for publication.
///
public int DequeueCount => Volatile.Read(ref _dequeueCount);
///
/// Clears the recorded counts and signals, so that a test observes only the events handled after the reset.
///
public void Reset()
{
ShouldBlockOnEnqueue = false;
ShouldThrowOnEnqueue = false;
Interlocked.Exchange(ref _enqueueCount, 0);
Interlocked.Exchange(ref _dequeueCount, 0);
_dequeueAttemptsByPath.Clear();
_dequeueSignalsByPath.Clear();
lock (_signalLock)
{
_enqueuedSignal = CreateSignal();
_enqueueReleaseSignal = CreateSignal();
}
}
///
/// Records that a domain event was enqueued, optionally blocking or failing the enqueuing request.
///
public void RecordEnqueue()
{
Interlocked.Increment(ref _enqueueCount);
TaskCompletionSource enqueuedSignal;
TaskCompletionSource releaseSignal;
lock (_signalLock)
{
enqueuedSignal = _enqueuedSignal;
releaseSignal = _enqueueReleaseSignal;
}
enqueuedSignal.TrySetResult(true);
if (ShouldBlockOnEnqueue && !releaseSignal.Task.Wait(BlockTimeout))
throw new TimeoutException("The test did not release the queued domain event in time.");
if (ShouldThrowOnEnqueue)
throw new InvalidOperationException("The test forces the request to fail after its domain event was queued.");
}
///
/// Records that the queue was asked for a domain event on the request of .
///
/// The path of the request whose middleware dequeued the queue.
/// Whether the queue actually contained an event.
public void RecordDequeue(string path, bool wasDequeued)
{
_dequeueAttemptsByPath.AddOrUpdate(path, 1, (_, attemptCount) => attemptCount + 1);
TaskCompletionSource signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal());
signal.TrySetResult(true);
if (wasDequeued)
Interlocked.Increment(ref _dequeueCount);
}
///
/// Gets the number of dequeue attempts made for the request of .
///
/// The path of the request.
/// The number of dequeue attempts made for the request.
public int GetDequeueAttemptCount(string path)
{
return _dequeueAttemptsByPath.TryGetValue(path, out int attemptCount) ? attemptCount : 0;
}
///
/// Waits until a dequeue attempt is made for the request of .
///
/// The path of the request to observe.
/// The maximum time to wait.
/// A task that represents the asynchronous operation.
public async Task WaitForDequeueAsync(string path, TimeSpan timeout)
{
Task signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal()).Task;
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
if (completedTask != signal)
throw new TimeoutException($"The domain events queue was not dequeued for '{path}' within {timeout}.");
}
///
/// Waits until a domain event is enqueued.
///
/// The maximum time to wait.
/// A task that represents the asynchronous operation.
public async Task WaitForEnqueueAsync(TimeSpan timeout)
{
Task signal;
lock (_signalLock)
signal = _enqueuedSignal.Task;
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
if (completedTask != signal)
throw new TimeoutException($"A domain event was not enqueued within {timeout}.");
}
///
/// Releases an enqueuing request blocked by .
///
public void ReleaseEnqueue()
{
TaskCompletionSource releaseSignal;
lock (_signalLock)
releaseSignal = _enqueueReleaseSignal;
releaseSignal.TrySetResult(true);
}
///
/// Creates a completion source that resumes its continuations asynchronously.
///
/// The created completion source.
private static TaskCompletionSource CreateSignal()
{
return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
}