#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Presentation.Api.Common.Http; using Lumina.Presentation.Api.Common.Middlewares; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares; /// /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class EventualConsistencyMiddlewareTests { private readonly EventualConsistencyMiddleware _sut; private bool _nextInvoked; /// /// Initializes a new instance of the class. /// public EventualConsistencyMiddlewareTests() { ILogger mockLogger = Substitute.For>(); _sut = new EventualConsistencyMiddleware( context => { _nextInvoked = true; return Task.CompletedTask; }, mockLogger); } [Fact] public async Task InvokeAsync_WhenEndpointOptsOutThroughMetadata_ShouldInvokeNextWithoutTouchingTheDatabase() { // Arrange DefaultHttpContext context = new(); context.SetEndpoint(new Endpoint( requestDelegate: null, new EndpointMetadataCollection(new SkipEventualConsistencyMetadata()), displayName: "GetTrackStream")); // Act // The database, the domain event publisher and the domain events queue are deliberately not supplied: an endpoint that opted out through // metadata must invoke the next delegate without touching any of them, which is exactly what a long lived stream needs. await _sut.InvokeAsync(context, null!, null!, null!); // Assert Assert.True(_nextInvoked); } [Fact] public async Task InvokeAsync_WhenTheClientAbortsAfterASuccessfulOperation_ShouldStillCommitTheTransaction() { // Arrange using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext dbContext = CreateContext(anchorConnection); using UnitOfWork unitOfWork = new(dbContext, Substitute.For()); await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); CapturingHttpResponseFeature responseFeature = new(); DefaultHttpContext httpContext = new(); httpContext.Features.Set(responseFeature); httpContext.Request.Path = "/api/v1/probe"; httpContext.Response.StatusCode = StatusCodes.Status200OK; using CancellationTokenSource cancellationTokenSource = new(); httpContext.RequestAborted = cancellationTokenSource.Token; ILogger mockLogger = Substitute.For>(); EventualConsistencyMiddleware sut = new( async requestContext => { await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);"); // The abort happens after the operation has completed, which is exactly when the response token can already be cancelled as the completion callback runs. cancellationTokenSource.Cancel(); }, mockLogger); IDomainEventPublisher mockPublisher = Substitute.For(); IDomainEventsQueue mockQueue = Substitute.For(); // Act await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue); await responseFeature.InvokeCompletedCallbacksAsync(); // Assert using LuminaDbContext verificationContext = CreateContext(anchorConnection); int committedCount = await verificationContext.Database .SqlQueryRaw("SELECT COUNT(*) AS \"Value\" FROM CommitProbe") .SingleAsync(); Assert.Equal(1, committedCount); } [Fact] public async Task InvokeAsync_WhenTheResponseIsNotSuccessful_ShouldRollBackTheTransactionAndTheEvents() { // Arrange using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext dbContext = CreateContext(anchorConnection); using UnitOfWork unitOfWork = new(dbContext, Substitute.For()); await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); CapturingHttpResponseFeature responseFeature = new(); DefaultHttpContext httpContext = new(); httpContext.Features.Set(responseFeature); httpContext.Request.Path = "/api/v1/probe"; ILogger mockLogger = Substitute.For>(); EventualConsistencyMiddleware sut = new( async requestContext => { await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);"); // A client abort is reported by the exception handling middleware as a non-success status, even though the request reached the database. requestContext.Response.StatusCode = StatusCodes.Status499ClientClosedRequest; }, mockLogger); IDomainEventPublisher mockPublisher = Substitute.For(); IDomainEventsQueue mockQueue = Substitute.For(); // Act await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue); await responseFeature.InvokeCompletedCallbacksAsync(); // Assert using LuminaDbContext verificationContext = CreateContext(anchorConnection); int committedCount = await verificationContext.Database .SqlQueryRaw("SELECT COUNT(*) AS \"Value\" FROM CommitProbe") .SingleAsync(); Assert.Equal(0, committedCount); await mockPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); } [Fact] public async Task InvokeAsync_WhenTheCommitFails_ShouldRollBackTheTransactionAndLogTheFailure() { // Arrange CapturingHttpResponseFeature responseFeature = new(); DefaultHttpContext httpContext = new(); httpContext.Features.Set(responseFeature); httpContext.Request.Path = "/api/v1/probe"; httpContext.Response.StatusCode = StatusCodes.Status200OK; ILogger mockLogger = Substitute.For>(); EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger); IUnitOfWork mockUnitOfWork = Substitute.For(); mockUnitOfWork .CommitTransactionAsync(Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("commit failed"))); IDomainEventPublisher mockPublisher = Substitute.For(); IDomainEventsQueue mockQueue = Substitute.For(); // Act await sut.InvokeAsync(httpContext, mockPublisher, mockUnitOfWork, mockQueue); await responseFeature.InvokeCompletedCallbacksAsync(); // Assert // The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit. await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any()); await mockPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); } /// /// Creates a context backed by the provided in-memory SQLite connection. /// /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. /// The created context. private static LuminaDbContext CreateContext(SqliteConnection anchorConnection) { LuminaDbContext context = new(new DbContextOptionsBuilder() .UseSqlite(anchorConnection.ConnectionString) .Options); context.Database.EnsureCreated(); return context; } /// /// Response feature that captures the completed callbacks so a test can run them when the response ends. /// private sealed class CapturingHttpResponseFeature : IHttpResponseFeature { private readonly List> _completedCallbacks = []; /// /// Gets or sets the HTTP status code of the response. /// public int StatusCode { get; set; } = StatusCodes.Status200OK; /// /// Gets or sets the reason phrase of the response. /// public string? ReasonPhrase { get; set; } /// /// Gets or sets the response headers. /// public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); /// /// Gets or sets the response body stream. /// public Stream Body { get; set; } = Stream.Null; /// /// Gets a value indicating whether the response has already started. /// public bool HasStarted => false; /// /// Registers a callback to be invoked when the response is about to start. /// /// The callback to invoke. /// The state passed to the callback. public void OnStarting(Func callback, object state) { } /// /// Registers a callback to be invoked when the response has completed. /// /// The callback to invoke. /// The state passed to the callback. public void OnCompleted(Func callback, object state) { _completedCallbacks.Add(() => callback(state)); } /// /// Invokes every callback that was registered through . /// /// A task representing the asynchronous operation. public async Task InvokeCompletedCallbacksAsync() { foreach (Func callback in _completedCallbacks) await callback(); } } }