#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DomainEvents;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Mediator;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Common.Middlewares;
///
/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfuly.
///
public class EventualConsistencyMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
/// The next middleware in the HTTP request pipeline.
/// Injected service for logging.
public EventualConsistencyMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
///
/// Handles incoming HTTP requests and ensures that domain events are published and the database transaction is committed upon successful request completion.
///
/// The current HTTP context.
/// The domain event publisher used to publish events.
/// The database context used to manage the transaction.
/// In memory queue containing the queued domain events.
public async Task InvokeAsync(HttpContext context, IPublisher publisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue)
{
// begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation
IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false);
// register an action to be executed once the response is completed (the user already received a response for the request)
context.Response.OnCompleted(async () =>
{
try
{
// only proceed if the response status code indicates success
if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300)
{
// check if domain events exist in the channel queue and publish them
while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent))
await publisher.Publish(nextEvent);
// commit the transaction
await transaction.CommitAsync().ConfigureAwait(false);
}
}
catch (EventualConsistencyException ex)
{
_logger.LogCritical(ex, "Failed to perform eventual consistency");
}
finally
{
// DisposeAsync automatically roles back any changes, if a call to CommitAsync was not performed prior
await transaction.DisposeAsync().ConfigureAwait(false);
}
});
await _next(context).ConfigureAwait(false);
}
}