mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 16:11:10 +00:00
Adds integration tests for EventualConsistencyMiddleware transaction atomicity
This commit is contained in:
1 parent
a07ecf449a
commit
d516e94346
9 files changed
+799
No files matched your search
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the domain events published through the real domain event publisher.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventPublicationProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private TaskCompletionSource<bool> _publishedSignal = CreateSignal();
|
||||
private int _publicationCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were published.
|
||||
/// </summary>
|
||||
public int PublicationCount => Volatile.Read(ref _publicationCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the favorite of the last published event was visible from a separate database scope.
|
||||
/// </summary>
|
||||
public bool WasFavoriteVisible { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded observations, so that a test observes only the events published after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
Interlocked.Exchange(ref _publicationCount, 0);
|
||||
WasFavoriteVisible = false;
|
||||
lock (_signalLock)
|
||||
_publishedSignal = CreateSignal();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was published, together with whether its favorite was visible at publication time.
|
||||
/// </summary>
|
||||
/// <param name="wasFavoriteVisible">Whether the favorite was visible from a separate database scope.</param>
|
||||
public void RecordPublication(bool wasFavoriteVisible)
|
||||
{
|
||||
WasFavoriteVisible = wasFavoriteVisible;
|
||||
Interlocked.Increment(ref _publicationCount);
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
signal = _publishedSignal;
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is published.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Controls and observes the domain events handled through the <see cref="ProbingDomainEventsQueue"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventsQueueProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly ConcurrentDictionary<string, int> _dequeueAttemptsByPath = new();
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> _dequeueSignalsByPath = new();
|
||||
private TaskCompletionSource<bool> _enqueuedSignal = CreateSignal();
|
||||
private TaskCompletionSource<bool> _enqueueReleaseSignal = CreateSignal();
|
||||
private volatile bool _shouldBlockOnEnqueue;
|
||||
private volatile bool _shouldThrowOnEnqueue;
|
||||
private int _enqueueCount;
|
||||
private int _dequeueCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event waits until the test releases it.
|
||||
/// </summary>
|
||||
public bool ShouldBlockOnEnqueue
|
||||
{
|
||||
get { return _shouldBlockOnEnqueue; }
|
||||
set { _shouldBlockOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event fails after the event is queued.
|
||||
/// </summary>
|
||||
public bool ShouldThrowOnEnqueue
|
||||
{
|
||||
get { return _shouldThrowOnEnqueue; }
|
||||
set { _shouldThrowOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how long a blocked enqueuing request waits for the test to release it.
|
||||
/// </summary>
|
||||
public TimeSpan BlockTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were enqueued.
|
||||
/// </summary>
|
||||
public int EnqueueCount => Volatile.Read(ref _enqueueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were dequeued for publication.
|
||||
/// </summary>
|
||||
public int DequeueCount => Volatile.Read(ref _dequeueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded counts and signals, so that a test observes only the events handled after the reset.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was enqueued, optionally blocking or failing the enqueuing request.
|
||||
/// </summary>
|
||||
public void RecordEnqueue()
|
||||
{
|
||||
Interlocked.Increment(ref _enqueueCount);
|
||||
TaskCompletionSource<bool> enqueuedSignal;
|
||||
TaskCompletionSource<bool> 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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the queue was asked for a domain event on the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose middleware dequeued the queue.</param>
|
||||
/// <param name="wasDequeued">Whether the queue actually contained an event.</param>
|
||||
public void RecordDequeue(string path, bool wasDequeued)
|
||||
{
|
||||
_dequeueAttemptsByPath.AddOrUpdate(path, 1, (_, attemptCount) => attemptCount + 1);
|
||||
TaskCompletionSource<bool> signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal());
|
||||
signal.TrySetResult(true);
|
||||
if (wasDequeued)
|
||||
Interlocked.Increment(ref _dequeueCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of dequeue attempts made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request.</param>
|
||||
/// <returns>The number of dequeue attempts made for the request.</returns>
|
||||
public int GetDequeueAttemptCount(string path)
|
||||
{
|
||||
return _dequeueAttemptsByPath.TryGetValue(path, out int attemptCount) ? attemptCount : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a dequeue attempt is made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is enqueued.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases an enqueuing request blocked by <see cref="ShouldBlockOnEnqueue"/>.
|
||||
/// </summary>
|
||||
public void ReleaseEnqueue()
|
||||
{
|
||||
TaskCompletionSource<bool> releaseSignal;
|
||||
lock (_signalLock)
|
||||
releaseSignal = _enqueueReleaseSignal;
|
||||
releaseSignal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Authenticated API factory whose database transactions and domain events are observable through probes.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class EventualConsistencyApiFactory : AuthenticatedLuminaApiFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the probe that controls and observes the domain events queue.
|
||||
/// </summary>
|
||||
public DomainEventsQueueProbe QueueProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the published domain events.
|
||||
/// </summary>
|
||||
public DomainEventPublicationProbe PublicationProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the database transaction lifecycle.
|
||||
/// </summary>
|
||||
public TransactionProbe TransactionProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Clears every probe, so that a test observes only the activity started after the reset.
|
||||
/// </summary>
|
||||
public void ResetProbes()
|
||||
{
|
||||
QueueProbe.Reset();
|
||||
PublicationProbe.Reset();
|
||||
TransactionProbe.Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transaction probe to the database context options.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
protected override void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
|
||||
{
|
||||
base.ConfigureDbContextOptions(serviceProvider, options);
|
||||
// The test services are registered before the shared factory configures the database, so the interceptor is available even from the
|
||||
// throwaway provider the shared factory uses to migrate the database, and a missing registration fails host construction loudly.
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<TransactionProbeInterceptor>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host, replacing the domain events queue and registering the recording event handler.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
// Registering the test services before the shared factory configures the database makes them available to its migration provider too.
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddSingleton(QueueProbe);
|
||||
services.AddSingleton(PublicationProbe);
|
||||
services.AddSingleton(TransactionProbe);
|
||||
services.AddSingleton<TransactionProbeInterceptor>();
|
||||
services.RemoveAll<IDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventsQueue, ProbingDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventHandler<FavoriteAddedDomainEvent>, RecordingFavoriteAddedDomainEventHandler>();
|
||||
});
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
+16
@@ -84,6 +84,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
options.UseSqlite(_sharedInMemoryConnectionString);
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
||||
ConfigureDbContextOptions(serviceProvider, options);
|
||||
});
|
||||
// Configure JWT authentication for testing.
|
||||
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
|
||||
@@ -110,6 +111,21 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures additional options of the database context used by the tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The hook is invoked every time the options of a database context are built, including once for the throwaway provider that migrates the
|
||||
/// database while the host is configured and once for the final provider of the host. Derived factories that resolve test services from the
|
||||
/// provided <paramref name="serviceProvider"/> must register those services before the shared factory configures the database, and must call
|
||||
/// this base implementation so that options added here are never silently skipped.
|
||||
/// </remarks>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
protected virtual void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the in-memory SQLite database to its original state.
|
||||
/// </summary>
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Domain events queue that exposes its enqueuing and dequeuing to a <see cref="DomainEventsQueueProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class ProbingDomainEventsQueue : IDomainEventsQueue
|
||||
{
|
||||
private readonly ConcurrentQueue<IDomainEvent> _queue = new();
|
||||
private readonly DomainEventsQueueProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProbingDomainEventsQueue"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that controls and observes the queue.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request that dequeues the queue.</param>
|
||||
public ProbingDomainEventsQueue(DomainEventsQueueProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a domain event to the queue, before reporting it to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to enqueue.</param>
|
||||
public void Enqueue(IDomainEvent domainEvent)
|
||||
{
|
||||
_queue.Enqueue(domainEvent);
|
||||
_probe.RecordEnqueue();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to remove and return the domain event at the beginning of the queue, reporting the attempt to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">When this method returns, contains the domain event removed from the queue, or the default value of <see cref="IDomainEvent"/> if the queue is empty.
|
||||
/// </param>
|
||||
/// <returns><see langword="true"/> if a domain event was successfully dequeued, <see langword="false"/> otherwise.</returns>
|
||||
public bool TryDequeue(out IDomainEvent domainEvent)
|
||||
{
|
||||
bool wasDequeued = _queue.TryDequeue(out domainEvent!);
|
||||
string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty;
|
||||
_probe.RecordDequeue(path, wasDequeued);
|
||||
return wasDequeued;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event handler that records the publication of a <see cref="FavoriteAddedDomainEvent"/>, together with the state visible at publication time.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class RecordingFavoriteAddedDomainEventHandler : IDomainEventHandler<FavoriteAddedDomainEvent>
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly DomainEventPublicationProbe _publicationProbe;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecordingFavoriteAddedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="scopeFactory">Injected factory used to create a database scope independent from the request scope.</param>
|
||||
/// <param name="publicationProbe">Injected probe that records the published event.</param>
|
||||
public RecordingFavoriteAddedDomainEventHandler(IServiceScopeFactory scopeFactory, DomainEventPublicationProbe publicationProbe)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_publicationProbe = publicationProbe;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the published <paramref name="domainEvent"/>, checking whether its favorite was already committed.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event being published.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async ValueTask HandleAsync(FavoriteAddedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// A separate scope and context prove that the row is visible to other connections, which is only true after the request transaction was committed.
|
||||
using IServiceScope scope = _scopeFactory.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bool wasFavoriteVisible = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.AnyAsync(favorite => favorite.Id == domainEvent.FavoriteId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_publicationProbe.RecordPublication(wasFavoriteVisible);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the database transactions rolled back on each request through the <see cref="TransactionProbeInterceptor"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly Dictionary<string, TaskCompletionSource<bool>> _rollbackSignalsByPath = [];
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded signals, so that a test observes only the rollbacks that happen after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
lock (_signalLock)
|
||||
_rollbackSignalsByPath.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the transaction of the request of <paramref name="path"/> was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose transaction was rolled back.</param>
|
||||
public void RecordRolledBack(string path)
|
||||
{
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out signal!))
|
||||
{
|
||||
signal = CreateSignal();
|
||||
_rollbackSignalsByPath[path] = signal;
|
||||
}
|
||||
}
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the transaction of the request of <paramref name="path"/> is rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForRollbackAsync(string path, TimeSpan timeout)
|
||||
{
|
||||
Task signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out TaskCompletionSource<bool>? 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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Database transaction interceptor that reports the rolled back transactions to a <see cref="TransactionProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbeInterceptor : DbTransactionInterceptor
|
||||
{
|
||||
private readonly TransactionProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TransactionProbeInterceptor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that records the rolled back transactions.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request whose transaction was rolled back.</param>
|
||||
public TransactionProbeInterceptor(TransactionProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default)
|
||||
{
|
||||
RecordRolledBack();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back synchronously.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData)
|
||||
{
|
||||
RecordRolledBack();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the rolled back transaction of the current request to the probe.
|
||||
/// </summary>
|
||||
private void RecordRolledBack()
|
||||
{
|
||||
string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty;
|
||||
_probe.RecordRolledBack(path);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user