From e69758bd861c5201db48b8eb07855730ee14129e Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:51:55 +0000 Subject: [PATCH] feat: enlist EF Core outbox sends in database transactions (#29) --- Directory.Packages.props | 1 + .../OutboxEnlistmentBenchmarks.cs | 65 +++ .../Relayer.Benchmarks.csproj | 2 + docs/decisions.md | 28 + docs/design.md | 2 +- .../EntityFrameworkCoreOutbox.cs | 202 +++++++ .../EntityFrameworkCoreOutboxExtensions.cs | 115 ++++ .../EntityFrameworkCoreOutboxOptions.cs | 10 +- .../OutboxConfiguration.cs | 27 + .../OutboxSaveChangesInterceptor.cs | 121 ++++ .../OutboxTransactionInterceptor.cs | 77 +++ .../Relayer.Outbox.EntityFrameworkCore.csproj | 4 + .../BufferedOutboxMessage.cs | 73 +++ .../PostgreSqlOutboxBatch.cs | 93 +++ .../Relayer.Outbox.PostgreSql.csproj | 1 + src/Relayer/Sending/IOutboxEnlistment.cs | 11 +- src/Relayer/Sending/OutgoingMessage.cs | 4 +- src/Relayer/Sending/SendRoute.cs | 3 +- tests/Relayer.AotSmoke/Program.cs | 16 + .../Relayer.AotSmoke/Relayer.AotSmoke.csproj | 1 + .../EnlistmentTests.cs | 533 ++++++++++++++++++ .../Relayer.Outbox.PostgreSql.Tests.csproj | 1 + tests/Relayer.Tests/FailurePipelineTests.cs | 2 +- tests/Relayer.Tests/HealthCheckTests.cs | 2 +- tests/Relayer.Tests/SenderTests.cs | 38 +- website/docs/reference/ef-core-outbox.md | 154 +++++ website/docs/reference/outbox-stores.md | 11 +- website/docs/reference/postgres-schema.md | 6 +- website/docs/reference/postgres-store.md | 11 +- website/docs/roadmap.md | 5 +- website/docs/transports/authoring.md | 2 +- website/sidebars.js | 2 +- website/src/pages/index.js | 3 +- 33 files changed, 1594 insertions(+), 32 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxExtensions.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/OutboxSaveChangesInterceptor.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/OutboxTransactionInterceptor.cs create mode 100644 src/Relayer.Outbox.PostgreSql/BufferedOutboxMessage.cs create mode 100644 src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs create mode 100644 tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs create mode 100644 website/docs/reference/ef-core-outbox.md diff --git a/Directory.Packages.props b/Directory.Packages.props index 783767c29..dfc2f4ffa 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -31,6 +31,7 @@ + diff --git a/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs b/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs new file mode 100644 index 000000000..7e9891045 --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs @@ -0,0 +1,65 @@ +using BenchmarkDotNet.Attributes; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Outbox.EntityFrameworkCore; + +namespace Relayer.Benchmarks; + +/// Enlists a serialized send before an implicit save, then releases reusable buffers without database I/O. +[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(); + _state = ((EntityFrameworkCoreOutbox)_outbox).Get(_context, new OutboxConfiguration(new())); + KeyValuePair[] 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 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(); + } +} diff --git a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj index 68d4674f0..f82e0041b 100644 --- a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj +++ b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj @@ -8,6 +8,7 @@ + @@ -15,6 +16,7 @@ + diff --git a/docs/decisions.md b/docs/decisions.md index de35641e2..b0e09af37 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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. diff --git a/docs/design.md b/docs/design.md index 19089df59..52ce706bc 100644 --- a/docs/design.md +++ b/docs/design.md @@ -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. diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs new file mode 100644 index 000000000..56ce552bd --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs @@ -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 _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 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; + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxExtensions.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxExtensions.cs new file mode 100644 index 000000000..47121624f --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxExtensions.cs @@ -0,0 +1,115 @@ +using System.Globalization; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; + +namespace Relayer.Outbox.EntityFrameworkCore; + +/// Registers scoped EF Core transaction enlistment. Dispatch is configured separately. +public static class EntityFrameworkCoreOutboxExtensions +{ + /// Adds the scoped send enlistment shared by all participating DbContexts. + public static IServiceCollection AddRelayerEntityFrameworkCoreOutbox(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + if (services.Any(static descriptor => descriptor.ServiceType == typeof(IOutboxEnlistment)) && + !services.Any(static descriptor => descriptor.ServiceType == typeof(EntityFrameworkCoreOutbox))) + throw new InvalidOperationException("A different IOutboxEnlistment is already registered. Configure one scoped outbox integration."); + services.TryAddScoped(); + services.TryAddScoped(static provider => provider.GetRequiredService()); + services.TryAddSingleton, OutboxOptionsValidator>(); + services.AddOptions().ValidateOnStart(); + return services; + } + + /// Binds immutable options explicitly through the Options pattern, including startup validation and reload for new scopes. + public static IServiceCollection AddRelayerEntityFrameworkCoreOutbox(this IServiceCollection services, IConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + services.AddRelayerEntityFrameworkCoreOutbox(); + services.AddSingleton>(provider => + new OutboxOptionsFactory(configuration, + provider.GetServices>(), + provider.GetServices>(), + provider.GetServices>())); + services.AddSingleton>( + new ConfigurationChangeTokenSource(configuration)); + return services; + } + + /// Installs interceptors on a non-pooled PostgreSQL DbContext. Use the same scoped provider as ISender. + public static TBuilder AddRelayerOutbox(this TBuilder builder, + IServiceProvider services, EntityFrameworkCoreOutboxOptions? options = null) + where TBuilder : DbContextOptionsBuilder + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(services); + if (builder.Options.FindExtension()?.MaxPoolSize is not null) + throw new InvalidOperationException("Relayer outbox requires scoped DbContexts. Use AddDbContext instead of AddDbContextPool."); + if (builder.Options.FindExtension()?.Interceptors is { } interceptors) + foreach (var interceptor in interceptors) + if (interceptor is OutboxSaveChangesInterceptor) + throw new InvalidOperationException("AddRelayerOutbox is already configured on these DbContext options."); + options ??= services.GetRequiredService>().Value; + var outbox = services.GetRequiredService(); + var configuration = new OutboxConfiguration(options); + builder.AddInterceptors(new OutboxSaveChangesInterceptor(outbox, configuration), + new OutboxTransactionInterceptor(outbox, configuration)); + return builder; + } + + /// Selects the context that owns sends before an implicit SaveChanges transaction, or disambiguates explicit transactions. + /// Dispose before disposing the context. Uncommitted messages are discarded. Do not use a DI scope concurrently. + public static IDisposable EnlistRelayerOutbox(this DbContext context) + { + ArgumentNullException.ThrowIfNull(context); + var options = context.GetService().FindExtension(); + if (options?.Interceptors is { } interceptors) + foreach (var interceptor in interceptors) + if (interceptor is OutboxSaveChangesInterceptor save) + return save.Outbox.Select(context, save.Configuration); + throw new InvalidOperationException("Configure this DbContext with AddRelayerOutbox before calling EnlistRelayerOutbox."); + } + + private sealed class OutboxOptionsValidator : IValidateOptions + { + public ValidateOptionsResult Validate(string? name, EntityFrameworkCoreOutboxOptions options) + { + try { _ = new OutboxConfiguration(options); return ValidateOptionsResult.Success; } + catch (ArgumentException error) { return ValidateOptionsResult.Fail(error.Message); } + } + } + + // The configuration binding generator skips init-only setters; match the health integration's explicit binding. + private sealed class OutboxOptionsFactory(IConfiguration configuration, + IEnumerable> setups, + IEnumerable> postConfigures, + IEnumerable> validations) + : OptionsFactory(setups, postConfigures, validations) + { + protected override EntityFrameworkCoreOutboxOptions CreateInstance(string name) + { + var defaults = new EntityFrameworkCoreOutboxOptions(); + return new() + { + Schema = configuration[nameof(defaults.Schema)], + TablePrefix = configuration[nameof(defaults.TablePrefix)] ?? defaults.TablePrefix, + Lanes = Read(nameof(defaults.Lanes), defaults.Lanes), + LeaseDuration = Read(nameof(defaults.LeaseDuration), defaults.LeaseDuration), + MaxDispatchAttempts = Read(nameof(defaults.MaxDispatchAttempts), defaults.MaxDispatchAttempts) + }; + } + + private T Read(string key, T fallback) where T : IParsable + { + var value = configuration[key]; + if (value is null) return fallback; + if (T.TryParse(value, CultureInfo.InvariantCulture, out var parsed)) return parsed; + throw new OptionsValidationException(Options.DefaultName, typeof(EntityFrameworkCoreOutboxOptions), + [$"{key}: '{value}' is invalid."]); + } + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxOptions.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxOptions.cs index 82fa0e2b9..83f34c438 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxOptions.cs +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutboxOptions.cs @@ -4,17 +4,17 @@ namespace Relayer.Outbox.EntityFrameworkCore; public sealed class EntityFrameworkCoreOutboxOptions { /// The database schema for Relayer tables. uses the default schema. - public string? Schema { get; set; } + public string? Schema { get; init; } /// Prefix for table and index names, so several endpoints can share a schema. - public string TablePrefix { get; set; } = "relayer_"; + public string TablePrefix { get; init; } = "relayer_"; /// Number of lanes for ordered dispatch. Changing it requires draining the outbox first. - public int Lanes { get; set; } = 32; + public int Lanes { get; init; } = 32; /// How long a lane or job lease lasts without a heartbeat. - public TimeSpan LeaseDuration { get; set; } = TimeSpan.FromSeconds(30); + public TimeSpan LeaseDuration { get; init; } = TimeSpan.FromSeconds(30); /// Dispatch attempts before a row is moved to the dead table. - public int MaxDispatchAttempts { get; set; } = 10; + public int MaxDispatchAttempts { get; init; } = 10; } diff --git a/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs b/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs new file mode 100644 index 000000000..e3becfba5 --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs @@ -0,0 +1,27 @@ +using Relayer.Outbox.PostgreSql; + +namespace Relayer.Outbox.EntityFrameworkCore; + +internal sealed class OutboxConfiguration +{ + internal string Table { get; } + internal int Lanes { get; } + internal string InsertSql { get; } + + internal OutboxConfiguration(EntityFrameworkCoreOutboxOptions options) + { + // Reuse the schema's validation, including generated identifier lengths, at registration time. + _ = PostgreSqlOutboxSchema.CreateScript(new() { Schema = options.Schema, TablePrefix = options.TablePrefix }); + if (options.Lanes <= 0) throw new ArgumentOutOfRangeException(nameof(options), "Lanes must be positive."); + Table = PostgreSqlOutboxSchema.QuoteIdentifier(options.Schema ?? "public") + "." + + PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "outbox"); + Lanes = options.Lanes; + InsertSql = $""" + INSERT INTO {Table} + (id, lane, ordering_key, transport, destination, message_type, headers, body, created_at, deliver_at, tenant_id) + SELECT id, lane, convert_from(key, 'UTF8'), transport, destination, type, headers, body, created, delivery, tenant + FROM unnest(@ids, @lanes, @keys, @transports, @destinations, @types, @headers, @bodies, @created, @delivery, @tenants) + AS rows(id, lane, key, transport, destination, type, headers, body, created, delivery, tenant) + """; + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/OutboxSaveChangesInterceptor.cs b/src/Relayer.Outbox.EntityFrameworkCore/OutboxSaveChangesInterceptor.cs new file mode 100644 index 000000000..4a15fc252 --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/OutboxSaveChangesInterceptor.cs @@ -0,0 +1,121 @@ +using System.Runtime.CompilerServices; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Relayer.Outbox.EntityFrameworkCore; + +internal sealed class OutboxSaveChangesInterceptor(EntityFrameworkCoreOutbox outbox, OutboxConfiguration configuration) + : SaveChangesInterceptor +{ + internal EntityFrameworkCoreOutbox Outbox { get; } = outbox; + internal OutboxConfiguration Configuration { get; } = configuration; + + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + var state = Outbox.Get(eventData.Context!, Configuration); + state.CheckTransaction(); + state.EnsureTransactionAvailable(); + if (state.Count > 0 && state.Context.Database.CurrentTransaction is null) + { + try + { + ValidateExecutionStrategy(state.Context); + state.OwnedTransaction = state.Context.Database.BeginTransaction(); + } + catch { state.Clear(); throw; } + } + return result; + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] + public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, + InterceptionResult result, CancellationToken cancellationToken = default) + { + var state = Outbox.Get(eventData.Context!, Configuration); + state.CheckTransaction(); + state.EnsureTransactionAvailable(); + if (state.Count > 0 && state.Context.Database.CurrentTransaction is null) + { + try + { + ValidateExecutionStrategy(state.Context); + state.OwnedTransaction = await state.Context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + } + catch { state.Clear(); throw; } + } + return result; + } + + private static void ValidateExecutionStrategy(DbContext context) + { + if (context.Database.CreateExecutionStrategy().RetriesOnFailure) + throw new InvalidOperationException("Relayer outbox requires an explicit transaction with a retrying EF Core execution strategy. " + + "Wrap the complete unit in Database.CreateExecutionStrategy().Execute/ExecuteAsync, create a fresh scoped DbContext for each attempt, " + + "and begin and commit an explicit transaction inside the strategy delegate."); + } + + public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + var state = Outbox.Get(eventData.Context!, Configuration); + if (state.OwnedTransaction is { } transaction) + { + try { transaction.Commit(); } + finally + { + transaction.Dispose(); + state.OwnedTransaction = null; + state.Clear(); + } + } + return result; + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] + public override async ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, + int result, CancellationToken cancellationToken = default) + { + var state = Outbox.Get(eventData.Context!, Configuration); + if (state.OwnedTransaction is { } transaction) + { + try { await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); } + finally + { + await transaction.DisposeAsync().ConfigureAwait(false); + state.OwnedTransaction = null; + state.Clear(); + } + } + return result; + } + + public override void SaveChangesFailed(DbContextErrorEventData eventData) => Failed(eventData.Context!); + public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default) => + FailedAsync(eventData.Context!); + public override void SaveChangesCanceled(DbContextEventData eventData) => Failed(eventData.Context!); + public override Task SaveChangesCanceledAsync(DbContextEventData eventData, CancellationToken cancellationToken = default) => + FailedAsync(eventData.Context!); + + private void Failed(DbContext context) + { + var state = Outbox.Get(context, Configuration); + if (state.OwnedTransaction is { } transaction) + { + try { transaction.Dispose(); } + finally { state.OwnedTransaction = null; state.Clear(); } + } + else if (state.Transaction is { } explicitTransaction) Outbox.Invalidate(explicitTransaction); + else state.Clear(); + } + + private async Task FailedAsync(DbContext context) + { + var state = Outbox.Get(context, Configuration); + if (state.OwnedTransaction is { } transaction) + { + try { await transaction.DisposeAsync().ConfigureAwait(false); } + finally { state.OwnedTransaction = null; state.Clear(); } + } + else if (state.Transaction is { } explicitTransaction) Outbox.Invalidate(explicitTransaction); + else state.Clear(); + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/OutboxTransactionInterceptor.cs b/src/Relayer.Outbox.EntityFrameworkCore/OutboxTransactionInterceptor.cs new file mode 100644 index 000000000..59aa6a4b6 --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/OutboxTransactionInterceptor.cs @@ -0,0 +1,77 @@ +using System.Data.Common; +using System.Runtime.CompilerServices; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Relayer.Outbox.EntityFrameworkCore; + +internal sealed class OutboxTransactionInterceptor(EntityFrameworkCoreOutbox outbox, OutboxConfiguration configuration) + : DbTransactionInterceptor +{ + public override DbTransaction TransactionStarted(DbConnection connection, TransactionEndEventData eventData, DbTransaction result) + { + outbox.Started(eventData.Context!, configuration, result, newTransaction: true); + return result; + } + + public override ValueTask TransactionStartedAsync(DbConnection connection, TransactionEndEventData eventData, + DbTransaction result, CancellationToken cancellationToken = default) => + new(TransactionStarted(connection, eventData, result)); + + public override DbTransaction TransactionUsed(DbConnection connection, TransactionEventData eventData, DbTransaction result) + { + outbox.Started(eventData.Context!, configuration, result, newTransaction: false); + return result; + } + + public override ValueTask TransactionUsedAsync(DbConnection connection, TransactionEventData eventData, + DbTransaction result, CancellationToken cancellationToken = default) => + new(TransactionUsed(connection, eventData, result)); + + public override InterceptionResult TransactionCommitting(DbTransaction transaction, TransactionEventData eventData, InterceptionResult result) + { + try { outbox.Prepare(transaction)?.Execute(); } + catch { outbox.Invalidate(transaction); throw; } + return result; + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] + public override async ValueTask TransactionCommittingAsync(DbTransaction transaction, TransactionEventData eventData, + InterceptionResult result, CancellationToken cancellationToken = default) + { + try + { + if (outbox.Prepare(transaction) is { } batch) await batch.ExecuteAsync(cancellationToken).ConfigureAwait(false); + } + catch { outbox.Invalidate(transaction); throw; } + return result; + } + + public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) => outbox.Ended(transaction); + public override Task TransactionCommittedAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default) + { + outbox.Ended(transaction); + return Task.CompletedTask; + } + + public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData) => outbox.Ended(transaction); + public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default) + { + outbox.Ended(transaction); + return Task.CompletedTask; + } + + public override void TransactionFailed(DbTransaction transaction, TransactionErrorEventData eventData) => outbox.Invalidate(transaction); + public override Task TransactionFailedAsync(DbTransaction transaction, TransactionErrorEventData eventData, CancellationToken cancellationToken = default) + { + outbox.Invalidate(transaction); + return Task.CompletedTask; + } + + // Conservatively invalidate a manually rewound unit. EF's automatic savepoint rollback also reaches SaveChangesFailed. + public override void RolledBackToSavepoint(DbTransaction transaction, TransactionEventData eventData) => outbox.Invalidate(transaction); + public override Task RolledBackToSavepointAsync(DbTransaction transaction, TransactionEventData eventData, CancellationToken cancellationToken = default) + { + outbox.Invalidate(transaction); + return Task.CompletedTask; + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/Relayer.Outbox.EntityFrameworkCore.csproj b/src/Relayer.Outbox.EntityFrameworkCore/Relayer.Outbox.EntityFrameworkCore.csproj index 977eba456..eaf9d6ac7 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/Relayer.Outbox.EntityFrameworkCore.csproj +++ b/src/Relayer.Outbox.EntityFrameworkCore/Relayer.Outbox.EntityFrameworkCore.csproj @@ -8,6 +8,10 @@ + + + + diff --git a/src/Relayer.Outbox.PostgreSql/BufferedOutboxMessage.cs b/src/Relayer.Outbox.PostgreSql/BufferedOutboxMessage.cs new file mode 100644 index 000000000..5d3b1e885 --- /dev/null +++ b/src/Relayer.Outbox.PostgreSql/BufferedOutboxMessage.cs @@ -0,0 +1,73 @@ +using System.Buffers; +using System.Text; + +namespace Relayer.Outbox.PostgreSql; + +internal sealed class BufferedOutboxMessage +{ + private readonly ArrayBufferWriter _buffer = new(); + internal string Transport { get; private set; } = ""; + internal string Destination { get; private set; } = ""; + internal string MessageType { get; private set; } = ""; + internal Guid Id { get; private set; } + internal DateTimeOffset CreatedAt { get; private set; } + internal string? TenantId { get; private set; } + internal DateTimeOffset? DeliverAt { get; private set; } + internal int? Lane { get; private set; } + internal ReadOnlyMemory Body { get; private set; } + internal ReadOnlyMemory Headers { get; private set; } + internal ReadOnlyMemory? OrderingKey { get; private set; } + + internal void Copy(OutboxRecord record, int lanes) + { + var message = record.Message; + _buffer.Clear(); + Transport = record.TransportName; + Destination = message.Destination; + MessageType = record.MessageType; + Id = record.Id; + CreatedAt = record.CreatedAt.ToUniversalTime(); + TenantId = record.TenantId; + DeliverAt = message.DeliverAt?.ToUniversalTime(); + _buffer.Write(message.Body.Span); + var bodyLength = _buffer.WrittenCount; + OutboxHeaderCodec.Write(_buffer, message.Headers.Span); + var headerEnd = _buffer.WrittenCount; + if (message.OrderingKey is { } key) WriteValue(key); + // Take slices only after growth has finished: ArrayBufferWriter can replace its backing array. + Body = _buffer.WrittenMemory[..bodyLength]; + Headers = _buffer.WrittenMemory[bodyLength..headerEnd]; + OrderingKey = message.OrderingKey is null ? null : _buffer.WrittenMemory[headerEnd..]; + Lane = null; + if (OrderingKey is { } orderingKey) + { + uint hash = 2166136261; + foreach (var value in orderingKey.Span) hash = unchecked((hash ^ value) * 16777619); + Lane = (int)(hash % (uint)lanes); + } + } + + private void WriteValue(WireString value) + { + var length = value.Text is { } text ? Encoding.UTF8.GetByteCount(text) : value.Utf8.Length; + if (value.Text is { } stringValue) + { + Encoding.UTF8.GetBytes(stringValue, _buffer.GetSpan(length)); + _buffer.Advance(length); + } + else _buffer.Write(value.Utf8.Span); + } + + internal void Clear() + { + Transport = Destination = MessageType = ""; + Id = default; + CreatedAt = default; + TenantId = null; + DeliverAt = null; + Lane = null; + Body = Headers = default; + OrderingKey = null; + _buffer.Clear(); + } +} diff --git a/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs new file mode 100644 index 000000000..4d8aa5286 --- /dev/null +++ b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs @@ -0,0 +1,93 @@ +using System.Data.Common; +using System.Runtime.CompilerServices; +using Npgsql; +using NpgsqlTypes; + +namespace Relayer.Outbox.PostgreSql; + +// Column storage is reused across commits. Parameter count is fixed, including large transactions. +internal sealed class PostgreSqlOutboxBatch : IDisposable +{ + private readonly List _ids = []; + private readonly List _lanes = []; + private readonly List?> _keys = []; + private readonly List _transports = []; + private readonly List _destinations = []; + private readonly List _types = []; + private readonly List> _headers = []; + private readonly List> _bodies = []; + private readonly List _created = []; + private readonly List _delivery = []; + private readonly List _tenants = []; + private readonly NpgsqlCommand _command = new(); + + internal PostgreSqlOutboxBatch() + { + _command.Parameters.AddWithValue("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid, _ids); + _command.Parameters.AddWithValue("lanes", NpgsqlDbType.Array | NpgsqlDbType.Integer, _lanes); + _command.Parameters.AddWithValue("keys", NpgsqlDbType.Array | NpgsqlDbType.Bytea, _keys); + _command.Parameters.AddWithValue("transports", NpgsqlDbType.Array | NpgsqlDbType.Text, _transports); + _command.Parameters.AddWithValue("destinations", NpgsqlDbType.Array | NpgsqlDbType.Text, _destinations); + _command.Parameters.AddWithValue("types", NpgsqlDbType.Array | NpgsqlDbType.Text, _types); + _command.Parameters.AddWithValue("headers", NpgsqlDbType.Array | NpgsqlDbType.Bytea, _headers); + _command.Parameters.AddWithValue("bodies", NpgsqlDbType.Array | NpgsqlDbType.Bytea, _bodies); + _command.Parameters.AddWithValue("created", NpgsqlDbType.Array | NpgsqlDbType.TimestampTz, _created); + _command.Parameters.AddWithValue("delivery", NpgsqlDbType.Array | NpgsqlDbType.TimestampTz, _delivery); + _command.Parameters.AddWithValue("tenants", NpgsqlDbType.Array | NpgsqlDbType.Text, _tenants); + } + + internal void Prepare(DbTransaction transaction, string insertSql) + { + Clear(); + _command.Connection = (NpgsqlConnection)transaction.Connection!; + _command.Transaction = (NpgsqlTransaction)transaction; + _command.CommandText = insertSql; + } + + internal void Add(BufferedOutboxMessage row) + { + _ids.Add(row.Id); + _lanes.Add(row.Lane); + _keys.Add(row.OrderingKey); + _transports.Add(row.Transport); + _destinations.Add(row.Destination); + _types.Add(row.MessageType); + _headers.Add(row.Headers); + _bodies.Add(row.Body); + _created.Add(row.CreatedAt); + _delivery.Add(row.DeliverAt); + _tenants.Add(row.TenantId); + } + + internal void Execute() + { + try { _command.ExecuteNonQuery(); } + finally { Clear(); } + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + internal async ValueTask ExecuteAsync(CancellationToken cancellationToken) + { + try { await _command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } + finally { Clear(); } + } + + private void Clear() + { + _ids.Clear(); + _lanes.Clear(); + _keys.Clear(); + _transports.Clear(); + _destinations.Clear(); + _types.Clear(); + _headers.Clear(); + _bodies.Clear(); + _created.Clear(); + _delivery.Clear(); + _tenants.Clear(); + _command.Transaction = null; + _command.Connection = null; + } + + public void Dispose() => _command.Dispose(); +} diff --git a/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj b/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj index 03f0acac0..123b2cb3c 100644 --- a/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj +++ b/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Relayer/Sending/IOutboxEnlistment.cs b/src/Relayer/Sending/IOutboxEnlistment.cs index 3c6212e95..aa4653495 100644 --- a/src/Relayer/Sending/IOutboxEnlistment.cs +++ b/src/Relayer/Sending/IOutboxEnlistment.cs @@ -3,10 +3,13 @@ namespace Relayer; /// Implemented by an outbox integration and registered as a scoped service. public interface IOutboxEnlistment { - /// Whether this scope currently has an active outbox transaction. + /// Whether this scope owns an active outbox transaction or a selected pending unit of work. bool IsActive { get; } - /// Copies the message into the active transaction before completing. - /// Observe cancellation. The message's storage is borrowed only until completion. - ValueTask EnlistAsync(string transportName, OutgoingMessage message, CancellationToken cancellationToken); + /// Takes an owned copy of the original row for the active transaction before completing. + /// + /// Observe cancellation. Payload storage is borrowed only until completion. The transaction owner persists + /// buffered rows before commit. Id, MessageType and CreatedAt come from the original send envelope, including raw mode. + /// + ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken); } diff --git a/src/Relayer/Sending/OutgoingMessage.cs b/src/Relayer/Sending/OutgoingMessage.cs index 10e9b686e..cae071028 100644 --- a/src/Relayer/Sending/OutgoingMessage.cs +++ b/src/Relayer/Sending/OutgoingMessage.cs @@ -4,8 +4,8 @@ namespace Relayer; /// /// Body, header entries, header value memory, ordering-key memory, and native options are borrowed. The caller must keep them alive /// and unchanged until the transport's send completes, including faulted or cancelled completion. A transport -/// must not retain them after completion. An outbox must copy body, headers, and ordering key into durable storage before -/// enlistment completes. Headers include the original CloudEvents attributes and creation context; dispatch +/// must not retain them after completion. An outbox must take an owned copy of body, headers, and ordering key before +/// enlistment completes and persist it before transaction commit. Headers include the original CloudEvents attributes and creation context; dispatch /// must preserve them rather than generating another identity or capturing the dispatcher's trace context. /// public readonly struct OutgoingMessage diff --git a/src/Relayer/Sending/SendRoute.cs b/src/Relayer/Sending/SendRoute.cs index 955d62480..f73cad8f5 100644 --- a/src/Relayer/Sending/SendRoute.cs +++ b/src/Relayer/Sending/SendRoute.cs @@ -256,7 +256,8 @@ public ValueTask DispatchAsync() } return _outbox is null ? _route._transport.SendAsync(outgoing, CancellationToken) - : _outbox.EnlistAsync(_route._transport.Name, outgoing, CancellationToken); + : _outbox.EnlistAsync(new OutboxRecord(_metadata.MessageId, _route._transport.Name, + _route._wireType, outgoing, _metadata.Time), CancellationToken); } private bool IsEnvelopeHeader(string name) diff --git a/tests/Relayer.AotSmoke/Program.cs b/tests/Relayer.AotSmoke/Program.cs index 0deb2b1fe..8798823ae 100644 --- a/tests/Relayer.AotSmoke/Program.cs +++ b/tests/Relayer.AotSmoke/Program.cs @@ -10,6 +10,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Relayer; using Relayer.HealthChecks; +using Relayer.Outbox.EntityFrameworkCore; using Relayer.Outbox.PostgreSql; using Relayer.Serialization; using Relayer.Transports; @@ -52,6 +53,21 @@ INSERT INTO relayer_outbox (id, transport, destination, message_type, headers, b } } Console.WriteLine("PostgreSQL keyed stores and cancellation passed under Native AOT."); +// This validates scoped registration and immutable configuration, without claiming an EF compiled-model round trip. +var outboxServices = new ServiceCollection(); +outboxServices.AddRelayerEntityFrameworkCoreOutbox(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary +{ + ["Schema"] = "messaging", ["TablePrefix"] = "smoke_", ["Lanes"] = "8" +}).Build()); +using (var outboxProvider = outboxServices.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true })) +using (var outboxScope = outboxProvider.CreateScope()) +{ + var options = outboxScope.ServiceProvider.GetRequiredService>().Value; + if (options.Schema != "messaging" || options.TablePrefix != "smoke_" || options.Lanes != 8 || + outboxScope.ServiceProvider.GetRequiredService().IsActive) + throw new InvalidOperationException("EF outbox registration or immutable configuration failed under Native AOT."); +} +Console.WriteLine("EF outbox registration and immutable configuration passed under Native AOT."); var transport = new SmokeTransport(); var services = new ServiceCollection(); diff --git a/tests/Relayer.AotSmoke/Relayer.AotSmoke.csproj b/tests/Relayer.AotSmoke/Relayer.AotSmoke.csproj index 607ac4b32..8309fa98b 100644 --- a/tests/Relayer.AotSmoke/Relayer.AotSmoke.csproj +++ b/tests/Relayer.AotSmoke/Relayer.AotSmoke.csproj @@ -13,6 +13,7 @@ + diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs new file mode 100644 index 000000000..265cd1c39 --- /dev/null +++ b/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs @@ -0,0 +1,533 @@ +using System.Buffers; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Npgsql; +using Relayer.Outbox.EntityFrameworkCore; +using Relayer.Outbox.PostgreSql; +using Relayer.Serialization; +using Relayer.Transports; + +namespace Relayer.Outbox.PostgreSql.Tests; + +public class EnlistmentTests +{ + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Implicit_saves_and_explicit_commits_are_atomic_and_batched(bool synchronous) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + var scheduled = DateTimeOffset.UtcNow.AddDays(1); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var sender = scope.ServiceProvider.GetRequiredService(); + // No transaction: native sending still works. + await sender.SendAsync(new Probe(9)); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(1); + using var enlistment = db.EnlistRelayerOutbox(); + db.Add(new Order { Id = 1 }); + await sender.SendAsync(new Probe(1), o => { o.OrderingKey = "café"; o.DeliverAt = scheduled; o.Headers["custom"] = "é"; }); + await sender.SendViaOutboxAsync(new Probe(2)); + await Assert.That(await database.Count()).IsEqualTo(0L); + if (synchronous) db.SaveChanges(); else await db.SaveChangesAsync(); + await Assert.That(await database.Count()).IsEqualTo(2L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(1L); + await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(1L); + + // An outbox-only save must also create and commit a transaction. + await sender.SendAsync(new Probe(3)); + if (synchronous) db.SaveChanges(); else await db.SaveChangesAsync(); + } + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var sender = scope.ServiceProvider.GetRequiredService(); + await using var transaction = synchronous ? db.Database.BeginTransaction() : await db.Database.BeginTransactionAsync(); + await sender.SendAsync(new Probe(4)); + db.Add(new Order { Id = 2 }); + if (synchronous) db.SaveChanges(); else await db.SaveChangesAsync(); + await sender.SendAsync(new Probe(5)); + if (synchronous) db.SaveChanges(); else await db.SaveChangesAsync(); + await sender.SendAsync(new Probe(6)); // No final SaveChanges required for these rows. + await Assert.That(await database.Count()).IsEqualTo(3L); + if (synchronous) transaction.Commit(); else await transaction.CommitAsync(); + await Assert.That(scope.ServiceProvider.GetRequiredService().IsActive).IsFalse(); + } + await Assert.That(await database.Count()).IsEqualTo(6L); + await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(3L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(1); + await database.VerifyEnvelope(scheduled); + } + + [Test] + public async Task Rollback_disposal_cancellation_and_failed_saves_never_leak_messages() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var sender = scope.ServiceProvider.GetRequiredService(); + await using (var transaction = await db.Database.BeginTransactionAsync()) + { + await sender.SendAsync(new Probe(1)); + db.Add(new Order { Id = 1 }); + await db.SaveChangesAsync(); + await transaction.RollbackAsync(); + } + await using (await db.Database.BeginTransactionAsync()) await sender.SendAsync(new Probe(2)); + await Assert.That(scope.ServiceProvider.GetRequiredService().IsActive).IsFalse(); + using (db.EnlistRelayerOutbox()) + { + await sender.SendAsync(new Probe(3)); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.That(async () => await db.SaveChangesAsync(cancellation.Token)).Throws(); + } + db.ChangeTracker.Clear(); + using (db.EnlistRelayerOutbox()) + { + db.Add(new Order { Id = -1 }); // Database CHECK violation. + await sender.SendAsync(new Probe(4)); + await Assert.That(async () => await db.SaveChangesAsync()).Throws(); + } + db.ChangeTracker.Clear(); + // A failed explicit unit cannot commit its earlier buffered sends after a savepoint rollback. + await using (var transaction = await db.Database.BeginTransactionAsync()) + { + await sender.SendAsync(new Probe(5)); + db.Add(new Order { Id = -2 }); + await Assert.That(async () => await db.SaveChangesAsync()).Throws(); + await Assert.That(async () => await transaction.CommitAsync()).Throws(); + await transaction.RollbackAsync(); + } + db.ChangeTracker.Clear(); + await Assert.That(await database.Count()).IsEqualTo(0L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(0L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + // Discarded sends never reappear in a later successful unit. + using (db.EnlistRelayerOutbox()) + { + await sender.SendAsync(new Probe(6)); + await db.SaveChangesAsync(); + } + await Assert.That(await database.Count()).IsEqualTo(1L); + } + + [Test] + public async Task Multiple_contexts_select_their_owner_and_shared_transactions_use_one_insert() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var orders = scope.ServiceProvider.GetRequiredService(); + var audits = scope.ServiceProvider.GetRequiredService(); + var sender = scope.ServiceProvider.GetRequiredService(); + using (orders.EnlistRelayerOutbox()) + { + // Nested selection of the same context must not discard the outer unit's sends. + using (orders.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(1)); + // Saving another context must not steal the buffered row. + await audits.SaveChangesAsync(); + await Assert.That(await database.Count()).IsEqualTo(0L); + await orders.SaveChangesAsync(); + } + await using (var first = await orders.Database.BeginTransactionAsync()) + await using (var second = await audits.Database.BeginTransactionAsync()) + { + await Assert.That(async () => await sender.SendAsync(new Probe(2))).Throws(); + using (orders.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(3)); + using (audits.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(4)); + orders.Add(new Order { Id = 10 }); + audits.Add(new Order { Id = 20 }); + await orders.SaveChangesAsync(); + await audits.SaveChangesAsync(); + await first.CommitAsync(); + await second.RollbackAsync(); + } + await Assert.That(await database.Count()).IsEqualTo(2L); + + // EF's UseTransaction joins the same native transaction across contexts. + await using var connection = new NpgsqlConnection(database.ConnectionString); + await connection.OpenAsync(); + var options = new DbContextOptionsBuilder(); + options.UseNpgsql(connection).AddRelayerOutbox(scope.ServiceProvider, Database.Options); + await using var joined = new AuditContext(options.Options); + orders.Database.SetDbConnection(connection); + await using var shared = await orders.Database.BeginTransactionAsync(); + await joined.Database.UseTransactionAsync(shared.GetDbTransaction()); + using (orders.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(5)); + using (joined.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(6)); + orders.Add(new Order { Id = 30 }); + joined.Add(new Order { Id = 40 }); + await orders.SaveChangesAsync(); + await joined.SaveChangesAsync(); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(1L); + await shared.CommitAsync(); + await Assert.That(await database.Count()).IsEqualTo(4L); + await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(3L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(3L); + } + + [Test] + public async Task Insert_failure_rolls_back_business_data_and_borrowed_storage_is_copied() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var outbox = scope.ServiceProvider.GetRequiredService(); + byte[] body = [1, 2, 3]; + byte[] value = "héllo"u8.ToArray(); + byte[] key = "key"u8.ToArray(); + KeyValuePair[] headers = [new("custom", new WireString(value))]; + var message = new OutgoingMessage("target", body, headers, new WireString(key)); + var record = new OutboxRecord(Guid.CreateVersion7(), "events", "wire.type;v=2", message, DateTimeOffset.UtcNow, TenantId: "tenant-a"); + using (db.EnlistRelayerOutbox()) + { + await outbox.EnlistAsync(record, default); + body[0] = 9; value[0] = 9; key[0] = 9; headers[0] = default; + await db.SaveChangesAsync(); + } + await using var connection = new NpgsqlConnection(database.ConnectionString); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand($"SELECT body, headers, ordering_key, tenant_id, lane FROM {Database.Table}", connection); + int lane; + await using (var reader = await command.ExecuteReaderAsync()) + { + await reader.ReadAsync(); + await Assert.That(reader.GetFieldValue(0).SequenceEqual(new byte[] { 1, 2, 3 })).IsTrue(); + await Assert.That(DecodeHeaders(reader.GetFieldValue(1))[0]).IsEqualTo(new KeyValuePair("custom", "héllo")); + await Assert.That(reader.GetString(2)).IsEqualTo("key"); + await Assert.That(reader.GetString(3)).IsEqualTo("tenant-a"); + lane = reader.GetInt32(4); + } + await using var dataSource = NpgsqlDataSource.Create(database.ConnectionString); + var store = new PostgreSqlOutboxStore(dataSource, new() { Schema = Database.Options.Schema, TablePrefix = Database.Options.TablePrefix }); + var rows = new OutboxRecord[1]; + await Assert.That(await store.ReadPendingAsync(new(lane, DateTimeOffset.UtcNow), rows, default)).IsEqualTo(1); + await Assert.That(rows[0].Id).IsEqualTo(record.Id); + await Assert.That(rows[0].MessageType).IsEqualTo(record.MessageType); + await Assert.That(rows[0].TenantId).IsEqualTo("tenant-a"); + await Assert.That(rows[0].Message.Headers.Span[0].Value.ToString()).IsEqualTo("héllo"); + await Assert.That(await store.GetPendingCountAsync(DateTimeOffset.UtcNow, default)).IsEqualTo(1L); + // Duplicate original identity makes the single INSERT fail. Business data must roll back as well. + record = record with { Message = new OutgoingMessage("target", default) }; + using (db.EnlistRelayerOutbox()) + { + await outbox.EnlistAsync(record, default); + db.Add(new Order { Id = 1 }); + await Assert.That(async () => await db.SaveChangesAsync()).Throws(); + } + await Assert.That(await database.Count()).IsEqualTo(1L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(0L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + + [Test] + public async Task Large_transaction_uses_one_insert_with_a_fixed_parameter_count() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var outbox = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(); + var record = new OutboxRecord(default, "events", "wire.type;v=1", new("target", new byte[256]), DateTimeOffset.UtcNow); + // A per-row parameter strategy would exceed PostgreSQL's 65,535 parameter limit. + for (var i = 0; i < 7000; i++) await outbox.EnlistAsync(record with { Id = Guid.CreateVersion7() }, default); + await transaction.CommitAsync(); + await Assert.That(await database.Count()).IsEqualTo(7000L); + await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(1L); + } + + [Test] + public async Task Invalid_configuration_and_nonpersistable_messages_fail_early() + { + var services = new ServiceCollection().AddRelayerEntityFrameworkCoreOutbox(); + await using var provider = services.BuildServiceProvider(); + await using var scope = provider.CreateAsyncScope(); + await Assert.That(() => new DbContextOptionsBuilder().AddRelayerOutbox(scope.ServiceProvider, + new() { Lanes = 0 })).Throws(); + await Assert.That(() => new DbContextOptionsBuilder().AddRelayerOutbox(scope.ServiceProvider, + new() { Schema = "" })).Throws(); + using var context = new DbContext(new DbContextOptionsBuilder().Options); + await Assert.That(() => context.EnlistRelayerOutbox()).Throws(); + + var options = new DbContextOptionsBuilder(); + options.UseNpgsql("Host=unused").AddRelayerOutbox(scope.ServiceProvider); + using var configured = new OrdersContext(options.Options); + await Assert.That(() => options.AddRelayerOutbox(scope.ServiceProvider)).Throws(); + using var enlistment = configured.EnlistRelayerOutbox(); + var outbox = scope.ServiceProvider.GetRequiredService(); + var record = new OutboxRecord(default, "events", "wire.type;v=1", new("target", default), DateTimeOffset.UtcNow); + await Assert.That(async () => await outbox.EnlistAsync(record, default)).Throws(); + var native = new SendOptions(); + native.ConfigureNative(static _ => { }); + await Assert.That(async () => await outbox.EnlistAsync(record with { Message = new("target", default, options: native) }, default)).Throws(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.That(async () => await outbox.EnlistAsync(record, cancellation.Token)).Throws(); + } + + [Test] + public async Task Immutable_options_bind_validate_and_reload_for_new_scopes() + { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { ["Schema"] = "messages", ["TablePrefix"] = "orders_", ["Lanes"] = "7" }).Build(); + var services = new ServiceCollection().AddRelayerEntityFrameworkCoreOutbox(configuration); + await using var provider = services.BuildServiceProvider(); + using var first = provider.CreateScope(); + var options = first.ServiceProvider.GetRequiredService>().Value; + await Assert.That(options.Schema).IsEqualTo("messages"); + await Assert.That(options.TablePrefix).IsEqualTo("orders_"); + await Assert.That(options.Lanes).IsEqualTo(7); + configuration["Lanes"] = "11"; + configuration.Reload(); + using var second = provider.CreateScope(); + await Assert.That(second.ServiceProvider.GetRequiredService>().Value.Lanes).IsEqualTo(11); + await Assert.That(first.ServiceProvider.GetRequiredService>().Value.Lanes).IsEqualTo(7); + configuration["Lanes"] = "bad"; + using var invalid = provider.CreateScope(); + await Assert.That(() => invalid.ServiceProvider.GetRequiredService>().Value) + .Throws(); + configuration["Lanes"] = "0"; + using var zero = provider.CreateScope(); + await Assert.That(() => zero.ServiceProvider.GetRequiredService>().Value) + .Throws(); + } + + [Test] + [Arguments(false, false)] + [Arguments(false, true)] + [Arguments(true, false)] + [Arguments(true, true)] + public async Task Disposing_shared_participants_preserves_rows_until_owner_commits(bool synchronous, bool disposeContext) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + await using var connection = new NpgsqlConnection(database.ConnectionString); + await connection.OpenAsync(); + var orders = scope.ServiceProvider.GetRequiredService(); + orders.Database.SetDbConnection(connection); + var options = new DbContextOptionsBuilder(); + options.UseNpgsql(connection).AddRelayerOutbox(scope.ServiceProvider, Database.Options); + await using var joined = new AuditContext(options.Options); + var sender = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await orders.Database.BeginTransactionAsync(); + var wrapper = await joined.Database.UseTransactionAsync(transaction.GetDbTransaction()); + using (joined.EnlistRelayerOutbox()) + { + await sender.SendAsync(new Probe(1)); + joined.Add(new Order { Id = 1 }); + await joined.SaveChangesAsync(); + } + if (disposeContext) + { + if (synchronous) joined.Dispose(); else await joined.DisposeAsync(); + } + else + { + if (synchronous) wrapper!.Dispose(); else await wrapper!.DisposeAsync(); + await Assert.That(() => joined.EnlistRelayerOutbox()).Throws(); + } + // Automatic routing must ignore the detached participant without discarding its durable work. + await sender.SendAsync(new Probe(2)); + if (synchronous) transaction.Commit(); else await transaction.CommitAsync(); + await Assert.That(await database.Count()).IsEqualTo(2L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(1L); + await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(1L); + await Assert.That(scope.ServiceProvider.GetRequiredService().IsActive).IsFalse(); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + + [Test] + public async Task Disposed_shared_units_do_not_reappear_when_the_native_transaction_is_reused() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.OpenConnectionAsync(); + var options = new DbContextOptionsBuilder(); + options.UseNpgsql(db.Database.GetDbConnection()).AddRelayerOutbox(scope.ServiceProvider, Database.Options); + await using var joined = new AuditContext(options.Options); + var sender = scope.ServiceProvider.GetRequiredService(); + await using (var abandoned = await db.Database.BeginTransactionAsync()) + { + await joined.Database.UseTransactionAsync(abandoned.GetDbTransaction()); + using (joined.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(1)); + } + // No send or IsActive probe between disposal and the next BeginTransaction. + await using (var next = await db.Database.BeginTransactionAsync()) + { + using (db.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(2)); + await next.CommitAsync(); + } + await Assert.That(await database.Count()).IsEqualTo(1L); + await Assert.That(await database.Scalar($"SELECT sum(get_byte(body, 0)) FROM {Database.Table}")).IsEqualTo(2L); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Retrying_strategies_require_explicit_transactions_and_retry_complete_units(bool synchronous) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(retries: true); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + using (db.EnlistRelayerOutbox()) + { + await scope.ServiceProvider.GetRequiredService().SendAsync(new Probe(1)); + db.Add(new Order { Id = 1 }); + var error = synchronous + ? await Assert.That(() => db.SaveChanges()).Throws() + : await Assert.That(async () => await db.SaveChangesAsync()).Throws(); + await Assert.That(error!.Message).Contains("Relayer outbox"); + await Assert.That(error.Message).Contains("explicit transaction"); + } + await Assert.That(await database.Count()).IsEqualTo(0L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(0L); + var attempts = 0; + var strategy = db.Database.CreateExecutionStrategy(); + await strategy.ExecuteAsync(async () => + { + await using var attemptScope = provider.CreateAsyncScope(); + var attemptDb = attemptScope.ServiceProvider.GetRequiredService(); + var sender = attemptScope.ServiceProvider.GetRequiredService(); + await using var transaction = synchronous ? attemptDb.Database.BeginTransaction() : await attemptDb.Database.BeginTransactionAsync(); + await sender.SendAsync(new Probe(2)); + attemptDb.Add(new Order { Id = 2 }); + if (synchronous) attemptDb.SaveChanges(); else await attemptDb.SaveChangesAsync(); + if (++attempts == 1) throw new TimeoutException("Retry this complete unit after rollback."); + if (synchronous) transaction.Commit(); else await transaction.CommitAsync(); + }); + await Assert.That(attempts).IsEqualTo(2); + await Assert.That(await database.Count()).IsEqualTo(1L); + await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(1L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + + private static List> DecodeHeaders(byte[] data) + { + KeyValuePair[] entries = []; + var headers = OutboxHeaderCodec.Read(data, ref entries); + var result = new List>(headers.Length); + foreach (var header in headers.Span) result.Add(new(header.Key, header.Value.ToString())); + return result; + } + + private sealed class Database : IAsyncDisposable + { + internal static EntityFrameworkCoreOutboxOptions Options => new() { Schema = "Case\"Schema", TablePrefix = "test_" }; + internal const string Table = "\"Case\"\"Schema\".\"test_outbox\""; + private readonly PostgreSqlFixture _fixture = new(); + internal string ConnectionString => _fixture.ConnectionString; + internal async Task Start() + { + await _fixture.StartAsync(); + await using var connection = new NpgsqlConnection(ConnectionString); + await connection.OpenAsync(); + var sql = PostgreSqlOutboxSchema.CreateScript(new() { Schema = Options.Schema, TablePrefix = Options.TablePrefix }) + $""" + CREATE TABLE orders ("Id" integer PRIMARY KEY CHECK ("Id" > 0)); + CREATE TABLE batch_log (id integer); + CREATE FUNCTION log_batch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN INSERT INTO batch_log VALUES (1); RETURN NULL; END; $$; + CREATE TRIGGER batch_count AFTER INSERT ON {Table} FOR EACH STATEMENT EXECUTE FUNCTION log_batch(); + """; + await using var command = new NpgsqlCommand(sql, connection); + await command.ExecuteNonQueryAsync(); + } + internal ServiceProvider Services(bool retries = false) + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(static sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddRelayerEntityFrameworkCoreOutbox(); + services.AddDbContext((sp, o) => o.UseNpgsql(ConnectionString, native => + { + if (retries) native.EnableRetryOnFailure(1, TimeSpan.Zero, null); + }).AddRelayerOutbox(sp, Options)); + services.AddDbContext((sp, o) => o.UseNpgsql(ConnectionString).AddRelayerOutbox(sp, Options)); + services.AddRelayer(builder => + { + builder.MessageTypes.Add("outbox.probe"); + builder.AddTransport("events", transport => transport.Send("destination")); + }); + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } + internal Task Count() => Scalar($"SELECT count(*) FROM {Table}"); + internal async Task Scalar(string sql) + { + await using var connection = new NpgsqlConnection(ConnectionString); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand(sql, connection); + return (long)(await command.ExecuteScalarAsync())!; + } + internal async Task VerifyEnvelope(DateTimeOffset scheduled) + { + await using var connection = new NpgsqlConnection(ConnectionString); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand($"SELECT id, message_type, headers, body, ordering_key, lane, deliver_at FROM {Table} WHERE ordering_key IS NOT NULL", connection); + await using var reader = await command.ExecuteReaderAsync(); + await reader.ReadAsync(); + var id = reader.GetGuid(0); + await Assert.That(id.Version).IsEqualTo(7); + await Assert.That(reader.GetString(1)).IsEqualTo("outbox.probe;v=1"); + var headers = DecodeHeaders(reader.GetFieldValue(2)); + await Assert.That(headers.Single(x => x.Key == "ce_id").Value).IsEqualTo(id.ToString("D")); + await Assert.That(headers.Single(x => x.Key == "custom").Value).IsEqualTo("é"); + await Assert.That(reader.GetFieldValue(3)[0]).IsEqualTo((byte)1); + await Assert.That(reader.GetString(4)).IsEqualTo("café"); + await Assert.That(reader.GetInt32(5) is >= 0 and < 32).IsTrue(); + await Assert.That(reader.GetFieldValue(6)).IsEqualTo(scheduled.AddTicks(-(scheduled.Ticks % 10))); + } + public ValueTask DisposeAsync() => _fixture.DisposeAsync(); + } + + public sealed class OrdersContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("orders").HasKey(x => x.Id); + } + public sealed class AuditContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("orders").HasKey(x => x.Id); + } + public sealed class Order { public int Id { get; set; } } + [Message("outbox.probe")] + public sealed record Probe(byte Value); + public sealed class Empty; + private sealed class Serializer : IMessageSerializer + { + public string ContentType => "application/test"; + public void Serialize(TMessage message, IBufferWriter destination) + { destination.GetSpan(1)[0] = ((Probe)(object)message!).Value; destination.Advance(1); } + public TMessage Deserialize(ReadOnlySequence source) => throw new NotSupportedException(); + } + private sealed class Transport : ITransport + { + public int Sends { get; private set; } + public string Name => "events"; + public TransportCapabilities GetCapabilities(string endpoint) => new() { OrderedByKey = true }; + public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) { Sends++; return default; } + public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => new(new TopologyReport([])); + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public ValueTask DisposeAsync() => default; + } +} diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj b/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj index 40b8af15c..419d3bacc 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj +++ b/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj @@ -3,6 +3,7 @@ Exe + diff --git a/tests/Relayer.Tests/FailurePipelineTests.cs b/tests/Relayer.Tests/FailurePipelineTests.cs index f804c7dc9..0a410e2e1 100644 --- a/tests/Relayer.Tests/FailurePipelineTests.cs +++ b/tests/Relayer.Tests/FailurePipelineTests.cs @@ -798,7 +798,7 @@ public sealed class Lifetime(Control control) : IAsyncDisposable private sealed class InactiveOutbox : IOutboxEnlistment { public bool IsActive => false; - public ValueTask EnlistAsync(string transportName, OutgoingMessage message, CancellationToken cancellationToken) + public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken) => throw new NotSupportedException(); } private sealed class Incoming diff --git a/tests/Relayer.Tests/HealthCheckTests.cs b/tests/Relayer.Tests/HealthCheckTests.cs index 8a5745f3d..c008e5855 100644 --- a/tests/Relayer.Tests/HealthCheckTests.cs +++ b/tests/Relayer.Tests/HealthCheckTests.cs @@ -408,6 +408,6 @@ private sealed class OutboxProvider(Func> re private sealed class UnusedOutbox : IOutboxEnlistment { public bool IsActive => throw new InvalidOperationException("Health must not resolve an enlistment."); - public ValueTask EnlistAsync(string transportName, OutgoingMessage message, CancellationToken cancellationToken) => throw new NotImplementedException(); + public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken) => throw new NotImplementedException(); } } diff --git a/tests/Relayer.Tests/SenderTests.cs b/tests/Relayer.Tests/SenderTests.cs index 8a0e4998f..56941d413 100644 --- a/tests/Relayer.Tests/SenderTests.cs +++ b/tests/Relayer.Tests/SenderTests.cs @@ -206,6 +206,33 @@ await Assert.That(async () => await send) await Assert.That(transport.Entered.Task.IsCompleted).IsFalse(); } + [Test] + [Arguments(MessageEnvelopeMode.CloudEvents)] + [Arguments(MessageEnvelopeMode.Raw)] + public async Task Outbox_receives_original_metadata_independently_of_native_headers(MessageEnvelopeMode mode) + { + var services = Services(new RecordingTransport("events")); + services.AddScoped(); + services.AddRelayer(builder => + { + builder.AddMessageTypesFromThisAssembly(); + builder.DeclareRoute("events", "orders", options: new() + { EnvelopeMode = mode, HeaderNames = new("cloudEvents:") }); + }); + using var provider = services.BuildServiceProvider(); + using var scope = provider.CreateScope(); + var outbox = (TestOutbox)scope.ServiceProvider.GetRequiredService(); + outbox.IsActive = true; + var before = DateTimeOffset.UtcNow; + await scope.ServiceProvider.GetRequiredService().SendAsync(new OrderPlaced(Guid.NewGuid())); + await Assert.That(outbox.Id.Version).IsEqualTo(7); + await Assert.That(outbox.MessageType).IsEqualTo("tests.order-placed;v=2"); + await Assert.That(outbox.CreatedAt >= before && outbox.CreatedAt <= DateTimeOffset.UtcNow).IsTrue(); + if (mode == MessageEnvelopeMode.CloudEvents) + await Assert.That(outbox.Headers["cloudEvents:id"]).IsEqualTo(outbox.Id.ToString("D")); + else await Assert.That(outbox.Headers.ContainsKey("cloudEvents:id")).IsFalse(); + } + [Test] public async Task Active_scoped_outbox_enlists_automatically_and_explicit_direct_send_bypasses_it() { @@ -865,6 +892,9 @@ public async ValueTask InvokeAsync(SendContext context, SendDelegate next) private sealed class TestOutbox : IOutboxEnlistment { + public Guid Id { get; private set; } + public string? MessageType { get; private set; } + public DateTimeOffset CreatedAt { get; private set; } public bool IsActive { get; set; } public CancelAfterSuccessCompletion? Completion { get; set; } public int Count { get; private set; } @@ -874,10 +904,14 @@ private sealed class TestOutbox : IOutboxEnlistment public string? OrderingKey { get; private set; } public DateTimeOffset? DeliverAt { get; private set; } public Dictionary Headers { get; } = []; - public ValueTask EnlistAsync(string transportName, OutgoingMessage message, CancellationToken cancellationToken) + public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken) { + Id = record.Id; + MessageType = record.MessageType; + CreatedAt = record.CreatedAt; + var message = record.Message; Count++; - TransportName = transportName; + TransportName = record.TransportName; Destination = message.Destination; Body = Encoding.UTF8.GetString(message.Body.Span); OrderingKey = message.OrderingKey?.ToString(); diff --git a/website/docs/reference/ef-core-outbox.md b/website/docs/reference/ef-core-outbox.md new file mode 100644 index 000000000..08854277c --- /dev/null +++ b/website/docs/reference/ef-core-outbox.md @@ -0,0 +1,154 @@ +--- +title: EF Core transaction enlistment +description: "Persist outgoing messages atomically with PostgreSQL business changes using EF Core interceptors." +--- + +`Relayer.Outbox.EntityFrameworkCore` implements transaction enlistment for the Npgsql EF Core provider. +It buffers serialized sends, copies borrowed memory before each send completes, and writes one batched +PostgreSQL `INSERT` immediately before commit. The insert uses the same connection and transaction as +the business data. No `SaveChanges` override or outbox entity mapping is required. + +This persists rows only. Register the [PostgreSQL durable store](postgres-store.md) separately for reads, +claims and backlog health queries. A built-in dispatcher, inbox, lane leases, cleanup and outbox tracing +remain planned. No broker send occurs when an outbox transaction commits. +There are no published NuGet packages yet; use project references from a repository checkout. + +## Registration + +Create the [PostgreSQL schema](postgres-schema.md) first. Register ordinary scoped DbContexts with +the same scoped service provider used by `ISender`: + +```csharp +using Microsoft.EntityFrameworkCore; +using Relayer.Outbox.EntityFrameworkCore; + +services.AddRelayerEntityFrameworkCoreOutbox(); +services.AddDbContext((provider, options) => + options.UseNpgsql(connectionString).AddRelayerOutbox(provider)); +``` + +Keep your normal `AddRelayer` message and route registrations. Register these interceptors on each +participating DbContext. Context pooling, concurrent use of one service scope and ambient +`TransactionScope` enlistment are not supported. Other EF database providers fail on first use; +SQL Server and MySQL schemas are still planned. + +The defaults are schema `public`, table prefix `relayer_`, and 32 lanes. Set immutable options per context: + +```csharp +options.UseNpgsql(connectionString).AddRelayerOutbox(provider, + new EntityFrameworkCoreOutboxOptions + { + Schema = "messaging", + TablePrefix = "orders_", + Lanes = 32 + }); +``` + +Alternatively, `services.AddRelayerEntityFrameworkCoreOutbox(configuration.GetSection("Outbox"))` +binds immutable defaults through the Options pattern. `IOptionsSnapshot` +keeps a scope's settings stable; configuration changes apply to newly created scopes. Invalid identifiers, +nonpositive lane counts and malformed numeric values fail validation. A per-context options argument +overrides those defaults. Always match the deployed schema and prefix. Drain the outbox before changing lanes. +`LeaseDuration` and `MaxDispatchAttempts` belong to the planned dispatcher and do not affect enlistment. + +## Save without an explicit transaction + +Select the context before sending, so Relayer knows which future save owns the messages: + +```csharp +using (db.EnlistRelayerOutbox()) +{ + db.Orders.Add(order); + await sender.SendAsync(new OrderPlaced(order.Id), cancellationToken); + await db.SaveChangesAsync(cancellationToken); +} +``` + +`SaveChangesAsync` creates an owned transaction when rows are buffered, even for a single business +command or an outbox-only save. It commits business changes and outgoing rows together. Synchronous +`SaveChanges` works too. Disposing the selection before saving discards unsaved messages. A second save +within the selection starts a new unit. Disposing the selection never commits anything. + +## Explicit transactions + +Starting an EF transaction activates automatic enlistment when it is the scope's only active context: + +```csharp +await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken); +await sender.SendAsync(new OrderPlaced(order.Id), cancellationToken); +db.Orders.Add(order); +await db.SaveChangesAsync(cancellationToken); +await transaction.CommitAsync(cancellationToken); +``` + +Sends made after the final save still join the same batch at commit. Several saves do not cause several +outbox inserts. `SendViaOutboxAsync` requires an active transaction or context selection; +`SendNowAsync` bypasses enlistment. Without either, `SendAsync` sends directly to the transport. + +Commit through EF's `IDbContextTransaction`, including the wrapper returned by `UseTransactionAsync`. +Calling `Commit` directly on the underlying `DbTransaction` bypasses EF interceptors and is unsupported. +Use EF's rollback and disposal APIs too. Cancellation or insertion failure prevents commit; disposing or +rolling back a transaction discards its buffered rows. Native callbacks cannot be persisted and fail before buffering. + +After a failed save, commit, or manual savepoint rollback, roll back the complete explicit transaction +and retry the whole unit with a fresh DbContext. Relayer rejects commit of an invalidated unit. +For an implicit save, insertion failure rolls back business data even if EF has already accepted tracked +changes; reusing that change tracker is not a recovery strategy. Configure EF execution strategies around +the whole explicit transaction, rather than retrying a final save alone. + +### Retrying execution strategies + +When Npgsql uses `EnableRetryOnFailure()`, an implicit save with buffered messages fails before opening +a transaction, with a Relayer error explaining the required explicit transaction. Wrap the entire unit +in EF's execution strategy and create a fresh DI scope and DbContext on each attempt: + +```csharp +await strategyContext.Database.CreateExecutionStrategy().ExecuteAsync(async () => +{ + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var sender = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken); + db.Orders.Add(new Order { Id = orderId }); + await sender.SendAsync(new OrderPlaced(orderId), cancellationToken); + await db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); +}); +``` + +Synchronous `Execute`, `SaveChanges` and transaction methods follow the same pattern. Do not carry +tracked entities or buffered messages from a failed attempt into the next attempt. A connection failure +during commit can leave the outcome unknown; retries still require application-level idempotency. + +## Several DbContexts + +Each context owns its own messages. Saving another context does not consume that buffer. When two +contexts have active transactions, wrap each send group in `context.EnlistRelayerOutbox()` to select +the owner; ambiguous automatic sends fail. Nested selections restore the previous owner when disposed +in reverse creation order. Dispose selections before their contexts. + +Contexts may share a native connection and transaction with EF's `UseTransactionAsync`. Configure them +with the same scoped provider, schema, prefix and lane count. Select each owner while sending and +commit through EF. Relayer combines their rows into one insert for that native transaction. +Disposing a joined context or its borrowed transaction wrapper leaves its buffered messages attached +to the live native transaction. Automatic sends then select the remaining active context. Commit or +rollback through the owner ends the entire shared unit. Complete that transaction before reusing a +detached context for another unit; Relayer rejects reuse that could discard its pending messages. + +## Stored representation + +`IOutboxEnlistment.EnlistAsync(OutboxRecord, CancellationToken)` receives the original UUIDv7 ID, +stable wire type and creation time directly from the send pipeline. This also works with raw envelopes +and custom native header names; Relayer does not infer identity by scanning headers. +The serialized body, all headers, ordering key and delivery time survive buffer reuse. New sends have +zero attempts and no dispatch error; callers cannot supply a lane. Tenant ID is preserved when supplied +through the low-level record contract; automatic tenant resolution remains planned. + +Header codec version 1 uses little-endian Int32 version and count, followed by name/value pairs, each +with an Int32 byte length and UTF-8 bytes. Header order and duplicate names are preserved. Ordered rows +use FNV-1a over the UTF-8 ordering key, modulo the configured lane count; unordered rows have a null lane. +The writer passes reusable column lists to one `unnest` insert, with a fixed parameter count for large batches. + +The enlistment pipeline uses no reflection or runtime code generation. EF Core and its provider still +require their own supported compiled-model/query setup for Native AOT; the database transaction tests +run under the JIT and do not establish end-to-end EF Native AOT support. diff --git a/website/docs/reference/outbox-stores.md b/website/docs/reference/outbox-stores.md index 281e6fcad..5c4626835 100644 --- a/website/docs/reference/outbox-stores.md +++ b/website/docs/reference/outbox-stores.md @@ -5,9 +5,9 @@ description: "Durable row reads, fenced claims, memory ownership and optional he The core package defines `IOutboxStore`, `OutboxRecord`, `OutboxReadRequest` and `OutboxClaim` for database integration authors. These contracts, the optional health adapter and [PostgreSQL schema scripts](postgres-schema.md) -are implemented, together with [PostgreSQL durable reads and fenced claims](postgres-store.md). -Transaction enlistment implementations, dispatch workers, lane leases and inbox deduplication -remain planned in [the outbox work](../roadmap.md). +are implemented, together with [PostgreSQL durable reads and fenced claims](postgres-store.md) +and [EF Core transaction enlistment for PostgreSQL](ef-core-outbox.md). +Dispatch workers, lane leases and inbox deduplication remain planned. ## Register a named store @@ -31,6 +31,11 @@ does not depend on health abstractions. Register stores separately from scoped ` enlistment writes through the application's native transaction, while `IOutboxStore` serves dispatch and health. Neither registration enables a background dispatcher. +The send pipeline calls `IOutboxEnlistment.EnlistAsync(OutboxRecord, CancellationToken)` with the original +identity, wire type and creation time. The enlistment takes owned copies of borrowed payload memory before +returning and persists buffered rows before transaction commit. These metadata fields remain available in raw +envelope mode and with custom header names. New records have no dispatch attempts, error or caller-supplied lane. + ## Rows and bounded reads An `OutboxRecord` contains the original UUIDv7 ID, named transport, stable wire message type including version, diff --git a/website/docs/reference/postgres-schema.md b/website/docs/reference/postgres-schema.md index 9b4051379..7dbba9484 100644 --- a/website/docs/reference/postgres-schema.md +++ b/website/docs/reference/postgres-schema.md @@ -5,8 +5,10 @@ description: "Create the shared outbox, dead outbox, inbox and lease tables with Relayer implements PostgreSQL schema creation in `Relayer.Outbox.PostgreSql`, plus an EF Core migration extension in `Relayer.Outbox.EntityFrameworkCore`. Schema creation does **not** enable durable sending, -transaction enlistment, dispatch, lease acquisition, poison-row handling or inbox deduplication. Those -integrations remain [planned](../roadmap.md). SQL Server and MySQL scripts are not implemented. +transaction enlistment, dispatch, lease acquisition, poison-row handling or inbox deduplication. +Register [EF Core transaction enlistment](ef-core-outbox.md) separately to persist outgoing rows. +Dispatch, lease acquisition, poison-row handling and inbox deduplication remain [planned](../roadmap.md). +SQL Server and MySQL scripts are not implemented. ## Print SQL diff --git a/website/docs/reference/postgres-store.md b/website/docs/reference/postgres-store.md index 3d77510f7..2b0e0304a 100644 --- a/website/docs/reference/postgres-store.md +++ b/website/docs/reference/postgres-store.md @@ -5,7 +5,8 @@ description: "Register PostgreSQL outbox reads, atomic claims, fenced outcomes a `Relayer.Outbox.PostgreSql` implements `IOutboxStore` over the [shared PostgreSQL schema](postgres-schema.md). It supplies durable reads, atomic claims, renewal, completion, failure persistence and eligible backlog counts. -Transactional enqueue, dispatch workers, ordered lane leases and inbox deduplication remain planned. +[EF Core transaction enlistment](ef-core-outbox.md) supplies atomic enqueue. ADO.NET/Dapper transaction +entry points, dispatch workers, ordered lane leases and inbox deduplication remain planned. ## Registration @@ -55,11 +56,11 @@ The store does not establish native broker delivery guarantees or ordered lane o ## Header storage -The `headers` column contains the provider's versioned binary format, shared with its future transactional writer. +The `headers` column contains the provider's versioned binary format, shared with its EF Core transactional writer. It starts with little-endian 32-bit version `1` and a header count. Each entry contains a length-prefixed UTF-8 name and a length-prefixed value. Values retain their bytes, including empty or malformed UTF-8 values. Duplicate names and ordering survive storage. Corrupt lengths, unsupported versions and trailing bytes fail explicitly. -Do not populate this column with JSON or empty bytes. Transactional row writing remains planned in -[#118](https://github.com/thomhurst/Relayer/issues/118); this store currently serves applications that already write -compatible rows. It does not generate identities, serialize messages, or rewrite envelopes during reads. +Do not populate this column with JSON or empty bytes. EF Core writes compatible rows through its registered +interceptors. ADO.NET/Dapper transaction entry points remain planned in [#118](https://github.com/thomhurst/Relayer/issues/118). +The store does not generate identities, serialize messages, or rewrite envelopes during reads. diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md index bc6ed02db..3b7ca8e9c 100644 --- a/website/docs/roadmap.md +++ b/website/docs/roadmap.md @@ -13,8 +13,9 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu - Compile-time analyzers and a code fix ([diagnostics](reference/diagnostics.md)). - The scoped send pipeline, send middleware and outbox enlistment hooks. - Provider-owned tracing and direct single/batch send tracing, integrated with the in-memory adapter's delivery and native settlement spans. Outbox tracing remains planned. -- The [durable outbox store contract](reference/outbox-stores.md), with bounded reads, fenced claims and an optional keyed health adapter, plus the [PostgreSQL read/claim implementation](reference/postgres-store.md). Transactional enqueue and dispatch workers remain planned. -- [PostgreSQL schema scripts and database CLI](reference/postgres-schema.md), including an application-owned EF Core migration path. Durable sending and dispatch remain planned. +- The [durable outbox store contract](reference/outbox-stores.md), with bounded reads, fenced claims and an optional keyed health adapter, plus the [PostgreSQL read/claim implementation](reference/postgres-store.md). Dispatch workers remain planned. +- [PostgreSQL schema scripts and database CLI](reference/postgres-schema.md), including an application-owned EF Core migration path. +- [EF Core transaction enlistment for PostgreSQL](reference/ef-core-outbox.md): implicit saves, explicit transactions, atomic rollback, multiple contexts and one batched insert per transaction. Dispatch and inbox remain planned. - The consume pipeline and the native receive SPI. - Generated batch handler execution, durable partial-failure decisions, and validated native/client-side receive executors for transport authors. - Typed failure classification, in-process retries, delayed redelivery and dead-letter copies with error history. diff --git a/website/docs/transports/authoring.md b/website/docs/transports/authoring.md index da0d92770..6f73b222b 100644 --- a/website/docs/transports/authoring.md +++ b/website/docs/transports/authoring.md @@ -41,7 +41,7 @@ var outgoing = new OutgoingMessage( await transport.SendAsync(outgoing, cancellationToken); ``` -The body, header entries, header value buffers, batch array, and native options must remain alive and unchanged until the send completes, including faulted or cancelled completion. A transport must finish using that memory before completion; it cannot return early while a native operation still uses the buffers. The caller can then return pooled storage. An outbox copies the body and headers into durable storage before enlistment completes; dispatch reconstructs the same send shape from the persisted fields. The transport name belongs to routing/outbox storage rather than the message passed to an already selected transport. +The body, header entries, header value buffers, batch array, and native options must remain alive and unchanged until the send completes, including faulted or cancelled completion. A transport must finish using that memory before completion; it cannot return early while a native operation still uses the buffers. The caller can then return pooled storage. An outbox takes owned copies of the body and headers before enlistment completes and persists them before transaction commit; dispatch reconstructs the same send shape from the persisted fields. The transport name belongs to routing/outbox storage rather than the message passed to an already selected transport. `options` carries only the native callbacks at this seam. The caller has already resolved `SendOptions.Headers`, `OrderingKey`, and `DeliverAt` into the other arguments. Options are borrowed, so callers must not mutate them during a send. diff --git a/website/sidebars.js b/website/sidebars.js index f83bfcffa..2cd87d731 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -38,7 +38,7 @@ const sidebars = { { type: 'category', label: 'Reference', - items: ['reference/diagnostics', 'reference/outbox-stores', 'reference/postgres-schema', 'reference/postgres-store'], + items: ['reference/diagnostics', 'reference/outbox-stores', 'reference/postgres-schema', 'reference/postgres-store', 'reference/ef-core-outbox'], }, 'roadmap', 'contributing/documentation', diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 65aa55885..d57124d36 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -287,8 +287,9 @@ const status = [ ['Durable outbox contracts and keyed health adapter', 'Implemented core seam', true], ['PostgreSQL schema scripts, CLI and EF migration path', 'Implemented schema tooling', true], ['PostgreSQL durable reads and fenced claims', 'Implemented store operations', true], + ['EF Core transaction enlistment for PostgreSQL', 'Implemented enqueue path', true], ['Native broker health adapters', 'Planned', false], - ['EF Core and PostgreSQL outbox and inbox', 'Planned', false], + ['Outbox dispatch, leases, cleanup and inbox', 'Planned', false], ['Send and delivery tracing, settlement, metrics and logs', 'Implemented', true], ['Native broker and outbox telemetry', 'Planned', false], ];