Repository navigation
Add transactional EF Core consumer inbox deduplication #141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| using System.Runtime.CompilerServices; | ||
| using BenchmarkDotNet.Attributes; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.EntityFrameworkCore.Storage; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Npgsql; | ||
| using Relayer.Outbox.EntityFrameworkCore; | ||
| using Relayer.Outbox.PostgreSql; | ||
|
|
||
| namespace Relayer.Benchmarks; | ||
|
|
||
| /// <summary>Compares inbox middleware with the same native insert and EF transaction. Requires RELAYER_BENCHMARK_POSTGRES.</summary> | ||
| [MemoryDiagnoser] | ||
| public class InboxBenchmarks | ||
| { | ||
| private ServiceProvider _provider = null!; | ||
| private IServiceScope _scope = null!; | ||
| private DbContext _db = null!; | ||
| private Context _context = null!; | ||
| private IConsumeMiddleware _middleware = null!; | ||
| private string _insert = null!; | ||
| private string _schema = null!; | ||
| private readonly string _duplicate = Guid.CreateVersion7().ToString("D"); | ||
|
|
||
| [Params(false, true)] | ||
| public bool Duplicate { get; set; } | ||
|
|
||
| [GlobalSetup] | ||
| public async Task Setup() | ||
| { | ||
| var connection = Environment.GetEnvironmentVariable("RELAYER_BENCHMARK_POSTGRES") | ||
| ?? throw new InvalidOperationException("Set RELAYER_BENCHMARK_POSTGRES to a disposable PostgreSQL benchmark database."); | ||
| _schema = "inbox_bench_" + Guid.NewGuid().ToString("N"); | ||
| var options = new EntityFrameworkCoreOutboxOptions { Schema = _schema }; | ||
| var services = new ServiceCollection(); | ||
| services.AddDbContext<DbContext>(o => o.UseNpgsql(connection)); | ||
| services.AddSingleton<RelayerInstrumentation>(); | ||
| _provider = services.BuildServiceProvider(); | ||
| _scope = _provider.CreateScope(); | ||
| _db = _scope.ServiceProvider.GetRequiredService<DbContext>(); | ||
| await _db.Database.OpenConnectionAsync(); | ||
| await using (var create = new NpgsqlCommand(PostgreSqlOutboxSchema.CreateScript(new() { Schema = _schema }), | ||
| (NpgsqlConnection)_db.Database.GetDbConnection())) | ||
| await create.ExecuteNonQueryAsync(); | ||
| var configuration = new OutboxConfiguration(options); | ||
| _insert = configuration.InboxInsertSql; | ||
| _middleware = new EntityFrameworkCoreConsumer<DbContext>("benchmark", true, false, configuration, | ||
| _provider.GetRequiredService<RelayerInstrumentation>()); | ||
| _context = new Context(_scope.ServiceProvider) { Id = _duplicate }; | ||
| await _middleware.InvokeAsync(_context, static _ => default); | ||
| } | ||
|
|
||
| [Benchmark(Baseline = true)] | ||
| [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] | ||
| public async ValueTask NativeInsert() | ||
| { | ||
| var id = Guid.Parse(Duplicate ? _duplicate : Guid.CreateVersion7().ToString("D")); | ||
| var transaction = await _db.Database.BeginTransactionAsync().ConfigureAwait(false); | ||
| try | ||
| { | ||
| await using var command = new NpgsqlCommand(_insert, (NpgsqlConnection)_db.Database.GetDbConnection(), | ||
| (NpgsqlTransaction)transaction.GetDbTransaction()); | ||
| command.Parameters.Add(new NpgsqlParameter<string>("consumer", "benchmark")); | ||
| command.Parameters.Add(new NpgsqlParameter<Guid>("id", id)); | ||
| await command.ExecuteNonQueryAsync().ConfigureAwait(false); | ||
| await transaction.CommitAsync().ConfigureAwait(false); | ||
| } | ||
| finally { await transaction.DisposeAsync().ConfigureAwait(false); } | ||
| } | ||
|
|
||
| [Benchmark] | ||
| public ValueTask RelayerInbox() | ||
| { | ||
| _context.Id = Duplicate ? _duplicate : Guid.CreateVersion7().ToString("D"); | ||
| return _middleware.InvokeAsync(_context, static _ => default); | ||
| } | ||
|
|
||
| [GlobalCleanup] | ||
| public async Task Cleanup() | ||
| { | ||
| await using (var drop = new NpgsqlCommand($"DROP SCHEMA {PostgreSqlOutboxSchema.QuoteIdentifier(_schema)} CASCADE", | ||
| (NpgsqlConnection)_db.Database.GetDbConnection())) | ||
| await drop.ExecuteNonQueryAsync(); | ||
| await new AsyncServiceScope(_scope).DisposeAsync(); | ||
| await _provider.DisposeAsync(); | ||
| } | ||
|
|
||
| private sealed class Context(IServiceProvider services) : MessageContext | ||
| { | ||
| internal string Id { get; set; } = ""; | ||
| public override string MessageId => Id; | ||
| public override MessageType MessageType => new("benchmark", 1); | ||
| public override MessageHeaders Headers => MessageHeaders.Empty; | ||
| public override int Attempt => 1; | ||
| public override IServiceProvider Services => services; | ||
| public override MessageFeatures Features { get; } = new(); | ||
| public override CancellationToken CancellationToken => default; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
73 changes: 73 additions & 0 deletions
73
src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| using System.Runtime.CompilerServices; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.EntityFrameworkCore.Storage; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Npgsql; | ||
|
|
||
| namespace Relayer.Outbox.EntityFrameworkCore; | ||
|
|
||
| internal sealed class EntityFrameworkCoreConsumer<TContext>(string consumer, bool inbox, bool outbox, | ||
| OutboxConfiguration configuration, RelayerInstrumentation instrumentation) : IConsumeTransactionMiddleware where TContext : DbContext | ||
| { | ||
| [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] | ||
| public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) | ||
| { | ||
| var cancellation = context.CancellationToken; | ||
| var messageId = inbox ? ParseMessageId(context.MessageId) : default; | ||
| var db = context.Services.GetRequiredService<TContext>(); | ||
| if (db.Database.CurrentTransaction is not null || System.Transactions.Transaction.Current is not null) | ||
| throw new InvalidOperationException("The EF Core consumer must own its transaction. Do not nest database consumer middleware or use an ambient transaction."); | ||
| var transaction = await db.Database.BeginTransactionAsync(cancellation).ConfigureAwait(false); | ||
| try | ||
| { | ||
| if (inbox) | ||
| { | ||
| // An outbox context can bind reloaded options in a new scope. Its interceptor has registered | ||
| // the exact configuration with this transaction; never write the inbox to a different schema. | ||
| var current = outbox ? context.Services.GetRequiredService<EntityFrameworkCoreOutbox>().Get(db, configuration).Configuration : configuration; | ||
| await using var command = new NpgsqlCommand(current.InboxInsertSql, | ||
| (NpgsqlConnection)db.Database.GetDbConnection(), (NpgsqlTransaction)transaction.GetDbTransaction()); | ||
| command.Parameters.Add(new NpgsqlParameter<string>("consumer", consumer)); | ||
| command.Parameters.Add(new NpgsqlParameter<Guid>("id", messageId)); | ||
| // The unique key waits for an overlapping transaction. A rollback lets this insert succeed. | ||
| if (await command.ExecuteNonQueryAsync(cancellation).ConfigureAwait(false) == 0) | ||
| { | ||
| RequestCompletion(context); | ||
| await transaction.CommitAsync(cancellation).ConfigureAwait(false); | ||
| instrumentation.RecordInboxDuplicate(consumer); | ||
| return; | ||
| } | ||
| } | ||
| await next(context).ConfigureAwait(false); | ||
| if (!ReferenceEquals(db.Database.CurrentTransaction, transaction)) | ||
| throw new InvalidOperationException("The handler ended or replaced the consumer transaction. Save changes in the handler and let Relayer commit."); | ||
| var disposition = context.Features.Get<ISettlementFeature>()?.RequestedDisposition; | ||
| if (disposition is { Kind: not DispositionKind.Complete }) | ||
| await transaction.RollbackAsync(cancellation).ConfigureAwait(false); | ||
| else | ||
| { | ||
| RequestCompletion(context); | ||
| await transaction.CommitAsync(cancellation).ConfigureAwait(false); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| // Disposal rolls back on every exception and cancellation path before failure handling runs. | ||
| await transaction.DisposeAsync().ConfigureAwait(false); | ||
| } | ||
| } | ||
|
|
||
| private static void RequestCompletion(MessageContext context) | ||
| { | ||
| // Fix the outcome before commit. Scope disposers cannot reject work that is already durable. | ||
| if (context.Features.Get<ISettlementFeature>() is { RequestedDisposition: null } settlement) | ||
| settlement.Complete(); | ||
| } | ||
|
|
||
| internal static Guid ParseMessageId(string messageId) | ||
| { | ||
| if (!Guid.TryParse(messageId, out var id) || id == Guid.Empty || id.Version != 7) | ||
| throw new MessageEnvelopeException("Inbox processing requires the original non-empty UUIDv7 message ID."); | ||
| return id; | ||
| } | ||
| } | ||
43 changes: 43 additions & 0 deletions
43
src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.EntityFrameworkCore.Infrastructure; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| namespace Relayer.Outbox.EntityFrameworkCore; | ||
|
|
||
| /// <summary>Configures a consumer's explicit database unit of work.</summary> | ||
| public static class EntityFrameworkCoreConsumerExtensions | ||
| { | ||
| /// <summary>Wraps handling in one PostgreSQL transaction. Inbox is automatic with AddRelayerOutbox, otherwise opt in.</summary> | ||
| /// <remarks> | ||
| /// Register first, before other middleware. Handlers save changes but must not commit, roll back or replace this transaction. | ||
| /// Request retry or dead-letter before returning from handling. Before commit the boundary requests completion | ||
| /// if no outcome is pending; further settlement requests, including during scope disposal, throw. | ||
| /// Use a stable consumer identity across replicas and restarts. Batch consumers are not supported. | ||
| /// </remarks> | ||
| public static ConsumePipelineBuilder EntityFrameworkCore<TContext>(this ConsumePipelineBuilder builder, | ||
| string consumer, bool inbox = false, EntityFrameworkCoreOutboxOptions? options = null) where TContext : DbContext | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentException.ThrowIfNullOrWhiteSpace(consumer); | ||
| return builder.Use(services => | ||
| { | ||
| var context = services.GetRequiredService<TContext>(); | ||
| if (context.Database.ProviderName != "Npgsql.EntityFrameworkCore.PostgreSQL") | ||
| throw new InvalidOperationException("EF Core consumers currently require the Npgsql PostgreSQL provider."); | ||
| if (context.Database.CreateExecutionStrategy().RetriesOnFailure) | ||
| throw new InvalidOperationException("EF Core consumers require retries of the complete handler in a fresh DI scope. Disable EnableRetryOnFailure and configure Relayer consumer retries."); | ||
| var core = context.GetService<IDbContextOptions>().FindExtension<CoreOptionsExtension>(); | ||
| if (core?.MaxPoolSize is not null) | ||
| throw new InvalidOperationException("EF Core consumers require scoped DbContexts. Use AddDbContext instead of AddDbContextPool."); | ||
| OutboxConfiguration? outbox = null; | ||
| if (core?.Interceptors is { } interceptors) | ||
| foreach (var interceptor in interceptors) | ||
| if (interceptor is OutboxSaveChangesInterceptor save) outbox = save.Configuration; | ||
| if (outbox is not null && options is not null) | ||
| throw new InvalidOperationException("Configure schema and prefix on AddRelayerOutbox; the consumer inbox uses that same configuration."); | ||
| var configuration = outbox ?? new OutboxConfiguration(options ?? new()); | ||
| return new EntityFrameworkCoreConsumer<TContext>(consumer, inbox || outbox is not null, outbox is not null, | ||
| configuration, services.GetRequiredService<RelayerInstrumentation>()); | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.