mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 14:11:10 +00:00
Implements domain events queue processing and eventual consistency
This commit is contained in:
1 parent
f96cfa4a2f
commit
80e2ce0f82
10 files changed
+198
-9
No files matched your search
@@ -0,0 +1,72 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfully.
|
||||
/// </summary>
|
||||
public class EventualConsistencyMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<EventualConsistencyMiddleware> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EventualConsistencyMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the HTTP request pipeline.</param>
|
||||
public EventualConsistencyMiddleware(RequestDelegate next, ILogger<EventualConsistencyMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles incoming HTTP requests and ensures that domain events are published and the database transaction is committed upon successful request completion.
|
||||
/// </summary>
|
||||
/// <param name="context">The current HTTP context.</param>
|
||||
/// <param name="publisher">The domain event publisher used to publish events.</param>
|
||||
/// <param name="dbContext">The database context used to manage the transaction.</param>
|
||||
/// <param name="domainEventQueue">In memory queue containing the queued domain events.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using Lumina.Domain.Common.DependencyInjection;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Infrastructure.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -122,6 +123,9 @@ public class Program
|
||||
.WithDotNetFlag(true);
|
||||
});
|
||||
|
||||
// add the middleware that fires domain events and ensures eventual transactional consistency
|
||||
app.UseMiddleware<EventualConsistencyMiddleware>();
|
||||
|
||||
// create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API
|
||||
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
|
||||
string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);
|
||||
|
||||
Reference in new issue
Block a user