diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs index 895578a88ed..f8df68805fa 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs @@ -40,7 +40,7 @@ public sealed class PostgresOutboxProcessor /// The signal used to wake the processor when new outbox messages are enqueued. /// /// - /// The outbox options containing the SQL queries and connection factory. + /// The options for this outbox processor. /// internal PostgresOutboxProcessor( ILogger logger, @@ -56,7 +56,7 @@ internal PostgresOutboxProcessor( _signal = signal; _contextPool = pools.DispatchContext; _options = options; - _timeProvider = services.GetService() ?? TimeProvider.System; + _timeProvider = services.GetTimeProvider(); } /// @@ -66,36 +66,40 @@ internal PostgresOutboxProcessor( /// A token that signals when the processor should stop. public async Task ProcessAsync(CancellationToken cancellationToken) { - while (!cancellationToken.IsCancellationRequested) + using var signalCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + try { - using var joinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var signaled = _signal.WaitAsync(signalCts.Token); - try + while (!cancellationToken.IsCancellationRequested) { - var signaled = _signal.WaitAsync(joinedCts.Token); - var nextPollingInterval = await ProcessPendingAsync(cancellationToken); + var delay = _options.PollingInterval; - if (nextPollingInterval is not null) + if (nextPollingInterval is { } interval && interval < delay) { - _logger.OutboxProcessorSleeping(nextPollingInterval.Value); - - await Task.WhenAny(Task.Delay(nextPollingInterval.Value, cancellationToken), signaled); + delay = interval; + _logger.OutboxProcessorSleeping(delay); } - else + + using var delayCts = new CancellationTokenSource(); + await Task.WhenAny(Task.Delay(delay, delayCts.Token), signaled); + delayCts.TryCancel(); + + if (signaled.IsCompleted) { await signaled; + signaled = _signal.WaitAsync(signalCts.Token); } } - catch (OperationCanceledException) - { - joinedCts.TryCancel(); - } - catch - { - joinedCts.TryCancel(); - throw; - } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + finally + { + signalCts.TryCancel(); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 1e16b12ac83..a01a26481c9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Mocha.EntityFrameworkCore; @@ -11,30 +12,23 @@ namespace Mocha.Outbox; /// -/// Provides extension methods on for registering -/// the Postgres outbox infrastructure including the outbox processor, worker, and message persistence. +/// Registers the Postgres outbox for an Entity Framework Core . /// public static class OutboxServiceCollectionExtensions { /// - /// Registers the full Postgres outbox pipeline: table info discovery from the EF Core model, - /// the , a hosted background worker, and a scoped - /// backed by direct Npgsql inserts. + /// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit. /// - /// - /// This method also calls - /// to register the EF Core interceptors that signal the processor on save and commit. - /// /// The Entity Framework Core builder to configure. /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UsePostgresOutbox(this IEntityFrameworkCoreBuilder builder) => builder.UsePostgresOutbox(static _ => { }); /// - /// Registers the full Postgres outbox pipeline with the specified . + /// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit. /// /// The Entity Framework Core builder to configure. - /// A delegate that configures the . + /// Configures the . /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UsePostgresOutbox( this IEntityFrameworkCoreBuilder builder, @@ -42,15 +36,30 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { ArgumentNullException.ThrowIfNull(configure); - var contextType = builder.ContextType; + builder.UseOutboxCore(); builder.Services.AddOptions(builder.Name).Configure(configure); + var contextType = builder.ContextType; + + if (builder.Services.Any(descriptor => + descriptor.ServiceType == typeof(PostgresOutboxProcessor) + && Equals(descriptor.ServiceKey, contextType))) + { + return builder; + } + + builder.Services.AddOptions(builder.Name) + .Validate( + options => options.PollingInterval > TimeSpan.Zero, + $"{nameof(PostgresOutboxOptions)}.{nameof(PostgresOutboxOptions.PollingInterval)} " + + "must be greater than zero."); + builder .Services.AddOptions(builder.Name) .Configure((options, sp) => { using var scope = sp.CreateScope(); - var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); + var dbContext = scope.ServiceProvider.GetRequiredDbContext(contextType); var model = dbContext.Model; ConfigureOutboxTableInfo(options.Outbox, model); @@ -62,15 +71,17 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { options.CreateConnection = services => { - var dbContext = (DbContext)services.GetRequiredService(contextType); + var dbContext = services.GetRequiredDbContext(contextType); return (NpgsqlConnection)((ICloneable)dbContext.Database.GetDbConnection()).Clone(); }; var tableInfo = tableInfoMonitor.Get(builder.Name); options.Queries = PostgresMessageOutboxQueries.From(tableInfo.Outbox); - }); + }) + .Configure>((options, outboxOptions) => + options.PollingInterval = outboxOptions.Get(builder.Name).PollingInterval); - builder.Services.AddSingleton(sp => + builder.Services.AddKeyedSingleton(contextType, (sp, _) => { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); @@ -79,19 +90,15 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( sp, sp.GetRequiredService(), sp.GetRequiredService(), - sp.GetRequiredService(), + sp.GetRequiredKeyedService(contextType), options); }); - builder.Services.AddSingleton(); - - builder.Services.AddHostedService(sp => sp.GetRequiredService()); + builder.Services.AddSingleton(sp => + new PostgresMessageBusOutboxWorker(sp.GetRequiredKeyedService(contextType))); builder.Services.TryAddScoped(sp => - PostgresMessageOutbox.Create(contextType, builder.Name, sp) - ); - - builder.UseOutboxCore(); + PostgresMessageOutbox.Create(contextType, builder.Name, sp)); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index 809c54c236b..3450c029337 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Transactions; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -13,14 +14,8 @@ namespace Mocha.Outbox; /// -/// Implements for Postgres by inserting serialized message envelopes -/// into the outbox table using raw SQL through the DbContext Npgsql connection. +/// Stores message envelopes in the PostgreSQL outbox. /// -/// -/// An active database or ambient transaction defers the outbox signal until commit. -/// A publish or send without a transaction throws when a transaction is required, -/// and otherwise signals immediately after insert. -/// internal sealed class PostgresMessageOutbox : IMessageOutbox, IDisposable { private readonly DbContext _originalDbContext; @@ -60,8 +55,8 @@ public PostgresMessageOutbox( /// A new configured for the specified DbContext. public static PostgresMessageOutbox Create(Type contextType, string optionsName, IServiceProvider services) { - var dbContext = (DbContext)services.GetRequiredService(contextType); - var signal = services.GetRequiredService(); + var dbContext = services.GetRequiredDbContext(contextType); + var signal = services.GetRequiredKeyedService(contextType); var outboxOptionsMonitor = services.GetRequiredService>(); var outboxOptions = outboxOptionsMonitor.Get(optionsName); var insertSql = outboxOptions.Queries.InsertEnvelope; @@ -71,7 +66,7 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, } /// - /// Serializes the message envelope and inserts it into the Postgres outbox table. + /// Serializes the message envelope and stores it in the Postgres outbox table. /// /// /// With an active database transaction, the signal is deferred to the transaction commit interceptor. @@ -85,13 +80,9 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, /// public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken cancellationToken) { - if (_requireTransaction && !HasTransaction() && RequiresTransaction(envelope)) + if (_requireTransaction && RequiresTransaction(envelope) && !HasTransaction()) { - throw new InvalidOperationException( - $"The outbox for DbContext '{_originalDbContext.GetType().FullName}' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " - + "or set RequireTransaction to false in UsePostgresOutbox()."); + throw ThrowHelper.OutboxRequiresTransaction(_originalDbContext.GetType()); } await _semaphore.WaitAsync(cancellationToken); @@ -119,7 +110,15 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken await command.ExecuteNonQueryAsync(cancellationToken); - if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is not NpgsqlTransaction) + if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is NpgsqlTransaction) + { + // A context without the messaging extension has no outbox state and no commit interceptor. + if (_originalDbContext.GetInfrastructure().GetService() is { } state) + { + state.HasUncommittedMessages = true; + } + } + else { _signal.SetAfterAmbientTransaction(); } @@ -137,7 +136,17 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken } private bool HasTransaction() - => _originalDbContext.Database.CurrentTransaction is not null || Transaction.Current is not null; + => _originalDbContext.Database.CurrentTransaction is not null + || HasSystemTransaction(_originalDbContext); + + /// + /// Returns whether the connection of the context takes part in a , either enlisted + /// explicitly or joined as the ambient transaction. + /// + private static bool HasSystemTransaction(DbContext context) + => context.GetService() is ITransactionEnlistmentManager manager + ? manager.EnlistedTransaction is not null || manager.CurrentAmbientTransaction is not null + : Transaction.Current is not null; // Replies and faults can be dispatched after the handler transaction rolls back. private static bool RequiresTransaction(MessageEnvelope envelope) diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs index a1971b7da30..de3cf533c82 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs @@ -24,6 +24,11 @@ internal sealed class PostgresMessageOutboxOptions /// public int CriticalAttemptInterval { get; set; } = 10; + /// + /// Gets or sets how long an idle processor waits before checking for messages when no notification arrives. + /// + public TimeSpan PollingInterval { get; set; } + /// /// Gets or sets how long the processor waits before it looks again for a due message that another /// instance holds. diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs index cc70588790a..df8f1191414 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs @@ -5,6 +5,12 @@ namespace Mocha.Outbox; /// public sealed class PostgresOutboxOptions { + /// + /// Gets or sets how long an idle worker waits before checking the database for messages to send + /// when no notification arrives. The default is 10 seconds. + /// + public TimeSpan PollingInterval { get; set; } = TimeSpan.FromSeconds(10); + /// /// Gets or sets whether a publish or send through the outbox requires an active database or ambient /// transaction and throws an without one. The default is true. diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs new file mode 100644 index 00000000000..d4f2f070541 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using Mocha.EntityFrameworkCore; + +namespace Mocha.Outbox; + +internal static class ThrowHelper +{ + public static InvalidOperationException OutboxRequiresTransaction(Type contextType) + => new( + $"{nameof(IMessageBus)} publishes and sends are stored in the outbox of the first {nameof(DbContext)} " + + $"registered with {nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}(), " + + $"'{contextType.FullName}', and require a transaction on that {nameof(DbContext)}. " + + $"Begin a transaction on it, use {nameof(EntityFrameworkCoreBuilderExtensions.UseTransaction)}() " + + "on it for consumers, " + + $"or set {nameof(PostgresOutboxOptions.RequireTransaction)} to false in " + + $"{nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}()."); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs new file mode 100644 index 00000000000..fa3faca2344 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Mocha.EntityFrameworkCore; + +internal static class DbContextMessagingServicesExtensions +{ + /// + /// Gets the application services carried by the messaging extension of the context options. + /// The context options must contain the messaging extension. + /// + public static MessagingDbContextServices GetMessagingServices(this DbContext context) + => context.GetService().FindExtension()!.Services; +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs index 9c1034617db..432185b3d14 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs @@ -11,13 +11,15 @@ internal static class DbContextOptionsBuilderExtensions /// /// The DbContext options builder to extend. /// The messaging options carrying service configuration delegates. + /// The application services that the messaging interceptors and outbox use. /// The same instance for chaining. public static DbContextOptionsBuilder AddMessagingExtensions( this DbContextOptionsBuilder optionsBuilder, - MessagingDbContextOptions options) + MessagingDbContextOptions options, + MessagingDbContextServices services) { ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension( - new MessagingDbContextOptionsExtension(options)); + new MessagingDbContextOptionsExtension(options, services)); return optionsBuilder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs new file mode 100644 index 00000000000..48d67a6108f --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; + +namespace Mocha.EntityFrameworkCore; + +internal static class DbContextServiceProviderExtensions +{ + /// + /// Gets the of the specified type, and throws when it is not registered. + /// + public static DbContext GetRequiredDbContext(this IServiceProvider services, Type contextType) + => (DbContext?)services.GetService(contextType) + ?? throw ThrowHelper.DbContextNotRegistered(contextType); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs new file mode 100644 index 00000000000..aba6de9266a --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs @@ -0,0 +1,34 @@ +using System.Runtime.ExceptionServices; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal sealed class EntityFrameworkConsumerExecutionStrategy(Type contextType) : IConsumerExecutionStrategy +{ + public async ValueTask ExecuteAsync(IConsumeContext context, Func executeAttempt) + { + await using var scope = context.Services.CreateAsyncScope(); + var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); + var strategy = dbContext.Database.CreateExecutionStrategy(); + + if (!strategy.RetriesOnFailure) + { + await executeAttempt(context.CancellationToken); + return; + } + + try + { + await strategy.ExecuteAsync( + executeAttemptToken => executeAttempt(executeAttemptToken).AsTask(), + context.CancellationToken); + } + catch (RetryLimitExceededException exception) when (exception.InnerException is not null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + throw; + } + } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs new file mode 100644 index 00000000000..8330e04080f --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs @@ -0,0 +1,38 @@ +namespace Mocha.EntityFrameworkCore; + +/// +/// Configures Entity Framework Core resilience and transaction middleware. +/// +public static class EntityFrameworkCoreBuilderExtensions +{ + /// + /// Runs consumers with the DbContext execution strategy. + /// + /// The Entity Framework Core builder to configure. + /// The same instance for chaining. + public static IEntityFrameworkCoreBuilder UseResilience(this IEntityFrameworkCoreBuilder builder) + { + builder.HostBuilder.ConfigureMessageBus(x => + x.ConfigureFeature(f => + f.Set(new ConsumerExecutionStrategyFeature + { + Strategy = new EntityFrameworkConsumerExecutionStrategy(builder.ContextType) + }))); + + return builder; + } + + /// + /// Wraps each consumer invocation in a database transaction, committing on success + /// and rolling back on failure. + /// + /// The Entity Framework Core builder to configure. + /// The same instance for chaining. + public static IEntityFrameworkCoreBuilder UseTransaction(this IEntityFrameworkCoreBuilder builder) + { + builder.HostBuilder.ConfigureMessageBus(x => + x.UseConsume(EntityFrameworkTransactionConsumeMiddleware.Create(builder.ContextType)) + ); + return builder; + } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs index ca9f98476ee..a637e53ff97 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs @@ -2,29 +2,20 @@ namespace Mocha.EntityFrameworkCore; -/// -/// Provides extension methods on for registering -/// additional services into the DbContext internal service provider. -/// -public static class EntityFrameworkCorePersistenceBuilderExtensions +internal static class EntityFrameworkCorePersistenceBuilderExtensions { /// - /// Registers a callback that configures services within the DbContext internal service provider, - /// allowing interceptors and other EF Core services to be injected alongside messaging infrastructure. + /// Registers services in the DbContext internal service provider. The delegate must not capture + /// application services. /// - /// The Entity Framework Core builder to configure. - /// - /// A delegate receiving the application and the DbContext - /// for registering additional services. - /// - /// The same instance for chaining. public static IEntityFrameworkCoreBuilder ConfigureEntityFrameworkServices( this IEntityFrameworkCoreBuilder builder, - Action configure) + Action configure) { builder.Services.Configure( builder.Name, - (options) => options.ConfigureServices.Add(configure)); + options => options.ConfigureServices.Add(configure)); + return builder; } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs new file mode 100644 index 00000000000..5696ff39710 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal sealed class EntityFrameworkTransactionConsumeMiddleware(Type contextType) +{ + public async ValueTask InvokeAsync(IConsumeContext context, ConsumerDelegate next) + { + var dbContext = (DbContext)context.Services.GetRequiredService(contextType); + + await using var transaction = await dbContext.Database.BeginTransactionAsync(context.CancellationToken); + + try + { + await next(context); + + await transaction.CommitAsync(context.CancellationToken); + } + catch (Exception) + { + await transaction.RollbackAsync(context.CancellationToken); + throw; + } + } + + public static ConsumerMiddlewareConfiguration Create(Type contextType) + => new( + (_, next) => + { + var middleware = new EntityFrameworkTransactionConsumeMiddleware(contextType); + return ctx => middleware.InvokeAsync(ctx, next); + }, + "EntityFrameworkTransaction"); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index a70dacc3836..ac1d959e30b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -1,8 +1,10 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; -using System.Runtime.ExceptionServices; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using Mocha.Outbox; +using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; @@ -25,7 +27,7 @@ public static IMessageBusHostBuilder AddEntityFramework( Action configure) where TContext : DbContext { - var persistenceBuilder = new EntityFrameworkCoreBuilder + var efBuilder = new EntityFrameworkCoreBuilder { Services = builder.Services, HostBuilder = builder, @@ -33,134 +35,24 @@ public static IMessageBusHostBuilder AddEntityFramework( Name = typeof(TContext).FullName ?? typeof(TContext).Name }; - configure(persistenceBuilder); + configure(efBuilder); - builder - .Services.AddOptions(persistenceBuilder.Name) - .Configure((options, serviceProvider) => options.ServiceProvider = serviceProvider); + builder.Services.AddOptions(efBuilder.Name); - builder.Services.AddSingleton< + builder.Services.TryAddKeyedSingleton( + typeof(TContext), + static (services, contextType) => new MessagingDbContextServices( + services.GetKeyedService(contextType), + services.GetService(), + services.GetTimeProvider())); + + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< IDbContextOptionsConfiguration, MessagingDbContextOptionsConfiguration - >(); - - builder.ConfigureMessageBus(x => - x.ConfigureFeature(f => f.Set(new EntityFrameworkConfigurationFeature { ContextType = typeof(TContext) })) - ); + >(static services => new MessagingDbContextOptionsConfiguration( + services.GetRequiredService>(), + services.GetRequiredKeyedService(typeof(TContext))))); return builder; } } - -/// -/// Provides extension methods on for configuring -/// resilience and transaction middleware for Entity Framework Core consumers. -/// -public static class EntityFrameworkCoreBuilderExtensions -{ - /// - /// Wraps consumer execution with the DbContext execution strategy, enabling automatic retry - /// for transient database failures such as connection drops or deadlocks. - /// - /// The Entity Framework Core builder to configure. - /// The same instance for chaining. - public static IEntityFrameworkCoreBuilder UseResilience(this IEntityFrameworkCoreBuilder builder) - { - builder.HostBuilder.ConfigureMessageBus(x => - x.ConfigureFeature(f => - f.Set(new ConsumerExecutionStrategyFeature - { - Strategy = new EntityFrameworkConsumerExecutionStrategy(builder.ContextType) - }))); - - return builder; - } - - /// - /// Wraps each consumer invocation in a database transaction, committing on success - /// and rolling back on failure. - /// - /// The Entity Framework Core builder to configure. - /// The same instance for chaining. - public static IEntityFrameworkCoreBuilder UseTransaction(this IEntityFrameworkCoreBuilder builder) - { - builder.HostBuilder.ConfigureMessageBus(x => - x.UseConsume(EntityFrameworkTransactionConsumeMiddleware.Create()) - ); - return builder; - } -} - -internal sealed class EntityFrameworkConfigurationFeature -{ - public Type? ContextType { get; set; } -} - -internal sealed class EntityFrameworkConsumerExecutionStrategy(Type contextType) : IConsumerExecutionStrategy -{ - public async ValueTask ExecuteAsync(IConsumeContext context, Func executeAttempt) - { - await using var scope = context.Services.CreateAsyncScope(); - var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); - var strategy = dbContext.Database.CreateExecutionStrategy(); - - if (!strategy.RetriesOnFailure) - { - await executeAttempt(context.CancellationToken); - return; - } - - try - { - await strategy.ExecuteAsync( - executeAttemptToken => executeAttempt(executeAttemptToken).AsTask(), - context.CancellationToken); - } - catch (RetryLimitExceededException exception) when (exception.InnerException is not null) - { - ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); - throw; - } - } -} - -internal sealed class EntityFrameworkTransactionConsumeMiddleware(Type contextType) -{ - public async ValueTask InvokeAsync(IConsumeContext context, ConsumerDelegate next) - { - var dbContext = (DbContext)context.Services.GetRequiredService(contextType); - - await using var transaction = await dbContext.Database.BeginTransactionAsync(context.CancellationToken); - - try - { - await next(context); - - await transaction.CommitAsync(context.CancellationToken); - } - catch (Exception) - { - await transaction.RollbackAsync(context.CancellationToken); - throw; - } - } - - public static ConsumerMiddlewareConfiguration Create() - => new( - static (context, next) => - { - var contextType = - context - .Services.GetRequiredService() - .Get() - ?.ContextType - ?? throw new InvalidOperationException( - "No Entity Framework Core DbContext type has been configured. " - + "Call AddEntityFramework() on the message bus host builder " - + "before using UseTransaction()."); - - var middleware = new EntityFrameworkTransactionConsumeMiddleware(contextType); - return ctx => middleware.InvokeAsync(ctx, next); - }, - "EntityFrameworkTransaction"); -} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs index 1c90aa97599..c2acc42644b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs @@ -6,24 +6,10 @@ namespace Mocha.EntityFrameworkCore; /// Holds configuration state for a messaging-enabled DbContext, including service registration /// delegates that are applied when the DbContext internal service provider is built. /// -public class MessagingDbContextOptions +internal sealed class MessagingDbContextOptions { /// /// Gets the list of delegates that register services into the DbContext internal service provider. /// - public List> ConfigureServices { get; init; } = []; - - /// - /// Gets or sets the application-level service provider used to resolve dependencies during DbContext service configuration. - /// - /// - /// Thrown when accessed before the service provider has been configured. - /// - public IServiceProvider ServiceProvider - { - get => field ?? - throw new InvalidOperationException( - "ServiceProvider has not been configured. Ensure AddEntityFramework() has been called on the message bus host builder."); - set; - } + public List> ConfigureServices { get; init; } = []; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs index 7f2367f9133..aa1a17c1cb9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs @@ -4,7 +4,9 @@ namespace Mocha.EntityFrameworkCore; -internal class MessagingDbContextOptionsConfiguration(IOptionsMonitor monitor) +internal class MessagingDbContextOptionsConfiguration( + IOptionsMonitor monitor, + MessagingDbContextServices services) : IDbContextOptionsConfiguration where TContext : DbContext { /// @@ -25,6 +27,6 @@ public void Configure(IServiceProvider serviceProvider, DbContextOptionsBuilder throw new InvalidOperationException($"No options found for context {name}"); } - optionsBuilder.AddMessagingExtensions(options); + optionsBuilder.AddMessagingExtensions(options, services); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs index c383b9b220f..e2a6c86032e 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs @@ -9,10 +9,17 @@ namespace Mocha.EntityFrameworkCore; /// saga support) into the DbContext internal service provider during context construction. /// /// The messaging options containing service configuration delegates to apply. -internal class MessagingDbContextOptionsExtension(MessagingDbContextOptions options) : IDbContextOptionsExtension +/// The application services that the messaging interceptors and outbox of the context use. +internal class MessagingDbContextOptionsExtension( + MessagingDbContextOptions options, + MessagingDbContextServices services) : IDbContextOptionsExtension { - private readonly IServiceProvider _serviceProvider = options.ServiceProvider; - private readonly Action[] _configureServices = [.. options.ConfigureServices]; + private readonly Action[] _configureServices = [.. options.ConfigureServices]; + + /// + /// Gets the application services that the messaging interceptors and outbox of the context use. + /// + public MessagingDbContextServices Services { get; } = services; /// /// Gets the extension metadata used by EF Core for service provider caching and debug output. @@ -28,7 +35,7 @@ public void ApplyServices(IServiceCollection services) { foreach (var configureService in _configureServices) { - configureService(_serviceProvider, services); + configureService(services); } } @@ -58,7 +65,6 @@ public override int GetServiceProviderHashCode() var extension = (MessagingDbContextOptionsExtension)Extension; var hash = new HashCode(); - hash.Add(GetReferenceHashCode(extension._serviceProvider)); foreach (var configureService in extension._configureServices) { @@ -87,11 +93,6 @@ public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo var current = (MessagingDbContextOptionsExtension)Extension; var candidate = (MessagingDbContextOptionsExtension)otherInfo.Extension; - if (!ReferenceEquals(current._serviceProvider, candidate._serviceProvider)) - { - return false; - } - if (current._configureServices.Length != candidate._configureServices.Length) { return false; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs new file mode 100644 index 00000000000..f75fcf5c813 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs @@ -0,0 +1,32 @@ +using Mocha.Outbox; +using Mocha.Scheduling; + +namespace Mocha.EntityFrameworkCore; + +/// +/// The application singletons that the messaging interceptors and the outbox of a DbContext type use. +/// A service provider has one instance per context type, which identifies the application of a context. +/// +/// The outbox signal of the context type, or null when it has no outbox. +/// The scheduler signal of the application, or null when it has no scheduler. +/// The time provider of the application. +internal sealed class MessagingDbContextServices( + IOutboxSignal? outboxSignal, + ISchedulerSignal? schedulerSignal, + TimeProvider timeProvider) +{ + /// + /// Gets the outbox signal of the context type, or null when the context type has no outbox. + /// + public IOutboxSignal? OutboxSignal { get; } = outboxSignal; + + /// + /// Gets the scheduler signal of the application, or null when the application has no scheduler. + /// + public ISchedulerSignal? SchedulerSignal { get; } = schedulerSignal; + + /// + /// Gets the time provider of the application. + /// + public TimeProvider TimeProvider { get; } = timeProvider; +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs new file mode 100644 index 00000000000..1426c665b66 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs @@ -0,0 +1,12 @@ +namespace Mocha.EntityFrameworkCore; + +/// +/// The outbox state of a single DbContext instance. +/// +internal sealed class DbContextOutboxState +{ + /// + /// Gets or sets whether the context wrote outbox messages in a transaction that has not committed yet. + /// + public bool HasUncommittedMessages { get; set; } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs new file mode 100644 index 00000000000..be44e32d8a9 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs @@ -0,0 +1,3 @@ +namespace Mocha.EntityFrameworkCore; + +internal sealed record OutboxDbContextRegistration(Type ContextType); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs index 8113a5d8f62..3a66cae1069 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs @@ -1,16 +1,14 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Outbox; +using Microsoft.EntityFrameworkCore.Infrastructure; namespace Mocha.EntityFrameworkCore; /// -/// Intercepts Entity Framework Core database transaction commit events to signal the outbox processor -/// that messages are ready for dispatch. +/// Signals the outbox processor of a context when a transaction commits in which the context wrote +/// outbox messages. /// -internal sealed class OutboxDbTransactionInterceptor(IOutboxSignal signal) - : DbTransactionInterceptor - , ISingletonInterceptor +internal sealed class OutboxDbTransactionInterceptor : DbTransactionInterceptor { /// public override Task TransactionCommittedAsync( @@ -26,6 +24,17 @@ public override Task TransactionCommittedAsync( /// public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) { - signal.Set(); + if (eventData.Context is not { } context) + { + return; + } + + var state = context.GetService(); + + if (state.HasUncommittedMessages) + { + state.HasUncommittedMessages = false; + context.GetMessagingServices().OutboxSignal?.Set(); + } } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs index 23c8fbceccb..e2bc74c6835 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -1,35 +1,42 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Mocha.Outbox; namespace Mocha.EntityFrameworkCore; /// /// Provides extension methods on for registering -/// core outbox interceptors that signal the outbox processor after save and transaction commit. +/// the core outbox services of a context. /// public static class OutboxEntityFrameworkCorePersistenceBuilderExtensions { /// - /// Registers the core outbox infrastructure, including EF Core interceptors that signal the - /// outbox processor when changes are saved or transactions are committed. + /// Registers the core outbox infrastructure of the context: its outbox signal, and the EF Core interceptor + /// that raises the signal when a transaction in which the context wrote outbox messages commits. /// /// The Entity Framework Core builder to configure. /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UseOutboxCore(this IEntityFrameworkCoreBuilder builder) { + if (builder.Services.Any(descriptor => + descriptor.ServiceType == typeof(OutboxDbContextRegistration) + && descriptor.ImplementationInstance is OutboxDbContextRegistration registration + && registration.ContextType == builder.ContextType)) + { + return builder; + } + + builder.Services.AddSingleton(new OutboxDbContextRegistration(builder.ContextType)); + builder.Services.TryAddKeyedSingleton(builder.ContextType); builder.HostBuilder.UseOutboxCore(); - builder.ConfigureEntityFrameworkServices((sp, services) => + builder.ConfigureEntityFrameworkServices(static services => { - var signal = sp.GetService(); - - if (signal is not null) - { - services.AddSingleton(new OutboxDbTransactionInterceptor(signal)); - services.AddSingleton(new OutboxSaveChangesInterceptor(signal)); - } + services.AddScoped(); + services.AddSingleton(); }); + return builder; } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs deleted file mode 100644 index 2855bc19c3a..00000000000 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Outbox; - -namespace Mocha.EntityFrameworkCore; - -/// -/// Intercepts Entity Framework Core save changes events to signal the outbox processor -/// that messages are ready for dispatch. -/// -internal sealed class OutboxSaveChangesInterceptor(IOutboxSignal signal) : SaveChangesInterceptor, ISingletonInterceptor -{ - /// - public override ValueTask SavedChangesAsync( - SaveChangesCompletedEventData eventData, - int result, - CancellationToken cancellationToken = default) - { - return new(SavedChanges(eventData, result)); - } - - /// - public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) - { - if (eventData.Context is not { } context) - { - return result; - } - - if (context.Database.CurrentTransaction is null) - { - signal.SetAfterAmbientTransaction(); - } - - return result; - } -} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs index 8f19bd8d792..8ffd5a17b74 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs @@ -1,16 +1,13 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core database transaction commit events to signal the scheduler -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class SchedulingDbTransactionInterceptor(ISchedulerSignal signal, TimeProvider timeProvider) - : DbTransactionInterceptor - , ISingletonInterceptor +internal sealed class SchedulingDbTransactionInterceptor : DbTransactionInterceptor { /// public override Task TransactionCommittedAsync( @@ -26,6 +23,10 @@ public override Task TransactionCommittedAsync( /// public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) { - signal.Notify(timeProvider.GetUtcNow()); + if (eventData.Context is { } context) + { + var services = context.GetMessagingServices(); + services.SchedulerSignal?.Notify(services.TimeProvider.GetUtcNow()); + } } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs index 6c834d3da07..ca05c7f7928 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -20,16 +20,10 @@ public static IEntityFrameworkCoreBuilder UseSchedulingCore(this IEntityFramewor { builder.HostBuilder.UseSchedulerCore(); - builder.ConfigureEntityFrameworkServices((sp, services) => + builder.ConfigureEntityFrameworkServices(static services => { - var signal = sp.GetService(); - - if (signal is not null) - { - var timeProvider = sp.GetService() ?? TimeProvider.System; - services.AddSingleton(new SchedulingDbTransactionInterceptor(signal, timeProvider)); - services.AddSingleton(new SchedulingSaveChangesInterceptor(signal, timeProvider)); - } + services.AddSingleton(); + services.AddSingleton(); }); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs index a682e56f22c..2ee5bb40493 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs @@ -1,17 +1,12 @@ using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core save changes events to signal the scheduler -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class SchedulingSaveChangesInterceptor( - ISchedulerSignal signal, - TimeProvider timeProvider) - : SaveChangesInterceptor - , ISingletonInterceptor +internal sealed class SchedulingSaveChangesInterceptor : SaveChangesInterceptor { /// public override ValueTask SavedChangesAsync( @@ -32,7 +27,8 @@ public override int SavedChanges(SaveChangesCompletedEventData eventData, int re if (context.Database.CurrentTransaction is null) { - signal.Notify(timeProvider.GetUtcNow()); + var services = context.GetMessagingServices(); + services.SchedulerSignal?.Notify(services.TimeProvider.GetUtcNow()); } return result; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs new file mode 100644 index 00000000000..d2a8cd6e843 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal static class ThrowHelper +{ + public static InvalidOperationException DbContextNotRegistered(Type contextType) + => new( + $"The {nameof(DbContext)} '{contextType.FullName}' is not registered as a service. " + + $"Register it with {nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextPool)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextFactory)} or " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)}. " + + $"Before EF Core 10, {nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)} " + + "does not register the context itself; also add " + + $"services.{nameof(ServiceCollectionServiceExtensions.AddScoped)}(sp => " + + $"sp.{nameof(ServiceProviderServiceExtensions.GetRequiredService)}" + + $"<{nameof(IDbContextFactory)}<{contextType.Name}>>()" + + $".{nameof(IDbContextFactory.CreateDbContext)}())."); +} diff --git a/src/Mocha/src/Mocha.Outbox/Assembly.cs b/src/Mocha/src/Mocha.Outbox/Assembly.cs new file mode 100644 index 00000000000..27476eb262a --- /dev/null +++ b/src/Mocha/src/Mocha.Outbox/Assembly.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mocha.EntityFrameworkCore")] diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs deleted file mode 100644 index 63ae700df2f..00000000000 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Mocha.Outbox; - -namespace Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; - -/// -/// An outbox signal whose never throws -/// . The production -/// MessageBusOutboxSignal wraps AsyncAutoResetEvent which -/// throws on Set() after disposal. In integration tests the outbox -/// processor's own transaction commits fire the EF Core interceptor that -/// calls Set(), and this can race with provider disposal. -/// -/// Uses a TaskCompletionSource to implement auto-reset semantics. -/// Unlike SemaphoreSlim, this approach does not accumulate waiters -/// across loop iterations - each WaitAsync atomically exchanges -/// the TCS, and Set signals whoever is currently waiting. -/// -/// -internal sealed class ResilientOutboxSignal : IOutboxSignal -{ -#if NET9_0_OR_GREATER - private readonly Lock _lock = new(); -#else - private readonly object _lock = new(); -#endif - private TaskCompletionSource _tcs; - - public ResilientOutboxSignal() - { - // Start signaled (like production AsyncAutoResetEvent(true)) - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _tcs.TrySetResult(); - } - - public void Set() - { - lock (_lock) - { - if (!_tcs.TrySetResult()) - { - // TCS was already cancelled or faulted - replace with a - // pre-completed TCS so the next WaitAsync sees the signal. - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _tcs.TrySetResult(); - } - } - } - - public Task WaitAsync(CancellationToken cancellationToken) - { - lock (_lock) - { - var task = _tcs.Task; - - if (task.IsCompletedSuccessfully) - { - // Reset: replace with a new, unsignaled TCS - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - return Task.CompletedTask; - } - - if (task.IsCanceled || task.IsFaulted) - { - // Previous waiter was cancelled - replace with fresh TCS - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - } - - // Register cancellation on the current TCS - var tcs = _tcs; - if (cancellationToken.CanBeCanceled) - { - cancellationToken.Register(static state => ((TaskCompletionSource)state!).TrySetCanceled(), tcs); - } - - return tcs.Task; - } - } -} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs index 40a7679e432..e0d817ac17e 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs @@ -5,9 +5,8 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; internal static class TestDbContextOptionsBuilderExtensions { - // Each test builds its own service provider, so EF accumulates more than twenty - // internal service providers across a run. Ignore the resulting warning instead of - // letting it throw. + // A test run builds more than twenty distinct EF Core configurations (data sources, interceptor + // instances), so EF's process-wide warning about many internal service providers is ignored. public static DbContextOptionsBuilder UseTestNpgsql( this DbContextOptionsBuilder optionsBuilder, string connectionString) diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs index baabe262685..ff64c6dcc80 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Options; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Inbox; -using Mocha.Outbox; using Mocha.Transport.InMemory; namespace Mocha.EntityFrameworkCore.Postgres.Tests; @@ -113,11 +112,6 @@ private static ServiceProvider BuildProvider(Action? configure = n services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); - // Use a resilient signal to prevent ObjectDisposedException when - // EF Core shares the internal service provider (and interceptors) - // across test classes via ShouldUseSameServiceProvider. - services.AddSingleton(); - var builder = services.AddMessageBus(); builder.AddEntityFramework( ef => ef.UsePostgresInbox(configure)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs index 5ebe57bf66d..67c6d14a960 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs @@ -35,6 +35,49 @@ public void UsePostgresOutbox_Should_DeferConfiguration_When_OptionsHaveNotBeenR Assert.Equal(1, configureCount); } + [Fact] + public async Task UsePostgresOutbox_Should_RegisterOnce_When_ConfigurationIsRepeated() + { + // arrange + var services = CreateServices(); + var builder = services.AddMessageBus(); + builder.AddInMemory(); + builder.AddEntityFramework(ef => ef.UseOutboxCore()); + + // act + builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); + builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); + await using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await using var scope = provider.CreateAsyncScope(); + + // assert + Assert.Single(provider.GetServices().OfType()); + Assert.IsType(scope.ServiceProvider.GetRequiredService()); + } + + [Fact] + public async Task UsePostgresOutbox_Should_ThrowClearError_When_ContextIsNotRegistered() + { + // arrange + var services = new ServiceCollection(); + services.AddLogging(); + services.AddMessageBus().AddEntityFramework(ef => ef.UsePostgresOutbox()).AddInMemory(); + await using var provider = services.BuildServiceProvider(); + + // act + var exception = Assert.Throws( + () => provider.GetRequiredKeyedService(typeof(TestDbContext))); + + // assert + Assert.Equal( + $"The DbContext '{typeof(TestDbContext).FullName}' is not registered as a service. " + + "Register it with AddDbContext, AddDbContextPool, AddDbContextFactory or AddPooledDbContextFactory. " + + "Before EF Core 10, AddPooledDbContextFactory does not register the context itself; also add " + + "services.AddScoped(sp => sp.GetRequiredService>()" + + ".CreateDbContext()).", + exception.Message); + } + [Fact] public async Task UsePostgresOutbox_Should_RegisterHostedService_When_Called() { @@ -81,16 +124,20 @@ public async Task UsePostgresOutbox_Should_RegisterScopedOutbox_When_Called() } [Fact] - public async Task UsePostgresOutbox_Should_RegisterProcessor_When_Called() + public async Task UsePostgresOutbox_Should_RegisterKeyedSingletonProcessor_When_Called() { - // Arrange + // arrange await using var provider = BuildProvider(); + await using var scope = provider.CreateAsyncScope(); - // Act - var processor = provider.GetService(); + // act + var processor = provider.GetRequiredKeyedService(typeof(TestDbContext)); - // Assert - Assert.NotNull(processor); + // assert + Assert.Same( + processor, + scope.ServiceProvider.GetRequiredKeyedService(typeof(TestDbContext))); + Assert.Null(provider.GetService()); } [Fact] @@ -116,24 +163,24 @@ public async Task UsePostgresOutbox_Should_ConfigureQueriesFromModel_When_Defaul private static ServiceProvider BuildProvider() { - var services = new ServiceCollection(); - services.AddLogging(); - services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); - - // Use a resilient signal to prevent ObjectDisposedException when - // EF Core shares the internal service provider (and interceptors) - // across test classes via ShouldUseSameServiceProvider. - services.AddSingleton(); - + var services = CreateServices(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); builder.AddInMemory(); var provider = services.BuildServiceProvider(); - // Build the runtime so that all singleton factories resolve _ = provider.GetRequiredService(); return provider; } + + private static ServiceCollection CreateServices() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); + + return services; + } } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs index 07358e8fc9a..1e323851afa 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs @@ -23,7 +23,6 @@ public async Task PersistAsync_Should_UseNamedOptions_When_TransactionRequiremen var connectionString = await _fixture.CreateDatabaseAsync(); var services = new ServiceCollection(); services.AddDbContext(options => options.UseTestNpgsql(connectionString)); - services.AddSingleton(); services.AddMessageBus().AddEntityFramework(ef => ef.UsePostgresOutbox()); services.PostConfigure( typeof(TestDbContext).FullName, diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs new file mode 100644 index 00000000000..6677784a166 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs @@ -0,0 +1,346 @@ +using System.Collections.Concurrent; +using System.Data; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresMultipleContextOutboxTests(PostgresFixture fixture) : IClassFixture +{ + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task Set_Should_WakeOnlyTheProcessorOfItsContext_When_MultipleContextsAreIdle() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + + // Initialize the schemas without outbox interceptors. + await using (var first = new FirstDbContext(new DbContextOptionsBuilder() + .UseTestNpgsql(firstConnection).Options)) + { + await first.Database.EnsureCreatedAsync(TestToken); + } + + await using (var second = new SecondDbContext(new DbContextOptionsBuilder() + .UseTestNpgsql(secondConnection).Options)) + { + await second.Database.EnsureCreatedAsync(TestToken); + } + + await using var provider = await CreateProviderAsync(firstConnection, secondConnection, wakeOnlyOnSignal: true); + var firstIdle = ObserveFirstPollCompletion(provider); + var secondIdle = ObserveFirstPollCompletion(provider); + var signal = provider.GetRequiredKeyedService(typeof(SecondDbContext)); + var recorder = provider.GetRequiredService(); + var runtime = provider.GetRequiredService(); + var type = runtime.GetMessageType(typeof(ContextEvent)); + var endpoint = runtime.GetPublishEndpoint(type); + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + await Task.WhenAll(firstIdle, secondIdle).WaitAsync(TimeSpan.FromSeconds(30), TestToken); + foreach (var (connection, context) in new[] { (firstConnection, "first"), (secondConnection, "second") }) + { + await MessageRows.InsertOutboxAsync(connection, new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = type.Identity, + ContentType = MessageContentType.Json.Value, + DestinationAddress = endpoint.Address.ToString(), + Body = JsonSerializer.SerializeToUtf8Bytes(new ContextEvent(context)) + }, TestToken); + } + + // act + signal.Set(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + while (recorder.Messages.IsEmpty) + { + await Task.Delay(25, timeout.Token); + } + + // assert + Assert.Equal(["second"], recorder.Messages.ToArray()); + Assert.Equal(1, await MessageRows.CountOutboxAsync(firstConnection, TestToken)); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + +#if NET9_0_OR_GREATER + [Fact] + public async Task CommitAsync_Should_SignalOnlyItsContext_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + var firstSignal = new StubOutboxSignal(); + var secondSignal = new StubOutboxSignal(); + var services = new ServiceCollection(); + services.AddKeyedSingleton(typeof(FirstDbContext), firstSignal); + services.AddKeyedSingleton(typeof(SecondDbContext), secondSignal); + await using var provider = await CreateProviderAsync( + services, + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + await using var scope = provider.CreateAsyncScope(); + var second = scope.ServiceProvider.GetRequiredService(); + using var outbox = PostgresMessageOutbox.Create( + typeof(SecondDbContext), + typeof(SecondDbContext).FullName!, + scope.ServiceProvider); + await using var transaction = await second.Database.BeginTransactionAsync(TestToken); + await outbox.PersistAsync( + new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = "urn:message:context-event", + DestinationAddress = "memory://test/queue", + Body = "{\"context\":\"second\"}"u8.ToArray() + }, + TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal((0, 1), (firstSignal.SetCallCount, secondSignal.SetCallCount)); + } +#endif + + [Fact] + public async Task PublishAsync_Should_PersistToFirstRegisteredContext_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + await using var scope = provider.CreateAsyncScope(); + var first = scope.ServiceProvider.GetRequiredService(); + var bus = scope.ServiceProvider.GetRequiredService(); + var recorder = provider.GetRequiredService(); + await using var transaction = await first.Database.BeginTransactionAsync(TestToken); + + // act + await bus.PublishAsync(new ContextEvent("default"), TestToken); + var beforeCommit = await CountRowsAsync(provider); + await transaction.CommitAsync(TestToken); + var afterCommit = await CountRowsAsync(provider); + + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + while (recorder.Messages.IsEmpty) + { + await Task.Delay(25, timeout.Token); + } + + // assert + Assert.Equal((0, 0), beforeCommit); + Assert.Equal((1, 0), afterCommit); + Assert.Equal(["default"], recorder.Messages.ToArray()); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + + [Fact] + public async Task RequestAsync_Should_ReturnResponse_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + var response = await bus.RequestAsync(new ContextRequest("request"), TestToken) + .AsTask() + .WaitAsync(TimeSpan.FromSeconds(30), TestToken); + + // assert + Assert.Equal("request", response.Context); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + + private static Task ObserveFirstPollCompletion(ServiceProvider provider) + where TContext : DbContext + { + var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var options = provider.GetRequiredService>() + .Get(typeof(TContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed) + { + completed.TrySetResult(); + } + }; + return connection; + }; + return completed.Task; + } + + private static async Task<(int First, int Second)> CountRowsAsync(ServiceProvider provider) + { + await using var scope = provider.CreateAsyncScope(); + var first = await scope.ServiceProvider.GetRequiredService() + .Set().CountAsync(TestToken); + var second = await scope.ServiceProvider.GetRequiredService() + .Set().CountAsync(TestToken); + return (first, second); + } + + // With wakeOnlyOnSignal the relays poll every 10 minutes and no consumer transaction commits, so only the + // outbox signal wakes an idle relay. + private static Task CreateProviderAsync( + string firstConnection, + string secondConnection, + bool wakeOnlyOnSignal) + => CreateProviderAsync(new ServiceCollection(), firstConnection, secondConnection, wakeOnlyOnSignal); + + private static async Task CreateProviderAsync( + ServiceCollection services, + string firstConnection, + string secondConnection, + bool wakeOnlyOnSignal) + { + services.AddLogging(); + services.AddSingleton(); + services.AddDbContextFactory(options => options.UseTestNpgsql(firstConnection)); + services.AddDbContext(options => options.UseTestNpgsql(secondConnection)); + var builder = services.AddMessageBus(); + Action configureOutbox = wakeOnlyOnSignal + ? static options => options.PollingInterval = TimeSpan.FromMinutes(10) + : static _ => { }; + builder.AddEntityFramework(ef => + { + ef.UsePostgresOutbox(configureOutbox); + if (!wakeOnlyOnSignal) + { + ef.UseTransaction(); + } + }); + builder.AddEntityFramework(ef => ef.UsePostgresOutbox(configureOutbox)); + builder.AddEventHandler(); + builder.AddRequestHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + public sealed record ContextEvent(string Context); + + public sealed record ContextRequest(string Context) : IEventRequest; + + public sealed record ContextResponse(string Context); + + public sealed class ContextRequestHandler : IEventRequestHandler + { + public ValueTask HandleAsync(ContextRequest request, CancellationToken cancellationToken) + => new(new ContextResponse(request.Context)); + } + + public sealed class ContextEventHandler( + MessageRecorder recorder, + FirstDbContext first, + SecondDbContext second) : IEventHandler + { + public ValueTask HandleAsync(ContextEvent message, CancellationToken cancellationToken) + { + recorder.Transactions.Enqueue(( + first.Database.CurrentTransaction is not null, + second.Database.CurrentTransaction is not null)); + recorder.Messages.Enqueue(message.Context); + if (recorder.Messages.Count == 2) + { + recorder.Completed.TrySetResult(); + } + + return default; + } + } + + public sealed class MessageRecorder + { + public ConcurrentQueue Messages { get; } = new(); + + public ConcurrentQueue<(bool First, bool Second)> Transactions { get; } = new(); + + public TaskCompletionSource Completed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public sealed class FirstDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.AddPostgresOutbox(); + } + + public sealed class SecondDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.AddPostgresOutbox(); + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs index 7828b2ef311..38480e20b13 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using System.Text.Json; using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -67,31 +66,6 @@ public async Task PersistAsync_Should_SignalOnlyAfterCommit_When_ManyMessagesSha AssertSignaledOnlyAfterCommit(signal); } - [Fact] - public async Task SaveChanges_Should_SignalOnlyAfterCommit_When_AmbientTransactionIsUsed() - { - // arrange - var connectionString = await fixture.CreateDatabaseAsync(); - var signal = new VisibilityProbeSignal(connectionString); - await using var provider = await CreateProviderAsync(connectionString, signal, addHandler: false); - await EnsureCreatedAsync(provider); - signal.Events.Clear(); - - // act - using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) - { - await using var scope = provider.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - db.Add(new OutboxMessage(Guid.NewGuid(), JsonDocument.Parse("{}"))); - await db.SaveChangesAsync(TestToken); - signal.Mark("before-complete"); - transaction.Complete(); - } - - // assert - AssertSignaledOnlyAfterCommit(signal); - } - [Fact] public async Task PersistAsync_Should_SignalOnCompletion_When_AmbientTransactionRollsBack() { @@ -127,7 +101,7 @@ public async Task Worker_Should_DeliverMessage_When_PublishedInsideAmbientTransa var recorder = new MessageRecorder(); await using var provider = await CreateProviderAsync( connectionString, - new ResilientOutboxSignal(), + signal: null, addHandler: true, recorder); await EnsureCreatedAsync(provider); @@ -195,7 +169,7 @@ private static async Task EnsureCreatedAsync(IServiceProvider provider) private static async Task CreateProviderAsync( string connectionString, - IOutboxSignal signal, + IOutboxSignal? signal, bool addHandler, MessageRecorder? recorder = null) { @@ -203,7 +177,10 @@ private static async Task CreateProviderAsync( services.AddSingleton(recorder ?? new MessageRecorder()); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(signal); + if (signal is not null) + { + services.AddKeyedSingleton(typeof(TestDbContext), signal); + } var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs index 7b37d89c9a3..d66bb009ca7 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Outbox; using Mocha.Transport.InMemory; @@ -28,7 +29,7 @@ public async Task Worker_Should_DeliverCommittedMessage_When_ContextUsesPassword await using var provider = await CreateProviderAsync( connectionString, configuration == ConnectionConfiguration.ConnectionString ? null : dataSource); var delivered = provider.GetRequiredService>(); - var worker = provider.GetRequiredService(); + var worker = provider.GetServices().OfType().Single(); // act int committedCount; @@ -88,7 +89,7 @@ public async Task Worker_Should_ReleaseConnection_When_Idle() }.ConnectionString; await using var provider = await CreateProviderAsync(connectionString, dataSource: null); var delivered = provider.GetRequiredService>(); - var worker = provider.GetRequiredService(); + var worker = provider.GetServices().OfType().Single(); await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService() diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs index b3abc21fe7c..bbf127689e5 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs @@ -91,7 +91,7 @@ public async Task ProcessAsync_Should_DiscardExpiredMessage_When_DeadlinePassesA // the failed delivery is made due at once instead of after the retry delay await MessageRows.WaitForOutboxTimesSentAsync(connectionString, id, 1, s_timeout, TestToken); await MessageRows.MakeOutboxDueAsync(connectionString, TestToken); - provider.GetRequiredService().Set(); + provider.GetRequiredKeyedService(typeof(TestDbContext)).Set(); var remainingAttempts = await MessageRows.WaitForOutboxRetryAsync( connectionString, id, s_timeout, TestToken); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs index 0fc506d8357..dbcd2657767 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs @@ -153,7 +153,6 @@ public async Task Outbox_Should_ProcessPendingMessages_When_WorkerStartsAfterPer services.AddSingleton(recorder); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); @@ -229,7 +228,6 @@ public async Task Outbox_Should_ResumeProcessing_When_WorkerRestartedAfterInterr services.AddSingleton(recorder); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); @@ -459,12 +457,6 @@ private async Task CreateBusWithOutboxAsync( services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - // Register the resilient signal BEFORE UsePostgresOutbox() so that - // TryAddSingleton in AddOutboxCore() is a no-op. - // This prevents ObjectDisposedException during teardown when the - // outbox processor's own transaction commits fire the interceptor. - services.AddSingleton(); - var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); configureBus(builder); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs new file mode 100644 index 00000000000..82106c3e641 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs @@ -0,0 +1,283 @@ +#if NET9_0_OR_GREATER +using System.Collections.Concurrent; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Scheduling; +using Mocha.Transport.InMemory; +using Npgsql; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxOptionsScopeTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly DateTimeOffset s_now = new(2026, 6, 1, 12, 0, 0, TimeSpan.Zero); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task CommitAsync_Should_SignalOutbox_When_OptionsScopeIsDisposed(bool scopedFactory) + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + var registration = scopedFactory ? ContextRegistration.ScopedFactory : ContextRegistration.ScopedOptions; + await using var provider = await CreateOutboxProviderAsync(connectionString, registration, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, registration); + using var outbox = CreateOutbox(provider, db); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + await outbox.PersistAsync(CreateEnvelope(), TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(1, signal.SetCallCount); + } + + [Fact] + public async Task SaveChangesAsync_Should_NotifyScheduler_When_OptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new RecordingSchedulerSignal(); + await using var provider = await CreateSchedulingProviderAsync(connectionString, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + db.Orders.Add(new Order { Id = 2 }); + + // act + await db.SaveChangesAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal([s_now, s_now], signal.Notifications); + } + + [Fact] + public async Task CommitAsync_Should_NotifyScheduler_When_OptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new RecordingSchedulerSignal(); + await using var provider = await CreateSchedulingProviderAsync(connectionString, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + db.Orders.Add(new Order { Id = 2 }); + await db.SaveChangesAsync(TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal([s_now, s_now], signal.Notifications); + } + + [Fact] + public async Task CommitAsync_Should_SignalOwnApplication_When_ApplicationsShareEntityFrameworkServices() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + StubOutboxSignal[] signals = [new(), new(), new()]; + await using var first = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[0]); + await using var second = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[1]); + await using var third = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[2]); + ServiceProvider[] providers = [first, second, third]; + var modelSources = new HashSet(ReferenceEqualityComparer.Instance); + + // act + for (var i = 0; i < providers.Length; i++) + { + await using var scope = providers[i].CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var bus = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + await bus.PublishAsync(new OrderPlaced(i + 1), TestToken); + await transaction.CommitAsync(TestToken); + modelSources.Add(db.GetService()); + } + + // assert + Assert.Single(modelSources); + Assert.Equal([1, 1, 1], signals.Select(s => s.SetCallCount)); + } + + private async Task CreateDatabaseAsync() + { + var connectionString = await fixture.CreateDatabaseAsync(); + var options = new DbContextOptionsBuilder().UseTestNpgsql(connectionString).Options; + await using var db = new ScopeDbContext(options); + await db.Database.EnsureCreatedAsync(TestToken); + return connectionString; + } + + private static async Task CreateContextOutlivingScopeAsync( + IServiceProvider provider, + ContextRegistration registration) + { + await using var scope = provider.CreateAsyncScope(); + var db = registration == ContextRegistration.ScopedFactory + ? await scope.ServiceProvider + .GetRequiredService>() + .CreateDbContextAsync(TestToken) + : new ScopeDbContext(scope.ServiceProvider.GetRequiredService>()); + db.Orders.Add(new Order { Id = 1 }); + await db.SaveChangesAsync(TestToken); + return db; + } + + private static async Task CountOrdersAsync(string connectionString) + { + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(TestToken); + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM orders"; + return (long)(await command.ExecuteScalarAsync(TestToken))!; + } + + private static Task CreateOutboxProviderAsync( + string connectionString, + ContextRegistration registration, + IOutboxSignal signal) + => CreateProviderAsync( + connectionString, + registration, + services => services.AddKeyedSingleton(typeof(ScopeDbContext), signal), + static ef => ef.UsePostgresOutbox()); + + // The outbox gets a signal of its own, so that only the commit of the context reaches the application's signal. + private static PostgresMessageOutbox CreateOutbox(IServiceProvider provider, ScopeDbContext db) + { + var options = provider + .GetRequiredService>() + .Get(typeof(ScopeDbContext).FullName); + + return new PostgresMessageOutbox( + db, + new StubOutboxSignal(), + options.Queries.InsertEnvelope, + requireTransaction: true); + } + + private static MessageEnvelope CreateEnvelope() + => new() + { + MessageId = Guid.NewGuid().ToString(), + MessageType = "urn:message:order-placed", + DestinationAddress = "memory://test/queue", + SentAt = DateTimeOffset.UtcNow, + Body = "{\"orderId\":1}"u8.ToArray() + }; + + private static Task CreateSchedulingProviderAsync( + string connectionString, + ISchedulerSignal signal) + => CreateProviderAsync( + connectionString, + ContextRegistration.ScopedFactory, + services => + { + services.AddSingleton(signal); + services.AddSingleton(new FakeTimeProvider(s_now)); + }, + static ef => ef.UsePostgresScheduling()); + + private static async Task CreateProviderAsync( + string connectionString, + ContextRegistration registration, + Action configureServices, + Action configureEntityFramework) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + configureServices(services); + + if (registration == ContextRegistration.ScopedFactory) + { + services.AddDbContextFactory( + options => options.UseTestNpgsql(connectionString), + ServiceLifetime.Scoped); + } + else + { + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + } + + var builder = services.AddMessageBus(); + builder.AddEntityFramework(configureEntityFramework); + builder.AddEventHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + return provider; + } + + private enum ContextRegistration + { + ScopedFactory, + ScopedOptions + } + + public sealed class ScopeDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet Orders => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.AddPostgresOutbox(); + modelBuilder.AddPostgresScheduledMessages(); + modelBuilder.Entity().ToTable("orders").Property(order => order.Id).ValueGeneratedNever(); + } + } + + public sealed class Order + { + public int Id { get; set; } + } + + public sealed record OrderPlaced(int OrderId); + + public sealed class MessageRecorder + { + public TaskCompletionSource Delivered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public sealed class OrderPlacedHandler(MessageRecorder recorder) : IEventHandler + { + public ValueTask HandleAsync(OrderPlaced message, CancellationToken cancellationToken) + { + recorder.Delivered.TrySetResult(message); + return default; + } + } + + private sealed class RecordingSchedulerSignal : ISchedulerSignal + { + public ConcurrentQueue Notifications { get; } = new(); + + public void Notify(DateTimeOffset scheduledTime) => Notifications.Enqueue(scheduledTime); + + public Task WaitUntilAsync(DateTimeOffset wakeTime, CancellationToken cancellationToken) + => Task.Delay(Timeout.Infinite, cancellationToken); + } +} +#endif diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs new file mode 100644 index 00000000000..9b263e9cb1c --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs @@ -0,0 +1,182 @@ +using System.Data; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxRelayClockTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + private static readonly DateTimeOffset s_now = new(2050, 1, 1, 12, 0, 0, TimeSpan.Zero); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_RetryFailedSend_When_RegisteredClockDoesNotAdvance() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var recorder = new DeliveryRecorder { FailFirstAttempt = true }; + // with an hour-long polling interval, only the wait until the failed row is due can retry it in time + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromHours(1), recorder); + await MessageRows.InsertOutboxAsync(connectionString, CreateEnvelope(provider), TestToken); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + var delivered = await recorder.Delivered.Task.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(2, recorder.Attempts); + Assert.Equal("pending", delivered.Value); + } + + [Fact] + public async Task ProcessAsync_Should_DeliverUnsignaledMessage_When_RegisteredClockDoesNotAdvance() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var recorder = new DeliveryRecorder(); + await using var provider = await CreateProviderAsync( + connectionString, TimeSpan.FromMilliseconds(100), recorder); + var firstPollEnded = ObserveFirstPoll(provider); + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + // the first poll ended with an empty outbox, so only a later poll can find the next row + await firstPollEnded.WaitAsync(s_timeout, TestToken); + + // act + await MessageRows.InsertOutboxAsync(connectionString, CreateEnvelope(provider), TestToken); + var delivered = await recorder.Delivered.Task.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(1, recorder.Attempts); + Assert.Equal("pending", delivered.Value); + } + + private static Task ObserveFirstPoll(ServiceProvider provider) + { + var firstPollEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var options = provider.GetRequiredService>() + .Get(typeof(TestDbContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed) + { + firstPollEnded.TrySetResult(); + } + }; + return connection; + }; + + return firstPollEnded.Task; + } + + private static MessageEnvelope CreateEnvelope(IServiceProvider provider) + { + var runtime = provider.GetRequiredService(); + var type = runtime.GetMessageType(typeof(ClockEvent)); + return new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = type.Identity, + ContentType = MessageContentType.Json.Value, + DestinationAddress = runtime.GetPublishEndpoint(type).Address.ToString(), + Body = JsonSerializer.SerializeToUtf8Bytes(new ClockEvent { Value = "pending" }) + }; + } + + private static async Task CreateProviderAsync( + string connectionString, + TimeSpan pollingInterval, + DeliveryRecorder recorder) + { + var services = new ServiceCollection(); + services.AddSingleton(new FakeTimeProvider(s_now)); + services.AddKeyedSingleton(typeof(TestDbContext)); + services.AddSingleton(recorder); + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = pollingInterval)); + builder.AddEventHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(); + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(TestToken); + var endpoint = runtime.GetPublishEndpoint(runtime.GetMessageType(typeof(ClockEvent))); + var recordingEndpoint = new RecordingDispatchEndpoint(endpoint, recorder); + recordingEndpoint.Initialize(runtime, new DispatchEndpointConfiguration { Name = endpoint.Name }); + recordingEndpoint.Complete(runtime); + runtime.Endpoints.Remove(endpoint); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + public sealed class ClockEvent + { + public required string Value { get; init; } + } + + public sealed class ClockEventHandler(DeliveryRecorder recorder) : IEventHandler + { + public ValueTask HandleAsync(ClockEvent message, CancellationToken cancellationToken) + { + recorder.Delivered.TrySetResult(message); + return default; + } + } + + public sealed class DeliveryRecorder + { + private int _attempts; + + public bool FailFirstAttempt { get; init; } + + public int Attempts => Volatile.Read(ref _attempts); + + public TaskCompletionSource Delivered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void RecordAttempt() + { + if (Interlocked.Increment(ref _attempts) == 1 && FailFirstAttempt) + { + throw new InvalidOperationException("The first send failed deliberately."); + } + } + } + + private sealed class RecordingDispatchEndpoint(DispatchEndpoint endpoint, DeliveryRecorder recorder) + : DispatchEndpoint(endpoint.Transport) + { + protected override void OnInitialize( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + Address = endpoint.Address; + Destination = endpoint.Destination; + } + + protected override void OnComplete( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { } + + protected override ValueTask DispatchAsync(IDispatchContext context) + { + recorder.RecordAttempt(); + return endpoint.DispatchInternalAsync(context); + } + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs new file mode 100644 index 00000000000..06a5cb8e99e --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs @@ -0,0 +1,106 @@ +#if NET9_0_OR_GREATER +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; +#endif +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxRepeatedRegistrationTests +{ + private const string ConnectionString = "Host=localhost;Database=test"; + +#if NET9_0_OR_GREATER + [Fact] + public async Task UsePostgresOutbox_Should_RegisterEachInterceptorOnce_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(), + ef => ef.UsePostgresOutbox()); + await using var scope = provider.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // act + var interceptors = dbContext.GetService>() + .Select(interceptor => interceptor.GetType().Name) + .Order(StringComparer.Ordinal); + + // assert + Assert.Equal(["OutboxDbTransactionInterceptor"], interceptors); + } +#endif + + [Fact] + public async Task UsePostgresOutbox_Should_RegisterOneProcessorWorkerAndValidator_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(), + ef => ef.UsePostgresOutbox()); + + // act + var processors = provider.GetKeyedServices(typeof(TestDbContext)).Count(); + var workers = provider.GetServices().OfType().Count(); + var validators = provider.GetServices>().Count(); + + // assert + Assert.Equal(1, processors); + Assert.Equal(1, workers); + Assert.Equal(1, validators); + } + + [Fact] + public async Task UsePostgresOutbox_Should_ValidateSecondConfiguration_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1)), + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.Zero)); + var monitor = provider.GetRequiredService>(); + + // act + var exception = Assert.Throws(() => monitor.Get(typeof(TestDbContext).FullName)); + + // assert + Assert.Equal( + "PostgresOutboxOptions.PollingInterval must be greater than zero.", + exception.Message); + } + + [Fact] + public async Task UsePostgresOutbox_Should_ApplySecondConfiguration_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1)), + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(2))); + var monitor = provider.GetRequiredService>(); + + // act + var options = monitor.Get(typeof(TestDbContext).FullName); + + // assert + Assert.Equal(TimeSpan.FromSeconds(2), options.PollingInterval); + } + + private static ServiceProvider BuildProvider( + Action first, + Action second) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(options => options.UseTestNpgsql(ConnectionString)); + var builder = services.AddMessageBus(); + builder.AddInMemory(); + builder.AddEntityFramework(first); + builder.AddEntityFramework(second); + + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs index 0734846c2d0..17c4b847227 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs @@ -305,7 +305,9 @@ private static async Task CreateProviderAsync( private static RunningProcessor StartProcessor(IServiceProvider provider) { var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + var processing = provider + .GetRequiredKeyedService(typeof(TestDbContext)) + .ProcessAsync(cancellation.Token); return new RunningProcessor(processing, cancellation); } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs new file mode 100644 index 00000000000..ff9f7621000 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs @@ -0,0 +1,143 @@ +using System.Collections.Concurrent; +using System.Data; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; +using Npgsql; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxSleepLogTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_NotLogSleep_When_NextMessageIsDueAfterPollingInterval() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var logger = new CapturingLogger(); + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromMilliseconds(50), logger); + await InsertMessageInRetryDelayAsync(connectionString, TimeSpan.FromHours(1)); + var thirdPollEnded = ObservePolls(provider, count: 3); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + await thirdPollEnded.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Empty(logger.Entries); + } + + [Fact] + public async Task ProcessAsync_Should_LogSleep_When_NextMessageIsDueBeforePollingInterval() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var logger = new CapturingLogger(); + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromHours(1), logger); + await InsertMessageInRetryDelayAsync(connectionString, TimeSpan.FromMinutes(1)); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + var entry = await logger.FirstEntry.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(LogLevel.Information, entry.Level); + Assert.Equal("OutboxProcessorSleeping", entry.EventId.Name); + } + + private static Task ObservePolls(ServiceProvider provider, int count) + { + var pollsEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var polls = 0; + var options = provider.GetRequiredService>() + .Get(typeof(TestDbContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed && Interlocked.Increment(ref polls) == count) + { + pollsEnded.TrySetResult(); + } + }; + return connection; + }; + + return pollsEnded.Task; + } + + private static async Task InsertMessageInRetryDelayAsync(string connectionString, TimeSpan dueIn) + { + var envelope = new MessageEnvelope { MessageId = Guid.NewGuid().ToString() }; + var id = await MessageRows.InsertOutboxAsync(connectionString, envelope, timesSent: 1, TestToken); + + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(TestToken); + await using var command = connection.CreateCommand(); + command.CommandText = """UPDATE "outbox_messages" SET "created_at" = NOW() + @dueIn WHERE "id" = @id;"""; + command.Parameters.AddWithValue("@dueIn", dueIn); + command.Parameters.AddWithValue("@id", id); + await command.ExecuteNonQueryAsync(TestToken); + } + + private static async Task CreateProviderAsync( + string connectionString, + TimeSpan pollingInterval, + CapturingLogger logger) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton>(logger); + services.AddKeyedSingleton(typeof(TestDbContext)); + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = pollingInterval)); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + private sealed record LogEntry(LogLevel Level, EventId EventId, string Message); + + private sealed class CapturingLogger : ILogger + { + private readonly ConcurrentQueue _entries = new(); + private readonly TaskCompletionSource _firstEntry = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public IReadOnlyCollection Entries => _entries; + + public Task FirstEntry => _firstEntry.Task; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + var entry = new LogEntry(logLevel, eventId, formatter(state, exception)); + _entries.Enqueue(entry); + _firstEntry.TrySetResult(entry); + } + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs index 0e6ada60e85..122817825ba 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs @@ -11,6 +11,14 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests; public sealed class PostgresOutboxTransactionTests(PostgresFixture fixture) : IClassFixture { + private const string RequiresTransactionMessage = + "IMessageBus publishes and sends are stored in the outbox of the first DbContext registered with " + + "UsePostgresOutbox(), " + + "'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext', " + + "and require a transaction on that DbContext. " + + "Begin a transaction on it, use UseTransaction() on it for consumers, " + + "or set RequireTransaction to false in UsePostgresOutbox()."; + private static CancellationToken TestToken => TestContext.Current.CancellationToken; [Fact] @@ -28,15 +36,60 @@ public async Task PublishAsync_Should_Throw_When_TransactionIsRequiredAndNoneIsA async () => await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken)); // assert - Assert.Equal( - "The outbox for DbContext 'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " - + "or set RequireTransaction to false in UsePostgresOutbox().", - exception.Message); + Assert.Equal(RequiresTransactionMessage, exception.Message); Assert.Equal(0, await CountOutboxRowsAsync(connectionString)); } + [Fact] + public async Task PublishAsync_Should_Throw_When_ConnectionDoesNotJoinAmbientTransaction() + { + // arrange + var connectionString = + new NpgsqlConnectionStringBuilder(await fixture.CreateDatabaseAsync()) { Enlist = false }.ConnectionString; + await using var provider = await CreateProviderAsync(connectionString, new StubOutboxSignal()); + await EnsureCreatedAsync(provider); + InvalidOperationException exception; + + // act + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + exception = await Assert.ThrowsAsync( + async () => await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken)); + } + + var rowsAfterRollback = await CountOutboxRowsAsync(connectionString); + + // assert + Assert.Equal(RequiresTransactionMessage, exception.Message); + Assert.Equal(0, rowsAfterRollback); + } + + [Fact] + public async Task PublishAsync_Should_InsertRowWithTransaction_When_ConnectionIsEnlistedWithoutAmbientTransaction() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync(connectionString, new StubOutboxSignal()); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + using var transaction = new CommittableTransaction(); + await db.Database.OpenConnectionAsync(TestToken); + db.Database.EnlistTransaction(transaction); + + // act + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + var rowsBeforeCommit = await CountOutboxRowsAsync(connectionString); + transaction.Commit(); + var rowsAfterCommit = await CountOutboxRowsAsync(connectionString); + + // assert + Assert.Equal((0L, 1L), (rowsBeforeCommit, rowsAfterCommit)); + } + [Fact] public async Task PublishAsync_Should_InsertRowImmediately_When_TransactionIsNotRequired() { @@ -84,6 +137,76 @@ public async Task PublishAsync_Should_InsertRowWithTransaction_When_DatabaseTran Assert.Equal((0L, 1L), (rowsBeforeCommit, rowsAfterCommit)); } +#if NET9_0_OR_GREATER + [Fact] + public async Task CommitAsync_Should_SignalOnce_When_TransactionWroteMessages() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + await bus.PublishAsync(new OrderPlaced { OrderId = 2 }, TestToken); + var signalsBeforeCommit = signal.SetCallCount; + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal((0, 1), (signalsBeforeCommit, signal.SetCallCount)); + } + + [Fact] + public async Task CommitAsync_Should_NotSignal_When_TransactionWroteNoMessage() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(0, signal.SetCallCount); + } + + [Fact] + public async Task CommitAsync_Should_NotSignalAgain_When_LaterTransactionWroteNoMessage() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + await using (var first = await db.Database.BeginTransactionAsync(TestToken)) + { + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + await first.CommitAsync(TestToken); + } + + await using var second = await db.Database.BeginTransactionAsync(TestToken); + + // act + await second.CommitAsync(TestToken); + + // assert + Assert.Equal(1, signal.SetCallCount); + } +#endif + [Fact] public async Task PublishAsync_Should_InsertRowWithTransaction_When_AmbientTransactionIsActive() { @@ -128,9 +251,11 @@ public async Task PersistAsync_Should_Throw_When_PublishOrSendHasNoTransaction(s // assert Assert.Equal( - "The outbox for DbContext 'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " + "IMessageBus publishes and sends are stored in the outbox of the first DbContext registered with " + + "UsePostgresOutbox(), " + + "'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext', " + + "and require a transaction on that DbContext. " + + "Begin a transaction on it, use UseTransaction() on it for consumers, " + "or set RequireTransaction to false in UsePostgresOutbox().", exception.Message); Assert.Equal(0, await CountOutboxRowsAsync(connectionString)); @@ -197,7 +322,7 @@ private static async Task CreateProviderAsync( { var services = new ServiceCollection(); services.AddLogging(); - services.AddSingleton(signal); + services.AddKeyedSingleton(typeof(TransactionDbContext), signal); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); var builder = services.AddMessageBus(); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs index 5e9cffe4d14..9015f09a470 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs @@ -32,7 +32,7 @@ public async Task Outbox_Should_RetryMessage_When_MessageTypeIsUnknown() TestContext.Current.CancellationToken); // act - host.Services.GetRequiredService().Set(); + host.Services.GetRequiredKeyedService(typeof(TestDbContext)).Set(); // assert var timesSent = await MessageRows.WaitForOutboxTimesSentAsync( @@ -66,7 +66,7 @@ public async Task Outbox_Should_RetryMessage_When_DestinationIsUnresolvable() TestContext.Current.CancellationToken); // act - host.Services.GetRequiredService().Set(); + host.Services.GetRequiredKeyedService(typeof(TestDbContext)).Set(); // assert var timesSent = await MessageRows.WaitForOutboxTimesSentAsync( diff --git a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs index 81a43729961..53f91e167dc 100644 --- a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs @@ -1,14 +1,10 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Diagnostics.Internal; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Time.Testing; using Mocha.EntityFrameworkCore; using Mocha.Scheduling; -#pragma warning disable EF1001 // LoggingOptions is an internal EF Core API, used here only to construct event data for tests. - namespace Mocha.Tests.Scheduling; public sealed class SchedulingInterceptorTests : IDisposable @@ -16,6 +12,9 @@ public sealed class SchedulingInterceptorTests : IDisposable private static readonly DateTimeOffset s_baseTime = new(2026, 6, 1, 12, 0, 0, TimeSpan.Zero); + private static readonly SchedulingDbTransactionInterceptor s_transactionInterceptor = new(); + private static readonly SchedulingSaveChangesInterceptor s_saveChangesInterceptor = new(); + private readonly SqliteConnection _connection; public SchedulingInterceptorTests() @@ -28,12 +27,14 @@ public SchedulingInterceptorTests() public void TransactionCommitted_Should_NotifySignalWithExactTime_When_Called() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingDbTransactionInterceptor(signal, timeProvider); + using var services = CreateServices(signal); + using var scope = services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + using var transaction = dbContext.Database.BeginTransaction(); // act - interceptor.TransactionCommitted(null!, null!); + transaction.Commit(); // assert var notification = Assert.Single(signal.Notifications); @@ -44,12 +45,15 @@ public void TransactionCommitted_Should_NotifySignalWithExactTime_When_Called() public async Task TransactionCommittedAsync_Should_NotifySignalWithExactTime_When_Called() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingDbTransactionInterceptor(signal, timeProvider); + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await dbContext.Database.BeginTransactionAsync( + TestContext.Current.CancellationToken); // act - await interceptor.TransactionCommittedAsync(null!, null!, TestContext.Current.CancellationToken); + await transaction.CommitAsync(TestContext.Current.CancellationToken); // assert var notification = Assert.Single(signal.Notifications); @@ -57,18 +61,16 @@ public async Task TransactionCommittedAsync_Should_NotifySignalWithExactTime_Whe } [Fact] - public async Task SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() + public void SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); + using var services = CreateServices(signal); + using var scope = services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); - await using var dbContext = CreateDbContext(); - var eventData = CreateSaveChangesEventData(dbContext); - - // act no transaction is open on the context - interceptor.SavedChanges(eventData, 1); + // act + dbContext.SaveChanges(); // assert var notification = Assert.Single(signal.Notifications); @@ -79,40 +81,17 @@ public async Task SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() public async Task SavedChanges_Should_NotNotifySignal_When_AmbientTransactionExists() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - await using var dbContext = CreateDbContext(); - dbContext.Database.EnsureCreated(); - - // Begin a transaction so CurrentTransaction is non-null + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); await using var transaction = await dbContext.Database.BeginTransactionAsync( TestContext.Current.CancellationToken); - var eventData = CreateSaveChangesEventData(dbContext); // act - interceptor.SavedChanges(eventData, 1); - - // assert signal should NOT have been notified - Assert.Empty(signal.Notifications); - } + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); - [Fact] - public void SavedChanges_Should_ReturnResult_When_ContextIsNull() - { - // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); - var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - var eventData = CreateSaveChangesEventData(context: null); - - // act - var result = interceptor.SavedChanges(eventData, 42); - - // assert result passes through, no notification - Assert.Equal(42, result); + // assert Assert.Empty(signal.Notifications); } @@ -120,45 +99,32 @@ public void SavedChanges_Should_ReturnResult_When_ContextIsNull() public async Task SavedChangesAsync_Should_NotifySignal_When_NoAmbientTransaction() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - await using var dbContext = CreateDbContext(); - var eventData = CreateSaveChangesEventData(dbContext); + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); // act - var result = await interceptor.SavedChangesAsync(eventData, 1, TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // assert - Assert.Equal(1, result); var notification = Assert.Single(signal.Notifications); Assert.Equal(s_baseTime, notification); } - private TestDbContext CreateDbContext() + private ServiceProvider CreateServices(RecordingSchedulerSignal signal) { - var options = new DbContextOptionsBuilder() + var messagingServices = new MessagingDbContextServices( + outboxSignal: null, + signal, + new FakeTimeProvider(s_baseTime)); + var services = new ServiceCollection(); + services.AddDbContext(options => options .UseSqlite(_connection) - .Options; - - return new TestDbContext(options); - } + .AddMessagingExtensions(new MessagingDbContextOptions(), messagingServices) + .AddInterceptors(s_transactionInterceptor, s_saveChangesInterceptor)); - private static SaveChangesCompletedEventData CreateSaveChangesEventData(DbContext? context) - { - var loggingOptions = new LoggingOptions(); - var eventDefinition = new StubEventDefinition( - loggingOptions, - new EventId(1, "TestSaveChanges"), - LogLevel.Information, - "TestSaveChanges"); - - return new SaveChangesCompletedEventData( - eventDefinition, - static (_, _) => "test", - context!, - entitiesSavedCount: 0); + return services.BuildServiceProvider(); } public void Dispose() @@ -179,12 +145,5 @@ public Task WaitUntilAsync(DateTimeOffset wakeTime, CancellationToken cancellati => Task.CompletedTask; } - private sealed class StubEventDefinition( - ILoggingOptions loggingOptions, - EventId eventId, - LogLevel level, - string eventIdCode) - : EventDefinitionBase(loggingOptions, eventId, level, eventIdCode); - private sealed class TestDbContext(DbContextOptions options) : DbContext(options); } diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index 5b6e6f9126e..1a9c380c522 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -1,6 +1,6 @@ --- title: Migrate Mocha from 16.7 to 16.8 -description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, source generator changes, and the health check, log, and trace changes that monitoring depends on." +description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, keyed outbox processors, Entity Framework Core registration changes, source generator changes, and the health check, log, and trace changes that monitoring depends on." --- Update every `Mocha.*` package in the application to version 16.8 before applying these changes. @@ -293,6 +293,20 @@ What you will observe: - For a temporary endpoint, the forwarding subscriptions and the queue are removed after the processor is disposed. When this takes longer than 30 seconds, the log shows the Warning `Deleting the temporary resources of Azure Service Bus queue '' did not complete within 00:00:30` and the stop continues. - Disposing the processor waits for running handlers. A handler that ignores its `CancellationToken` delays the stop until it returns. +## `UseTransaction()` uses its own DbContext + +`UseTransaction()` opens the consumer transaction on the DbContext of the `AddEntityFramework` call it is configured on. Previously it used the context of the last `AddEntityFramework` call. + +## The outbox processor checks for messages when idle + +Each outbox processor now checks the database for new messages when it has not been notified for `PollingInterval`, ten seconds by default. This delivers messages committed outside Entity Framework Core, for example by another process. On .NET 8, where Mocha's Entity Framework Core interceptors are not applied, it also delivers messages written in an Entity Framework Core transaction. Configure the interval with `UsePostgresOutbox(options => options.PollingInterval = ...)`. + +## Entity Framework Core services are shared across hosts + +Contexts registered with `AddEntityFramework` now share Entity Framework Core's internal service provider, and with it the model cache, across the hosts in one process, under the same rules as contexts without Mocha. In 16.7 each host had its own internal service provider. + +When `OnModelCreating` depends on a value that differs per host, for example a schema injected into the context, every host uses the model that was built first, and the outbox processor of every host uses the outbox table of that model. Replace Entity Framework Core's `IModelCacheKeyFactory` with one that adds the value to the cache key. See [Alternating between multiple models with the same DbContext type](https://learn.microsoft.com/ef/core/modeling/dynamic-model). + ## The source generator registers message types differently - An assembly that publishes or sends messages through `IMessageBus` but has no handlers or sagas now gets a generated `Add{Module}()` method, which registers the message types it publishes or sends that are declared in the same assembly. Message types from a referenced assembly, such as a contracts project, are not registered by call sites. The compile-time type of the message argument decides what is registered: a call that passes the message as an interface, an abstract class, or `object` registers nothing. See [Module naming](../handler-registration.md#module-naming). diff --git a/website/content/docs/mocha/reliability.md b/website/content/docs/mocha/reliability.md index 4a8e6a54f9f..41984438f75 100644 --- a/website/content/docs/mocha/reliability.md +++ b/website/content/docs/mocha/reliability.md @@ -757,13 +757,15 @@ public class OrderPlacedHandler(AppDbContext dbContext, IMessageBus bus) } ``` -After the transaction commits, the outbox processor detects the new message (via EF Core interceptors that signal on save and transaction commit) and dispatches it to the transport. +After the transaction commits, the outbox processor dispatches the new message to the transport. On .NET 9 and later, a commit through EF Core wakes the outbox processor at once. On .NET 8, after a commit made directly through an externally owned database transaction, and after the commit of a transaction enlisted with `Database.EnlistTransaction`, the outbox processor finds the message the next time it checks the database. + +Without a notification, the outbox processor waits up to ten seconds before checking the database for messages to send. Configure this wait with `UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1))`. ## Transaction requirements By default, the outbox requires a transaction for `PublishAsync` and `SendAsync`. Without an open database transaction on the DbContext or an ambient `TransactionScope`, these calls throw an `InvalidOperationException` and no message is written. Replies and faults are written without a transaction. -Direct bus publishes use the first DbContext registered with `UsePostgresOutbox()`. A transaction on another DbContext does not satisfy this requirement. +With more than one outbox context, `IMessageBus` publishes and sends, and the replies and faults Mocha sends from handlers, use the outbox of the first context registered with `UsePostgresOutbox()`. The transaction must be open on that context. A transaction on another DbContext does not satisfy this requirement, and `UseTransaction()` on another context does not cover `IMessageBus` publishes. Each outbox context has its own outbox processor. Inside a transaction, the message is written to the outbox table as part of that transaction. Consumers get a transaction from `UseTransaction()`, and mediator handlers from `UseEntityFrameworkTransactions()`. In other code, open one on the DbContext: @@ -825,7 +827,7 @@ builder.Services ## How the outbox processor works -The outbox processor is a background hosted service (`IHostedService`). When the EF Core interceptors detect a `SaveChanges` or transaction commit, they signal the processor through `IOutboxSignal`. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. +The outbox processor is a background hosted service (`IHostedService`). Each outbox context has its own processor and its own `IOutboxSignal`. A transaction that wrote an outbox message signals the processor of its context when it commits through EF Core. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. Dispatch middleware runs once per message, when the message is written to the outbox. The processor does not run dispatch middleware again when it sends the stored envelope.