diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 905573aa..5422de9d 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -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(); + return services; } } diff --git a/src/Lumina.Application/Common/DomainEvents/DomainEventsQueue.cs b/src/Lumina.Application/Common/DomainEvents/DomainEventsQueue.cs new file mode 100644 index 00000000..9dbd62c1 --- /dev/null +++ b/src/Lumina.Application/Common/DomainEvents/DomainEventsQueue.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using System.Collections.Concurrent; +#endregion + +namespace Lumina.Application.Common.DomainEvents; + +/// +/// Represents a thread-safe queue for managing domain events. +/// +public class DomainEventsQueue : IDomainEventsQueue +{ + private readonly ConcurrentQueue _queue = new(); + + /// + /// Adds a domain event to the queue. + /// + /// The domain event to enqueue. + public void Enqueue(IDomainEvent domainEvent) + { + _queue.Enqueue(domainEvent); + } + + /// + /// Attempts to remove and return the domain event at the beginning of the queue. + /// + /// When this method returns, contains the domain event removed from the queue, or the default value of if the queue is empty. + /// + /// if a domain event was successfully dequeued, otherwise. + public bool TryDequeue(out IDomainEvent domainEvent) + { + return _queue.TryDequeue(out domainEvent!); + } +} diff --git a/src/Lumina.Application/Common/DomainEvents/IDomainEventsQueue.cs b/src/Lumina.Application/Common/DomainEvents/IDomainEventsQueue.cs new file mode 100644 index 00000000..cd802424 --- /dev/null +++ b/src/Lumina.Application/Common/DomainEvents/IDomainEventsQueue.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +#endregion + +namespace Lumina.Application.Common.DomainEvents; + +/// +/// Interface for a thread-safe queue for managing domain events. +/// +public interface IDomainEventsQueue +{ + /// + /// Adds a domain event to the queue. + /// + /// The domain event to enqueue. + void Enqueue(IDomainEvent domainEvent); + + /// + /// Attempts to remove and return the domain event at the beginning of the queue. + /// + /// When this method returns, contains the domain event removed from the queue, or the default value of if the queue is empty. + /// + /// if a domain event was successfully dequeued, otherwise. + bool TryDequeue(out IDomainEvent domainEvent); +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index b8f607f9..e856a08b 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -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>() - .ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly); + modelBuilder.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly); base.OnModelCreating(modelBuilder); } diff --git a/src/Lumina.Domain/Common/Events/IDomainEvent.cs b/src/Lumina.Domain/Common/Events/IDomainEvent.cs index 58265749..fbb4ed46 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEvent.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEvent.cs @@ -1,4 +1,5 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== +using Mediator; using System; #endregion @@ -7,15 +8,15 @@ namespace Lumina.Domain.Common.Events; /// /// Interface defining a domain event. /// -public interface IDomainEvent +public interface IDomainEvent : INotification { /// - /// Gets the id of the domain event. + /// Gets the Id of the domain event. /// Guid Id { get; } /// /// Gets the date and time when the domain event occurred. /// - DateTime OccurredOn { get; } -} \ No newline at end of file + DateTime OccurredOnUtc { get; } +} diff --git a/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs b/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs new file mode 100644 index 00000000..f25bdb7a --- /dev/null +++ b/src/Lumina.Domain/Common/Exceptions/EventualConsistencyException.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Common.Exceptions; + +/// +/// Custom exception for domain aggregates eventual consistency. +/// +public class EventualConsistencyException : Exception +{ + /// + /// Gets the primary error associated with the eventual consistency failure. + /// + public Error EventualConsistencyError { get; } + + /// + /// Gets a list of underlying errors that contributed to the eventual consistency failure. + /// + public List UnderlyingErrors { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The primary error representing the eventual consistency issue. + /// A list of additional errors contributing to the issue, or if no additional errors exist. + public EventualConsistencyException(Error eventualConsistencyError, List? underlyingErrors = null) : base(message: eventualConsistencyError.Description) + { + EventualConsistencyError = eventualConsistencyError; + UnderlyingErrors = underlyingErrors ?? []; + } +} diff --git a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs index 97a54a34..76822219 100644 --- a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs +++ b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs @@ -1,3 +1,8 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using System.Collections.Generic; +#endregion + namespace Lumina.Domain.Common.Models.Core; /// @@ -6,6 +11,8 @@ namespace Lumina.Domain.Common.Models.Core; /// The type representing the unique identifier for the Aggregate Root. It should be a non-nullable type. public abstract class AggregateRoot : Entity where TId : notnull { + protected readonly List _domainEvents = []; + /// /// Initializes a new instance of the class. /// @@ -22,4 +29,15 @@ public abstract class AggregateRoot : Entity where TId : notnull { } + + /// + /// Retrieves and clears all domain events associated with this aggregate root. + /// + /// A list of all domain events that were raised by this aggregate root. + public List PopDomainEvents() + { + List domainEventsCopy = [.. _domainEvents]; + _domainEvents.Clear(); + return domainEventsCopy; + } } diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 46d926bd..8ad251e1 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -19,6 +19,7 @@ + diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs new file mode 100644 index 00000000..c1568008 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -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; + +/// +/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfully. +/// +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. + 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); + } +} diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 702cf680..f2bbb0cf 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -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(); + // 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("MediaSettings:RootDirectory") ?? string.Empty; string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);