#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
///
/// Observes the domain events published through the real domain event publisher.
///
[ExcludeFromCodeCoverage]
public sealed class DomainEventPublicationProbe
{
private readonly Lock _signalLock = new();
private TaskCompletionSource _publishedSignal = CreateSignal();
private int _publicationCount;
///
/// Gets the number of domain events that were published.
///
public int PublicationCount => Volatile.Read(ref _publicationCount);
///
/// Gets whether the favorite of the last published event was visible from a separate database scope.
///
public bool WasFavoriteVisible { get; private set; }
///
/// Clears the recorded observations, so that a test observes only the events published after the reset.
///
public void Reset()
{
Interlocked.Exchange(ref _publicationCount, 0);
WasFavoriteVisible = false;
lock (_signalLock)
_publishedSignal = CreateSignal();
}
///
/// Records that a domain event was published, together with whether its favorite was visible at publication time.
///
/// Whether the favorite was visible from a separate database scope.
public void RecordPublication(bool wasFavoriteVisible)
{
WasFavoriteVisible = wasFavoriteVisible;
Interlocked.Increment(ref _publicationCount);
TaskCompletionSource signal;
lock (_signalLock)
signal = _publishedSignal;
signal.TrySetResult(true);
}
///
/// Waits until a domain event is published.
///
/// The maximum time to wait.
/// A task that represents the asynchronous operation.
public async Task WaitForPublicationAsync(TimeSpan timeout)
{
Task signal;
lock (_signalLock)
signal = _publishedSignal.Task;
Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false);
if (completedTask != signal)
throw new TimeoutException($"A domain event was not published within {timeout}.");
}
///
/// Creates a completion source that resumes its continuations asynchronously.
///
/// The created completion source.
private static TaskCompletionSource CreateSignal()
{
return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
}