mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #295 from BinaryAlley/feature/add-eventual-consistency-integration-tests
Adds integration tests for EventualConsistencyMiddleware transaction atomicity
This commit is contained in:
9 files changed
+799
No files matched your search
+209
@@ -0,0 +1,209 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||||
|
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
|
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
|
using Lumina.DataAccess.Core.UoW;
|
||||||
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
|
using Lumina.Presentation.Api.Common.Middlewares;
|
||||||
|
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.IntegrationTests.Common.Middlewares;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains integration tests for the <see cref="EventualConsistencyMiddleware"/> class through the real HTTP pipeline.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class EventualConsistencyMiddlewareTests : IClassFixture<EventualConsistencyApiFactory>, IAsyncLifetime
|
||||||
|
{
|
||||||
|
private const string FAVORITES_PATH = "/api/v1/users/me/favorites";
|
||||||
|
private const string LOGIN_PATH = "/api/v1/auth/login";
|
||||||
|
|
||||||
|
private static readonly TimeSpan s_probeTimeout = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
private HttpClient _client;
|
||||||
|
private readonly EventualConsistencyApiFactory _apiFactory;
|
||||||
|
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||||
|
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||||
|
private readonly List<Guid> _seededLibraryIds = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="EventualConsistencyMiddlewareTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiFactory">Injected in-memory API factory with observable transactions and domain events.</param>
|
||||||
|
public EventualConsistencyMiddlewareTests(EventualConsistencyApiFactory apiFactory)
|
||||||
|
{
|
||||||
|
_apiFactory = apiFactory;
|
||||||
|
_client = apiFactory.CreateClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes the authenticated API client, and clears the probes after the login request completed.
|
||||||
|
/// </summary>
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
_apiFactory.ResetProbes();
|
||||||
|
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||||
|
// The login request runs through the same middleware, so its dequeue of the response completion must finish before the probes observe the test request.
|
||||||
|
await _apiFactory.QueueProbe.WaitForDequeueAsync(LOGIN_PATH, s_probeTimeout);
|
||||||
|
_apiFactory.ResetProbes();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AddFavorite_WhenTheResponseSucceeds_ShouldPublishTheQueuedEventAfterCommittingTheTransaction()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid bookId = await SeedBookAsync(userId);
|
||||||
|
_apiFactory.ResetProbes();
|
||||||
|
_apiFactory.QueueProbe.ShouldBlockOnEnqueue = true;
|
||||||
|
Task<HttpResponseMessage> responseTask;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Act
|
||||||
|
// The POST runs on a dedicated task, so that a blocking domain event queue can never block the test thread that must release it.
|
||||||
|
responseTask = Task.Run(async () => await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId }));
|
||||||
|
await _apiFactory.QueueProbe.WaitForEnqueueAsync(s_probeTimeout);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
// The event is queued while the endpoint still runs, so it must not be published yet.
|
||||||
|
Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_apiFactory.QueueProbe.ReleaseEnqueue();
|
||||||
|
_apiFactory.QueueProbe.ShouldBlockOnEnqueue = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpResponseMessage response = await responseTask;
|
||||||
|
await _apiFactory.PublicationProbe.WaitForPublicationAsync(s_probeTimeout);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.True(_apiFactory.PublicationProbe.WasFavoriteVisible);
|
||||||
|
Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount);
|
||||||
|
Assert.Equal(1, _apiFactory.QueueProbe.DequeueCount);
|
||||||
|
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AddFavorite_WhenTheRequestFailsAfterQueueingTheEvent_ShouldRollBackTheTransactionAndNotPublishTheEvent()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = GetCurrentUserId();
|
||||||
|
Guid bookId = await SeedBookAsync(userId);
|
||||||
|
_apiFactory.ResetProbes();
|
||||||
|
_apiFactory.QueueProbe.ShouldThrowOnEnqueue = true;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId });
|
||||||
|
await _apiFactory.TransactionProbe.WaitForRollbackAsync(FAVORITES_PATH, s_probeTimeout);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||||
|
Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount);
|
||||||
|
Assert.Equal(0, _apiFactory.QueueProbe.DequeueCount);
|
||||||
|
Assert.Equal(0, _apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH));
|
||||||
|
Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount);
|
||||||
|
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_apiFactory.QueueProbe.ShouldThrowOnEnqueue = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetFavorites_WhenCalled_ShouldRunThroughTheEventualConsistencyMiddleware()
|
||||||
|
{
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.GetAsync(FAVORITES_PATH);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
// The middleware dequeues the events only after committing a successful request, so a dequeue attempt for this path proves the pipeline ran through it.
|
||||||
|
await _apiFactory.QueueProbe.WaitForDequeueAsync(FAVORITES_PATH, s_probeTimeout);
|
||||||
|
Assert.True(_apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH) > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Seeds a book of a book library owned by <paramref name="userId"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||||
|
/// <returns>The Id of the seeded book.</returns>
|
||||||
|
private async Task<Guid> SeedBookAsync(Guid userId)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
Guid libraryId = Guid.CreateVersion7();
|
||||||
|
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||||
|
id: libraryId,
|
||||||
|
userId: userId,
|
||||||
|
title: $"Eventual Consistency Library-{Guid.NewGuid():N}",
|
||||||
|
libraryType: LibraryType.EBook,
|
||||||
|
contentLocations: []));
|
||||||
|
Guid bookId = Guid.CreateVersion7();
|
||||||
|
dbContext.Books.Add(_bookEntityFixture.Create(
|
||||||
|
id: bookId,
|
||||||
|
libraryId: libraryId,
|
||||||
|
title: $"Eventual Consistency Book-{Guid.NewGuid():N}",
|
||||||
|
includeMetadata: false));
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
_seededLibraryIds.Add(libraryId);
|
||||||
|
return bookId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the Id of the currently authenticated test user.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>The Id of the authenticated test user.</returns>
|
||||||
|
private Guid GetCurrentUserId()
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||||
|
return user.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes the data seeded by the test and the API factory test user.
|
||||||
|
/// </summary>
|
||||||
|
public async Task DisposeAsync()
|
||||||
|
{
|
||||||
|
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||||
|
{
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||||
|
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||||
|
Guid? userId = await dbContext.Users
|
||||||
|
.Where(user => user.Username == _apiFactory.TestUsername)
|
||||||
|
.Select(user => (Guid?)user.Id)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (userId is not null)
|
||||||
|
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => favorite.UserId == userId.Value));
|
||||||
|
dbContext.Books.RemoveRange(dbContext.Books.Where(book => bookIds.Contains(book.Id)));
|
||||||
|
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
await _apiFactory.RemoveTestUserAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
+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.UseSqlite(_sharedInMemoryConnectionString);
|
||||||
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
||||||
|
ConfigureDbContextOptions(serviceProvider, options);
|
||||||
});
|
});
|
||||||
// Configure JWT authentication for testing.
|
// Configure JWT authentication for testing.
|
||||||
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
|
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>
|
/// <summary>
|
||||||
/// Resets the in-memory SQLite database to its original state.
|
/// Resets the in-memory SQLite database to its original state.
|
||||||
/// </summary>
|
/// </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