Implements domain events queue processing and eventual consistency

This commit is contained in:
BinaryAlley committed 2025-01-04 17:42:40 +02:00
1 parent f96cfa4a2f
commit 80e2ce0f82
10 files changed
+198 -9

No files matched your search

@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Lumina.Application.Common.DomainEvents;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
@@ -33,6 +34,8 @@ public static class ApplicationLayerServices
// register fluent validators
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
services.AddScoped<IDomainEventsQueue, DomainEventsQueue>();
return services;
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using System.Collections.Concurrent;
#endregion
namespace Lumina.Application.Common.DomainEvents;
/// <summary>
/// Represents a thread-safe queue for managing domain events.
/// </summary>
public class DomainEventsQueue : IDomainEventsQueue
{
private readonly ConcurrentQueue<IDomainEvent> _queue = new();
/// <summary>
/// Adds a domain event to the queue.
/// </summary>
/// <param name="domainEvent">The domain event to enqueue.</param>
public void Enqueue(IDomainEvent domainEvent)
{
_queue.Enqueue(domainEvent);
}
/// <summary>
/// Attempts to remove and return the domain event at the beginning of the queue.
/// </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)
{
return _queue.TryDequeue(out domainEvent!);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
#endregion
namespace Lumina.Application.Common.DomainEvents;
/// <summary>
/// Interface for a thread-safe queue for managing domain events.
/// </summary>
public interface IDomainEventsQueue
{
/// <summary>
/// Adds a domain event to the queue.
/// </summary>
/// <param name="domainEvent">The domain event to enqueue.</param>
void Enqueue(IDomainEvent domainEvent);
/// <summary>
/// Attempts to remove and return the domain event at the beginning of the queue.
/// </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>
bool TryDequeue(out IDomainEvent domainEvent);
}
@@ -3,9 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Events;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Core.UoW;
@@ -41,8 +39,7 @@ public class LuminaDbContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// find all the entity configurations in the assembly and apply them
modelBuilder.Ignore<List<IDomainEvent>>()
.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Mediator;
using System;
#endregion
@@ -7,15 +8,15 @@ namespace Lumina.Domain.Common.Events;
/// <summary>
/// Interface defining a domain event.
/// </summary>
public interface IDomainEvent
public interface IDomainEvent : INotification
{
/// <summary>
/// Gets the id of the domain event.
/// Gets the Id of the domain event.
/// </summary>
Guid Id { get; }
/// <summary>
/// Gets the date and time when the domain event occurred.
/// </summary>
DateTime OccurredOn { get; }
}
DateTime OccurredOnUtc { get; }
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Common.Exceptions;
/// <summary>
/// Custom exception for domain aggregates eventual consistency.
/// </summary>
public class EventualConsistencyException : Exception
{
/// <summary>
/// Gets the primary error associated with the eventual consistency failure.
/// </summary>
public Error EventualConsistencyError { get; }
/// <summary>
/// Gets a list of underlying errors that contributed to the eventual consistency failure.
/// </summary>
public List<Error> UnderlyingErrors { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EventualConsistencyException"/> class.
/// </summary>
/// <param name="eventualConsistencyError">The primary error representing the eventual consistency issue.</param>
/// <param name="underlyingErrors">A list of additional errors contributing to the issue, or <see langword="null"/> if no additional errors exist.</param>
public EventualConsistencyException(Error eventualConsistencyError, List<Error>? underlyingErrors = null) : base(message: eventualConsistencyError.Description)
{
EventualConsistencyError = eventualConsistencyError;
UnderlyingErrors = underlyingErrors ?? [];
}
}
@@ -1,3 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Common.Models.Core;
/// <summary>
@@ -6,6 +11,8 @@ namespace Lumina.Domain.Common.Models.Core;
/// <typeparam name="TId">The type representing the unique identifier for the Aggregate Root. It should be a non-nullable type.</typeparam>
public abstract class AggregateRoot<TId> : Entity<TId> where TId : notnull
{
protected readonly List<IDomainEvent> _domainEvents = [];
/// <summary>
/// Initializes a new instance of the <see cref="AggregateRoot{TId}"/> class.
/// </summary>
@@ -22,4 +29,15 @@ public abstract class AggregateRoot<TId> : Entity<TId> where TId : notnull
{
}
/// <summary>
/// Retrieves and clears all domain events associated with this aggregate root.
/// </summary>
/// <returns>A list of all domain events that were raised by this aggregate root.</returns>
public List<IDomainEvent> PopDomainEvents()
{
List<IDomainEvent> domainEventsCopy = [.. _domainEvents];
_domainEvents.Clear();
return domainEventsCopy;
}
}
+1
View File
@@ -19,6 +19,7 @@
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageReference Include="System.IO.Abstractions" Version="21.1.3" />
<PackageReference Include="System.IO.FileSystem.AccessControl" Version="5.0.0" />
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
</ItemGroup>
</Project>
@@ -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);
}
}
+4
View File
@@ -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);