Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions benchmarks/Relayer.Benchmarks/InboxBenchmarks.cs
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;
}
}
24 changes: 24 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D33](#d33-commit-triggered-dispatch-transfers-owned-buffers-to-a-named-worker) | Commit-triggered dispatch transfers owned buffers to a named worker | Accepted |
| [D34](#d34-ordered-postgresql-dispatch-drains-a-locked-lane-before-transfer) | Ordered PostgreSQL lane ownership and transfer | Accepted |
| [D35](#d35-direct-dispatch-bounds-endpoint-capability-retention) | Direct dispatch bounds endpoint capability retention | Accepted |
| [D36](#d36-an-explicit-ef-core-consumer-boundary-owns-the-inbox-transaction) | An explicit EF Core consumer boundary owns the inbox transaction | Accepted |

---

Expand Down Expand Up @@ -642,3 +643,26 @@ against the previous unbounded lookup; their raw results remain outside the repo
**Alternatives rejected.** Transport-only keys lose endpoint-specific limits. LRU adds maintenance to
every hit. Clearing the entire cache discards unrelated hot entries at once. A public cache setting
adds configuration surface before evidence shows applications need one.

## D36. An explicit EF Core consumer boundary owns the inbox transaction

**Context.** The inbox key must be durable in the same transaction as business data and outgoing rows.
Inspecting handler dependencies would introduce hidden conventions and cannot identify one owner when
several DbContexts share a scope. A preflight existence query alone races with concurrent deliveries.

**Decision.** `ConsumePipelineBuilder.EntityFrameworkCore<TContext>(consumer)` explicitly selects the
scoped context and owns a transaction around the handler and all inner middleware. Install it first.
The inbox is automatic when that context has outbox interceptors; without them it is opt-in per
consumer. Schema and prefix follow the outbox context's scoped configuration. PostgreSQL's unique
`(consumer, message_id)` key and `INSERT ... ON CONFLICT DO NOTHING` serialize concurrent duplicates.
An insert that loses to a committed row skips the handler, records a duplicate metric and permits
normal native settlement. A rollback lets the waiting delivery process the original UUIDv7 identity.

**Consequences.** Handler saves do not commit the unit. Exceptions, cancellation and non-complete
settlement requests roll back business data, inbox and outgoing rows before ordinary failure handling.
Successful handling requests completion if no outcome is pending, then commits before scope disposal
and native settlement. The one-request rule rejects any later settlement request, so disposal cannot
retry or dead-letter work after commit. Native acknowledgement loss
therefore redelivers safely. Retrying EF strategies, pooled contexts, ambient transactions and batch
consumers are rejected; Relayer retries with fresh scopes instead. Handlers must not end the owned
transaction or perform native settlement. Inbox retention remains separate work.
9 changes: 9 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,15 @@ After dispatch, rows are deleted in batches. One leased **cleanup** job handles
- A duplicate delivery is acknowledged without invoking the handler, and a metric is recorded.
- The inbox is opt-in per consumer. It is enabled automatically when the outbox is used on the same DbContext.

The implemented PostgreSQL EF Core consumer boundary explicitly selects its scoped DbContext at
composition time, validates its provider and owns the transaction around the complete handler attempt.
It inserts the inbox key before dispatch with `ON CONFLICT DO NOTHING`; the database unique constraint
coordinates overlapping instances and permits a waiting delivery to run if the first rolls back.
Outbox configuration on the selected context enables inbox deduplication automatically (D36).
Before commit the boundary requests completion if no settlement outcome is pending. The existing
one-request rule rejects settlement changes during scope disposal after the work is durable.
See [consumer configuration and failure boundaries](https://relayer.tomlonghurst.dev/docs/reference/ef-core-inbox).

### 6.6 Multi-tenancy

- `IOutboxStoreResolver` maps the current tenant to a connection or DbContext, supporting a database per tenant or a schema per tenant (CAP #699, Rebus #1218, Wolverine #556).
Expand Down
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);
Comment thread
thomhurst marked this conversation as resolved.
Resolved
}
}
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;
}
}
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>());
});
}
}
4 changes: 4 additions & 0 deletions src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ internal sealed class OutboxConfiguration
internal int Lanes { get; }
internal string InsertSql { get; }
internal PostgreSqlDirectDispatcher? Dispatcher { get; }
internal string InboxInsertSql { get; }

internal OutboxConfiguration(EntityFrameworkCoreOutboxOptions options, PostgreSqlDirectDispatcher? dispatcher = null)
{
Expand All @@ -20,6 +21,9 @@ internal OutboxConfiguration(EntityFrameworkCoreOutboxOptions options, PostgreSq
if (options.DispatchStoreName is not null) ArgumentException.ThrowIfNullOrWhiteSpace(options.DispatchStoreName);
dispatcher?.ValidateStore(options.Schema, options.TablePrefix);
Dispatcher = dispatcher;
var inbox = PostgreSqlOutboxSchema.QuoteIdentifier(options.Schema ?? "public") + "." +
PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "inbox");
InboxInsertSql = $"INSERT INTO {inbox} (consumer, message_id, processed_at) VALUES (@consumer, @id, clock_timestamp()) ON CONFLICT (consumer, message_id) DO NOTHING";
InsertSql = PostgreSqlOutboxBatch.CreateInsertSql(Table);
}
}
4 changes: 4 additions & 0 deletions src/Relayer/Failures/Failures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,14 @@ public interface IFailureClassifier
/// <remarks>
/// Get from MessageContext.Features. One request is allowed per attempt. A handler or middleware exception
/// overrides the request; cancellation, scope disposal and durable-write failures prevent settlement.
/// Transaction boundaries may request completion before commit; further requests during scope disposal then throw.
/// Do not retain this pooled feature beyond processing. Native settlement is deferred until durable work succeeds.
/// </remarks>
public interface ISettlementFeature
{
/// <summary>The requested outcome, or null when handling has not requested settlement.</summary>
Disposition? RequestedDisposition { get; }

/// <summary>Requests completion after successful handling and durable sends.</summary>
void Complete();

Expand Down
1 change: 1 addition & 0 deletions src/Relayer/Failures/PendingSettlement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Relayer;
internal sealed class PendingSettlement(DefaultMessageContext context, ConsumePipeline owner) : ISettlementFeature
{
internal Disposition? Request { get; private set; }
public Disposition? RequestedDisposition => Request;

public void Complete() => Set(Disposition.Complete);
public void Retry(TimeSpan delay) => Set(Disposition.Redeliver(delay));
Expand Down
12 changes: 12 additions & 0 deletions src/Relayer/Pipeline/ConsumePipelineBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,22 @@ public ConsumePipelineBuilder Use(IConsumeMiddleware middleware)
{
EnsureMutable();
ArgumentNullException.ThrowIfNull(middleware);
if (middleware is IConsumeTransactionMiddleware && _middleware.Count != 0)
throw new InvalidOperationException("Register the consumer transaction boundary once, before other middleware.");
_middleware.Add(middleware);
return this;
}

/// <summary>Creates concurrent middleware in a temporary synchronous startup scope. Do not retain scoped services.</summary>
/// <remarks>Services resolved by the factory must support synchronous disposal.</remarks>
public ConsumePipelineBuilder Use(Func<IServiceProvider, IConsumeMiddleware> factory)
{
EnsureMutable();
ArgumentNullException.ThrowIfNull(factory);
using var scope = _scopes.CreateScope();
return Use(factory(scope.ServiceProvider));
}

/// <summary>Attaches this endpoint's process metrics and generated failure logging.</summary>
public ConsumePipelineBuilder Telemetry(EndpointTelemetry telemetry)
{
Expand Down
3 changes: 3 additions & 0 deletions src/Relayer/Pipeline/Middleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ public interface IConsumeMiddleware
ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next);
}

/// <summary>A database transaction boundary. Register exactly once, before other consume middleware.</summary>
public interface IConsumeTransactionMiddleware : IConsumeMiddleware;

/// <summary>A step in the send pipeline.</summary>
public delegate ValueTask SendDelegate(SendContext context);

Expand Down
Loading
Loading