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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<ItemGroup Label="Outbox">
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.14" />
<PackageVersion Include="Npgsql" Version="10.0.3" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
</ItemGroup>

<ItemGroup Label="Testing and benchmarks">
Expand Down
65 changes: 65 additions & 0 deletions benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using BenchmarkDotNet.Attributes;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Relayer.Outbox.EntityFrameworkCore;

namespace Relayer.Benchmarks;

/// <summary>Enlists a serialized send before an implicit save, then releases reusable buffers without database I/O.</summary>
[MemoryDiagnoser]
public class OutboxEnlistmentBenchmarks
{
private ServiceProvider _provider = null!;
private IServiceScope _scope = null!;
private DbContext _context = null!;
private IDisposable _selection = null!;
private IOutboxEnlistment _outbox = null!;
private OutboxContext _state = null!;
private OutboxRecord _record;

[Params(256, 4096)]
public int BodySize { get; set; }

[GlobalSetup]
public void Setup()
{
_provider = new ServiceCollection().AddRelayerEntityFrameworkCoreOutbox().BuildServiceProvider();
_scope = _provider.CreateScope();
var options = new DbContextOptionsBuilder();
options.UseNpgsql("Host=unused").AddRelayerOutbox(_scope.ServiceProvider);
_context = new DbContext(options.Options);
_selection = _context.EnlistRelayerOutbox();
_outbox = _scope.ServiceProvider.GetRequiredService<IOutboxEnlistment>();
_state = ((EntityFrameworkCoreOutbox)_outbox).Get(_context, new OutboxConfiguration(new()));
KeyValuePair<string, WireString>[] headers =
[
new("ce_id", new WireString("00000000-0000-7000-8000-000000000001"u8.ToArray())),
new("ce_type", new WireString("benchmark.order;v=1")),
new("traceparent", new WireString("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"))
];
_record = new(Guid.CreateVersion7(), "events", "benchmark.order;v=1",
new OutgoingMessage("orders", new byte[BodySize], headers, new WireString("customer-42")), DateTimeOffset.UtcNow);
_state.Add(_record);
_state.Clear();
}

[Benchmark]
public async ValueTask<int> EnlistAndRelease()
{
if (!_outbox.IsActive) throw new InvalidOperationException("No selected outbox context.");
await _outbox.EnlistAsync(_record, default).ConfigureAwait(false);
var row = _state.Rows[0];
var length = row.Body.Length + row.Headers.Length;
_state.Clear();
return length;
}

[GlobalCleanup]
public void Cleanup()
{
_selection.Dispose();
_context.Dispose();
_scope.Dispose();
_provider.Dispose();
}
}
2 changes: 2 additions & 0 deletions benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Logging" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Relayer.Outbox.PostgreSql\Relayer.Outbox.PostgreSql.csproj" />
<ProjectReference Include="..\..\src\Relayer\Relayer.csproj" />
<ProjectReference Include="..\..\src\Relayer.Outbox.EntityFrameworkCore\Relayer.Outbox.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\..\src\Relayer.SourceGenerators\Relayer.SourceGenerators.csproj"
ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
</ItemGroup>
Expand Down
28 changes: 28 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,31 @@ Lane columns use PostgreSQL integer, matching the durable contract's nonnegative
The EF integration currently carries the PostgreSQL dependency; future database providers need their own explicit
migration operations. This establishes schema deployment without claiming that database stores, durable sending,
dispatch workers or inbox behavior are implemented.

## D31. EF Core buffers sends for an explicitly owned context and flushes at commit

**Context.** An implicit SaveChanges transaction does not exist when a handler sends its messages.
Several DbContexts can coexist in one DI scope. EF transaction interceptors observe EF's transaction
wrapper; they cannot observe a direct call to a provider's underlying DbTransaction.Commit.
Header prefixes and raw envelope mode also make native headers unsuitable as the only enqueue metadata.

**Decision.** Scoped EF interceptors share an enlistment coordinator. A context selection owns sends
before an implicit save; one active explicit EF transaction is selected automatically, and ambiguous
transactions require explicit selection. The send seam passes an OutboxRecord containing original identity,
stable wire type and creation time. Enlistment copies borrowed storage, then flushes one batched insert
before the EF commit. An implicit save with buffered rows owns a transaction even with no business commands.
Contexts joining the same native transaction share one insert and identical schema/prefix/lane settings.
Buffered rows belong to the native transaction even after a joined context or borrowed EF wrapper is
disposed. Detached participants are excluded from automatic send selection and cannot start another
unit until their pending transaction ends. Retrying EF execution strategies require an explicit
transaction around the complete unit, with a fresh scoped context on each attempt; implicit saves
with buffered rows reject retrying strategies with an actionable error before opening a transaction.
PostgreSQL is implemented first. Its versioned header codec retains all name/value pairs; deterministic
FNV-1a lane hashing uses UTF-8 ordering keys. Tenant metadata is preserved when explicitly supplied.

**Consequences.** No SaveChanges override, entity mapping, header scanning, or process-wide mutable
state is required. Native transaction rollback/disposal abandons buffered sends. Failed explicit units and savepoint rollback
invalidate commit until the whole transaction is rolled back; callers retry complete units with fresh contexts.
Commit goes through IDbContextTransaction, including UseTransaction wrappers. Direct provider commits,
ambient TransactionScope, pooled contexts and concurrent use of a scope are outside this integration.
Schema deployment, dispatch, inbox, leases and health polling remain separate concerns.
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ The outbox is the area where every existing library has had correctness bugs, so

### 6.2 Enlisting: hard to misuse

- **EF Core:** Relayer registers a `SaveChangesInterceptor` and a `DbTransactionInterceptor`. Messages sent in the scope are added to the change set, so `SaveChangesAsync`, or a transaction you started yourself, writes them atomically. You do not need to override `SaveChanges` (Silverback #164), and it works with **multiple DbContexts** (Silverback #163). Committing the raw transaction is fine, because Relayer observes the commit through the interceptor (CAP #1675).
- **EF Core:** Relayer registers a `SaveChangesInterceptor` and a `DbTransactionInterceptor`. Before an implicit save, `context.EnlistRelayerOutbox()` explicitly selects the context that owns buffered sends. An explicit EF transaction activates enlistment automatically when unambiguous. `SaveChangesAsync`, or committing the EF transaction directly, writes business data and outgoing rows atomically. You do not need to override `SaveChanges` (Silverback #164), and it works with **multiple DbContexts** (Silverback #163). Commit through EF's `IDbContextTransaction`, including its `UseTransaction` wrapper: calling the underlying `DbTransaction.Commit` bypasses EF interception. D31 records ownership and failure boundaries; [the site](https://relayer.tomlonghurst.dev/docs/reference/ef-core-outbox) documents implemented PostgreSQL enlistment and remaining dispatch work.
- **ADO.NET / Dapper:** `await using var tx = await outbox.BeginTransactionAsync(connection)` returns a real `DbTransaction` subclass. Using it as normal is the correct usage, so there is no second "Relayer transaction" to forget.
- **MongoDB / DynamoDB:** use their session and transaction APIs in the same style.

Expand Down
202 changes: 202 additions & 0 deletions src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Relayer.Outbox.PostgreSql;

namespace Relayer.Outbox.EntityFrameworkCore;

// Scoped, like DbContext and ISender. Never shared by concurrent units of work.
internal sealed class EntityFrameworkCoreOutbox : IOutboxEnlistment, IDisposable
{
private readonly List<OutboxContext> _contexts = [];
private readonly PostgreSqlOutboxBatch _batch = new();
private Selection? _selection;

public bool IsActive => Target() is not null;

public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var target = Target() ?? throw new InvalidOperationException("Select an EF Core outbox context or begin an EF Core transaction before sending.");
target.Add(record);
return ValueTask.CompletedTask;
}

internal OutboxContext Get(DbContext context, OutboxConfiguration configuration)
{
foreach (var state in _contexts)
if (ReferenceEquals(state.Context, context)) return state;
if (context.Database.ProviderName != "Npgsql.EntityFrameworkCore.PostgreSQL")
throw new InvalidOperationException("EF Core outbox enlistment currently requires the Npgsql PostgreSQL provider.");
var created = new OutboxContext(context, configuration);
_contexts.Add(created);
return created;
}

internal IDisposable Select(DbContext context, OutboxConfiguration configuration)
{
var state = Get(context, configuration);
state.CheckTransaction();
state.EnsureTransactionAvailable();
var selection = new Selection(this, state, _selection);
state.SelectionDepth++;
_selection = selection;
return selection;
}

private OutboxContext? Target()
{
if (_selection is { State: var selected })
{
selected.CheckTransaction();
selected.EnsureTransactionAvailable();
return selected;
}
OutboxContext? target = null;
foreach (var state in _contexts)
{
state.CheckTransaction();
if (state.Transaction is null || !state.HasCurrentTransaction()) continue;
if (target is not null)
throw new InvalidOperationException("Several DbContexts have active transactions. Use context.EnlistRelayerOutbox() to select the owner of sends.");
target = state;
}
return target;
}

internal void Started(DbContext context, OutboxConfiguration configuration, DbTransaction transaction, bool newTransaction)
{
// Npgsql can reuse the same native object after disposal. A new EF transaction is a new unit.
if (newTransaction) Ended(transaction);
var state = Get(context, configuration);
state.CheckTransaction();
if (state.Transaction is not null && !ReferenceEquals(state.Transaction, transaction))
throw new InvalidOperationException("This DbContext still has buffered work in a live shared transaction. Complete that transaction before reusing the context.");
state.Transaction = transaction;
state.Detached = false;
}

internal void Ended(DbTransaction transaction)
{
foreach (var state in _contexts)
if (ReferenceEquals(state.Transaction, transaction)) state.Clear();
}

internal void Invalidate(DbTransaction transaction)
{
foreach (var state in _contexts)
if (ReferenceEquals(state.Transaction, transaction)) state.Failed = true;
}

internal PostgreSqlOutboxBatch? Prepare(DbTransaction transaction)
{
OutboxConfiguration? configuration = null;
var count = 0;
foreach (var state in _contexts)
{
if (!ReferenceEquals(state.Transaction, transaction)) continue;
if (state.Failed) throw new InvalidOperationException("This outbox unit failed. Roll back the transaction and retry the complete unit of work.");
if (configuration is not null && (configuration.Table != state.Configuration.Table || configuration.Lanes != state.Configuration.Lanes))
throw new InvalidOperationException("DbContexts sharing a transaction must use identical outbox schema, prefix and lane settings.");
configuration = state.Configuration;
count = checked(count + state.Count);
}
if (count == 0) return null;
_batch.Prepare(transaction, configuration!.InsertSql);
foreach (var state in _contexts)
if (ReferenceEquals(state.Transaction, transaction))
for (var i = 0; i < state.Count; i++) _batch.Add(state.Rows[i]);
return _batch;
}

public void Dispose()
{
foreach (var state in _contexts) state.Clear();
_batch.Dispose();
}

private sealed class Selection(EntityFrameworkCoreOutbox owner, OutboxContext state, Selection? previous) : IDisposable
{
internal OutboxContext State { get; } = state;
private bool _disposed;
public void Dispose()
{
if (_disposed) return;
if (!ReferenceEquals(owner._selection, this))
throw new InvalidOperationException("Dispose EF Core outbox selections in reverse creation order.");
owner._selection = previous;
State.SelectionDepth--;
// An explicit transaction keeps ownership until commit/rollback; an unsaved implicit unit is abandoned.
State.CheckTransaction();
if (State.SelectionDepth == 0 && State.Transaction is null) State.Clear();
_disposed = true;
}
}
}

internal sealed class OutboxContext(DbContext context, OutboxConfiguration configuration)
{
internal DbContext Context { get; } = context;
internal OutboxConfiguration Configuration { get; } = configuration;
internal DbTransaction? Transaction { get; set; }
internal IDbContextTransaction? OwnedTransaction { get; set; }
internal bool Failed { get; set; }
internal bool Detached { get; set; }
internal List<BufferedOutboxMessage> Rows { get; } = [];
internal int Count { get; private set; }
internal int SelectionDepth { get; set; }

internal void CheckTransaction()
{
if (Transaction is null) return;
// Disposing a borrowed EF wrapper does not end the native shared transaction.
// Keep its rows until native completion, even when this context no longer participates.
try
{
if (Transaction.Connection is null) Clear();
}
catch (ObjectDisposedException) { Clear(); }
}

internal bool HasCurrentTransaction()
{
if (Detached) return false;
try
{
if (ReferenceEquals(Context.Database.CurrentTransaction?.GetDbTransaction(), Transaction)) return true;
}
catch (ObjectDisposedException) { }
Detached = true;
return false;
}

internal void EnsureTransactionAvailable()
{
if (Transaction is not null && !HasCurrentTransaction())
throw new InvalidOperationException("This DbContext no longer participates in its live shared transaction. Complete that transaction before reusing the context.");
}

internal void Add(OutboxRecord record)
{
if (Failed) throw new InvalidOperationException("Roll back the failed outbox transaction before sending again.");
record.Message.ValidateForOutbox();
if (record.Id == Guid.Empty || record.Id.Version != 7 || string.IsNullOrWhiteSpace(record.MessageType))
throw new InvalidOperationException("Outbox sends require the original UUIDv7 identity and stable MessageType. Use ISender or supply the original OutboxRecord metadata.");
if (record.Attempts != 0 || record.LastError is not null || record.Lane is not null)
throw new ArgumentException("New outbox sends cannot specify dispatch attempts, errors or lanes. Lanes are computed from the ordering key.", nameof(record));
ArgumentException.ThrowIfNullOrWhiteSpace(record.TransportName);
ArgumentException.ThrowIfNullOrWhiteSpace(record.Message.Destination);
if (Count == Rows.Count) Rows.Add(new());
Rows[Count].Copy(record, Configuration.Lanes);
Count++;
}

internal void Clear()
{
for (var i = 0; i < Count; i++) Rows[i].Clear();
Count = 0;
Transaction = null;
Failed = false;
Detached = false;
}
}
Loading
Loading