From 884b57ee31069bf71738f4a17e9f5be8286488ba Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:02:24 +0000 Subject: [PATCH 1/2] feat: deduplicate EF Core consumers with a transactional inbox (#35) --- .../Relayer.Benchmarks/InboxBenchmarks.cs | 99 +++++ docs/decisions.md | 21 + docs/design.md | 7 + .../EntityFrameworkCoreConsumer.cs | 62 +++ .../EntityFrameworkCoreConsumerExtensions.cs | 41 ++ .../OutboxConfiguration.cs | 4 + src/Relayer/Failures/Failures.cs | 3 + src/Relayer/Failures/PendingSettlement.cs | 1 + .../Pipeline/ConsumePipelineBuilder.cs | 12 + src/Relayer/Pipeline/Middleware.cs | 3 + .../Telemetry/RelayerInstrumentation.cs | 4 + .../InboxTests.cs | 393 ++++++++++++++++++ .../Relayer.Outbox.PostgreSql.Tests.csproj | 2 + tests/Relayer.Tests/ConsumePipelineTests.cs | 36 ++ website/docs/reference/ef-core-inbox.md | 82 ++++ website/docs/reference/ef-core-outbox.md | 147 +------ website/docs/reference/outbox-stores.md | 82 +--- website/docs/reference/postgres-schema.md | 110 +---- website/docs/reference/postgres-store.md | 60 +-- website/docs/roadmap.md | 28 +- website/docs/transports/consume-pipeline.md | 6 + website/sidebars.js | 10 +- website/src/pages/index.js | 51 +-- 23 files changed, 794 insertions(+), 470 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/InboxBenchmarks.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs create mode 100644 src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs create mode 100644 tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs create mode 100644 website/docs/reference/ef-core-inbox.md diff --git a/benchmarks/Relayer.Benchmarks/InboxBenchmarks.cs b/benchmarks/Relayer.Benchmarks/InboxBenchmarks.cs new file mode 100644 index 000000000..aa0da4349 --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/InboxBenchmarks.cs @@ -0,0 +1,99 @@ +using System.Runtime.CompilerServices; +using BenchmarkDotNet.Attributes; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Relayer.Outbox.EntityFrameworkCore; +using Relayer.Outbox.PostgreSql; + +namespace Relayer.Benchmarks; + +/// Compares inbox middleware with the same native insert and EF transaction. Requires RELAYER_BENCHMARK_POSTGRES. +[MemoryDiagnoser] +public class InboxBenchmarks +{ + private ServiceProvider _provider = null!; + private IServiceScope _scope = null!; + private DbContext _db = null!; + private Context _context = null!; + private IConsumeMiddleware _middleware = null!; + private string _insert = null!; + private string _schema = null!; + private readonly string _duplicate = Guid.CreateVersion7().ToString("D"); + + [Params(false, true)] + public bool Duplicate { get; set; } + + [GlobalSetup] + public async Task Setup() + { + var connection = Environment.GetEnvironmentVariable("RELAYER_BENCHMARK_POSTGRES") + ?? throw new InvalidOperationException("Set RELAYER_BENCHMARK_POSTGRES to a disposable PostgreSQL benchmark database."); + _schema = "inbox_bench_" + Guid.NewGuid().ToString("N"); + var options = new EntityFrameworkCoreOutboxOptions { Schema = _schema }; + var services = new ServiceCollection(); + services.AddDbContext(o => o.UseNpgsql(connection)); + services.AddSingleton(); + _provider = services.BuildServiceProvider(); + _scope = _provider.CreateScope(); + _db = _scope.ServiceProvider.GetRequiredService(); + await _db.Database.OpenConnectionAsync(); + await using (var create = new NpgsqlCommand(PostgreSqlOutboxSchema.CreateScript(new() { Schema = _schema }), + (NpgsqlConnection)_db.Database.GetDbConnection())) + await create.ExecuteNonQueryAsync(); + var configuration = new OutboxConfiguration(options); + _insert = configuration.InboxInsertSql; + _middleware = new EntityFrameworkCoreConsumer("benchmark", true, false, configuration, + _provider.GetRequiredService()); + _context = new Context(_scope.ServiceProvider) { Id = _duplicate }; + await _middleware.InvokeAsync(_context, static _ => default); + } + + [Benchmark(Baseline = true)] + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + public async ValueTask NativeInsert() + { + var id = Guid.Parse(Duplicate ? _duplicate : Guid.CreateVersion7().ToString("D")); + var transaction = await _db.Database.BeginTransactionAsync().ConfigureAwait(false); + try + { + await using var command = new NpgsqlCommand(_insert, (NpgsqlConnection)_db.Database.GetDbConnection(), + (NpgsqlTransaction)transaction.GetDbTransaction()); + command.Parameters.Add(new NpgsqlParameter("consumer", "benchmark")); + command.Parameters.Add(new NpgsqlParameter("id", id)); + await command.ExecuteNonQueryAsync().ConfigureAwait(false); + await transaction.CommitAsync().ConfigureAwait(false); + } + finally { await transaction.DisposeAsync().ConfigureAwait(false); } + } + + [Benchmark] + public ValueTask RelayerInbox() + { + _context.Id = Duplicate ? _duplicate : Guid.CreateVersion7().ToString("D"); + return _middleware.InvokeAsync(_context, static _ => default); + } + + [GlobalCleanup] + public async Task Cleanup() + { + await using (var drop = new NpgsqlCommand($"DROP SCHEMA {PostgreSqlOutboxSchema.QuoteIdentifier(_schema)} CASCADE", + (NpgsqlConnection)_db.Database.GetDbConnection())) + await drop.ExecuteNonQueryAsync(); + await new AsyncServiceScope(_scope).DisposeAsync(); + await _provider.DisposeAsync(); + } + + private sealed class Context(IServiceProvider services) : MessageContext + { + internal string Id { get; set; } = ""; + public override string MessageId => Id; + public override MessageType MessageType => new("benchmark", 1); + public override MessageHeaders Headers => MessageHeaders.Empty; + public override int Attempt => 1; + public override IServiceProvider Services => services; + public override MessageFeatures Features { get; } = new(); + public override CancellationToken CancellationToken => default; + } +} diff --git a/docs/decisions.md b/docs/decisions.md index fa6d039bd..587e308eb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -642,3 +642,24 @@ against the previous unbounded lookup; their raw results remain outside the repo **Alternatives rejected.** Transport-only keys lose endpoint-specific limits. LRU adds maintenance to every hit. Clearing the entire cache discards unrelated hot entries at once. A public cache setting adds configuration surface before evidence shows applications need one. + +## D36. An explicit EF Core consumer boundary owns the inbox transaction + +**Context.** The inbox key must be durable in the same transaction as business data and outgoing rows. +Inspecting handler dependencies would introduce hidden conventions and cannot identify one owner when +several DbContexts share a scope. A preflight existence query alone races with concurrent deliveries. + +**Decision.** `ConsumePipelineBuilder.EntityFrameworkCore(consumer)` explicitly selects the +scoped context and owns a transaction around the handler and all inner middleware. Install it first. +The inbox is automatic when that context has outbox interceptors; without them it is opt-in per +consumer. Schema and prefix follow the outbox context's scoped configuration. PostgreSQL's unique +`(consumer, message_id)` key and `INSERT ... ON CONFLICT DO NOTHING` serialize concurrent duplicates. +An insert that loses to a committed row skips the handler, records a duplicate metric and permits +normal native settlement. A rollback lets the waiting delivery process the original UUIDv7 identity. + +**Consequences.** Handler saves do not commit the unit. Exceptions, cancellation and non-complete +settlement requests roll back business data, inbox and outgoing rows before ordinary failure handling. +Successful handling commits before scope disposal and native settlement. Native acknowledgement loss +therefore redelivers safely. Retrying EF strategies, pooled contexts, ambient transactions and batch +consumers are rejected; Relayer retries with fresh scopes instead. Handlers must not end the owned +transaction or perform native settlement. Inbox retention remains separate work. diff --git a/docs/design.md b/docs/design.md index 4253058e0..17de88550 100644 --- a/docs/design.md +++ b/docs/design.md @@ -527,6 +527,13 @@ After dispatch, rows are deleted in batches. One leased **cleanup** job handles - A duplicate delivery is acknowledged without invoking the handler, and a metric is recorded. - The inbox is opt-in per consumer. It is enabled automatically when the outbox is used on the same DbContext. +The implemented PostgreSQL EF Core consumer boundary explicitly selects its scoped DbContext at +composition time, validates its provider and owns the transaction around the complete handler attempt. +It inserts the inbox key before dispatch with `ON CONFLICT DO NOTHING`; the database unique constraint +coordinates overlapping instances and permits a waiting delivery to run if the first rolls back. +Outbox configuration on the selected context enables inbox deduplication automatically (D32). +See [consumer configuration and failure boundaries](https://relayer.tomlonghurst.dev/docs/reference/ef-core-inbox). + ### 6.6 Multi-tenancy - `IOutboxStoreResolver` maps the current tenant to a connection or DbContext, supporting a database per tenant or a schema per tenant (CAP #699, Rebus #1218, Wolverine #556). diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs new file mode 100644 index 000000000..dfb00a486 --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs @@ -0,0 +1,62 @@ +using System.Runtime.CompilerServices; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; + +namespace Relayer.Outbox.EntityFrameworkCore; + +internal sealed class EntityFrameworkCoreConsumer(string consumer, bool inbox, bool outbox, + OutboxConfiguration configuration, RelayerInstrumentation instrumentation) : IConsumeTransactionMiddleware where TContext : DbContext +{ + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) + { + var cancellation = context.CancellationToken; + var messageId = inbox ? ParseMessageId(context.MessageId) : default; + var db = context.Services.GetRequiredService(); + if (db.Database.CurrentTransaction is not null || System.Transactions.Transaction.Current is not null) + throw new InvalidOperationException("The EF Core consumer must own its transaction. Do not nest database consumer middleware or use an ambient transaction."); + var transaction = await db.Database.BeginTransactionAsync(cancellation).ConfigureAwait(false); + try + { + if (inbox) + { + // An outbox context can bind reloaded options in a new scope. Its interceptor has registered + // the exact configuration with this transaction; never write the inbox to a different schema. + var current = outbox ? context.Services.GetRequiredService().Get(db, configuration).Configuration : configuration; + await using var command = new NpgsqlCommand(current.InboxInsertSql, + (NpgsqlConnection)db.Database.GetDbConnection(), (NpgsqlTransaction)transaction.GetDbTransaction()); + command.Parameters.Add(new NpgsqlParameter("consumer", consumer)); + command.Parameters.Add(new NpgsqlParameter("id", messageId)); + // The unique key waits for an overlapping transaction. A rollback lets this insert succeed. + if (await command.ExecuteNonQueryAsync(cancellation).ConfigureAwait(false) == 0) + { + await transaction.CommitAsync(cancellation).ConfigureAwait(false); + instrumentation.RecordInboxDuplicate(consumer); + return; + } + } + await next(context).ConfigureAwait(false); + if (!ReferenceEquals(db.Database.CurrentTransaction, transaction)) + throw new InvalidOperationException("The handler ended or replaced the consumer transaction. Save changes in the handler and let Relayer commit."); + var disposition = context.Features.Get()?.RequestedDisposition; + if (disposition is { Kind: not DispositionKind.Complete }) + await transaction.RollbackAsync(cancellation).ConfigureAwait(false); + else + await transaction.CommitAsync(cancellation).ConfigureAwait(false); + } + finally + { + // Disposal rolls back on every exception and cancellation path before failure handling runs. + await transaction.DisposeAsync().ConfigureAwait(false); + } + } + + internal static Guid ParseMessageId(string messageId) + { + if (!Guid.TryParse(messageId, out var id) || id == Guid.Empty || id.Version != 7) + throw new MessageEnvelopeException("Inbox processing requires the original non-empty UUIDv7 message ID."); + return id; + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs new file mode 100644 index 000000000..1a44279b9 --- /dev/null +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Relayer.Outbox.EntityFrameworkCore; + +/// Configures a consumer's explicit database unit of work. +public static class EntityFrameworkCoreConsumerExtensions +{ + /// Wraps handling in one PostgreSQL transaction. Inbox is automatic with AddRelayerOutbox, otherwise opt in. + /// + /// Register first, before other middleware. Handlers save changes but must not commit, roll back or replace this transaction. + /// Use a stable consumer identity across replicas and restarts. Batch consumers are not supported. + /// + public static ConsumePipelineBuilder EntityFrameworkCore(this ConsumePipelineBuilder builder, + string consumer, bool inbox = false, EntityFrameworkCoreOutboxOptions? options = null) where TContext : DbContext + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentException.ThrowIfNullOrWhiteSpace(consumer); + return builder.Use(services => + { + var context = services.GetRequiredService(); + if (context.Database.ProviderName != "Npgsql.EntityFrameworkCore.PostgreSQL") + throw new InvalidOperationException("EF Core consumers currently require the Npgsql PostgreSQL provider."); + if (context.Database.CreateExecutionStrategy().RetriesOnFailure) + throw new InvalidOperationException("EF Core consumers require retries of the complete handler in a fresh DI scope. Disable EnableRetryOnFailure and configure Relayer consumer retries."); + var core = context.GetService().FindExtension(); + if (core?.MaxPoolSize is not null) + throw new InvalidOperationException("EF Core consumers require scoped DbContexts. Use AddDbContext instead of AddDbContextPool."); + OutboxConfiguration? outbox = null; + if (core?.Interceptors is { } interceptors) + foreach (var interceptor in interceptors) + if (interceptor is OutboxSaveChangesInterceptor save) outbox = save.Configuration; + if (outbox is not null && options is not null) + throw new InvalidOperationException("Configure schema and prefix on AddRelayerOutbox; the consumer inbox uses that same configuration."); + var configuration = outbox ?? new OutboxConfiguration(options ?? new()); + return new EntityFrameworkCoreConsumer(consumer, inbox || outbox is not null, outbox is not null, + configuration, services.GetRequiredService()); + }); + } +} diff --git a/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs b/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs index 72c43a47b..ceb967bbc 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs +++ b/src/Relayer.Outbox.EntityFrameworkCore/OutboxConfiguration.cs @@ -8,6 +8,7 @@ internal sealed class OutboxConfiguration internal int Lanes { get; } internal string InsertSql { get; } internal PostgreSqlDirectDispatcher? Dispatcher { get; } + internal string InboxInsertSql { get; } internal OutboxConfiguration(EntityFrameworkCoreOutboxOptions options, PostgreSqlDirectDispatcher? dispatcher = null) { @@ -20,6 +21,9 @@ internal OutboxConfiguration(EntityFrameworkCoreOutboxOptions options, PostgreSq if (options.DispatchStoreName is not null) ArgumentException.ThrowIfNullOrWhiteSpace(options.DispatchStoreName); dispatcher?.ValidateStore(options.Schema, options.TablePrefix); Dispatcher = dispatcher; + var inbox = PostgreSqlOutboxSchema.QuoteIdentifier(options.Schema ?? "public") + "." + + PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "inbox"); + InboxInsertSql = $"INSERT INTO {inbox} (consumer, message_id, processed_at) VALUES (@consumer, @id, clock_timestamp()) ON CONFLICT (consumer, message_id) DO NOTHING"; InsertSql = PostgreSqlOutboxBatch.CreateInsertSql(Table); } } diff --git a/src/Relayer/Failures/Failures.cs b/src/Relayer/Failures/Failures.cs index 25b7fe890..957e7fffb 100644 --- a/src/Relayer/Failures/Failures.cs +++ b/src/Relayer/Failures/Failures.cs @@ -28,6 +28,9 @@ public interface IFailureClassifier /// public interface ISettlementFeature { + /// The requested outcome, or null when handling has not requested settlement. + Disposition? RequestedDisposition { get; } + /// Requests completion after successful handling and durable sends. void Complete(); diff --git a/src/Relayer/Failures/PendingSettlement.cs b/src/Relayer/Failures/PendingSettlement.cs index c5940532b..7d0f4650d 100644 --- a/src/Relayer/Failures/PendingSettlement.cs +++ b/src/Relayer/Failures/PendingSettlement.cs @@ -4,6 +4,7 @@ namespace Relayer; internal sealed class PendingSettlement(DefaultMessageContext context, ConsumePipeline owner) : ISettlementFeature { internal Disposition? Request { get; private set; } + public Disposition? RequestedDisposition => Request; public void Complete() => Set(Disposition.Complete); public void Retry(TimeSpan delay) => Set(Disposition.Redeliver(delay)); diff --git a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs index c4d5f77b2..438deb39b 100644 --- a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs +++ b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs @@ -101,10 +101,22 @@ public ConsumePipelineBuilder Use(IConsumeMiddleware middleware) { EnsureMutable(); ArgumentNullException.ThrowIfNull(middleware); + if (middleware is IConsumeTransactionMiddleware && _middleware.Count != 0) + throw new InvalidOperationException("Register the consumer transaction boundary once, before other middleware."); _middleware.Add(middleware); return this; } + /// Creates concurrent middleware in a temporary synchronous startup scope. Do not retain scoped services. + /// Services resolved by the factory must support synchronous disposal. + public ConsumePipelineBuilder Use(Func factory) + { + EnsureMutable(); + ArgumentNullException.ThrowIfNull(factory); + using var scope = _scopes.CreateScope(); + return Use(factory(scope.ServiceProvider)); + } + /// Attaches this endpoint's process metrics and generated failure logging. public ConsumePipelineBuilder Telemetry(EndpointTelemetry telemetry) { diff --git a/src/Relayer/Pipeline/Middleware.cs b/src/Relayer/Pipeline/Middleware.cs index f525508f3..c82e6df14 100644 --- a/src/Relayer/Pipeline/Middleware.cs +++ b/src/Relayer/Pipeline/Middleware.cs @@ -10,6 +10,9 @@ public interface IConsumeMiddleware ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next); } +/// A database transaction boundary. Register exactly once, before other consume middleware. +public interface IConsumeTransactionMiddleware : IConsumeMiddleware; + /// A step in the send pipeline. public delegate ValueTask SendDelegate(SendContext context); diff --git a/src/Relayer/Telemetry/RelayerInstrumentation.cs b/src/Relayer/Telemetry/RelayerInstrumentation.cs index 85f32bf6f..d3feb818b 100644 --- a/src/Relayer/Telemetry/RelayerInstrumentation.cs +++ b/src/Relayer/Telemetry/RelayerInstrumentation.cs @@ -62,6 +62,10 @@ public EndpointTelemetry CreateEndpoint(EndpointTelemetryOptions options) return new(this, options, _logger); } + /// Counts a suppressed duplicate for a stable, application-declared consumer identity. + public void RecordInboxDuplicate(string consumer) + => Duplicates.Add(1, new KeyValuePair("relayer.consumer", consumer)); + /// Stops publishing every instrument owned by this instance. public void Dispose() => _meter.Dispose(); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs new file mode 100644 index 000000000..a8a309616 --- /dev/null +++ b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs @@ -0,0 +1,393 @@ +using System.Buffers; +using System.Diagnostics.Metrics; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Relayer.Outbox.EntityFrameworkCore; +using Relayer.Serialization; +using Relayer.Transports; + +namespace Relayer.Outbox.PostgreSql.Tests; + +public class InboxTests +{ + [Test] + public async Task Redelivery_skips_handler_and_records_metric_after_atomic_commit() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: true); + var control = provider.GetRequiredService(); + control.AfterSave = async context => + { + await Assert.That(context.Services.GetRequiredService().Database.CurrentTransaction).IsNotNull(); + await Assert.That(await database.Orders()).IsEqualTo(0L); + await Assert.That(await database.Count("inbox")).IsEqualTo(0L); + await Assert.That(await database.Count("outbox")).IsEqualTo(0L); + context.Features.GetRequired().Complete(); + }; + var instrumentation = provider.GetRequiredService(); + long duplicates = 0; + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, meter) => + { + if (instrument.Name == "relayer.inbox.duplicates" && ReferenceEquals(instrument.Meter.Scope, instrumentation)) + meter.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, count, tags, _) => + { + foreach (var tag in tags) + if (tag.Key == "relayer.consumer" && Equals(tag.Value, "orders")) Interlocked.Add(ref duplicates, count); + }); + listener.Start(); + var settlements = 0; + var pipeline = Pipeline(provider).Settle(async _ => + { + await Assert.That(await database.Count("inbox")).IsEqualTo(1L); + await Assert.That(await database.Count("outbox")).IsEqualTo(1L); + await Assert.That(await database.Orders()).IsEqualTo(1L); + settlements++; + }).Build(); + var message = Message(); + await Deliver(pipeline, message); + await Deliver(pipeline, message); + await Assert.That(control.Invocations).IsEqualTo(1); + await Assert.That(duplicates).IsEqualTo(1L); + await Assert.That(settlements).IsEqualTo(2); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + + [Test] + [Arguments(false, false, 2)] + [Arguments(false, true, 1)] + [Arguments(true, false, 1)] + public async Task Inbox_is_opt_in_without_outbox_and_automatic_with_same_context(bool outbox, bool inbox, int calls) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox); + var control = provider.GetRequiredService(); + var pipeline = Pipeline(provider, inbox: inbox).Build(); + var message = Message(); + await Deliver(pipeline, message); + await Deliver(pipeline, message); + await Assert.That(control.Invocations).IsEqualTo(calls); + await Assert.That(await database.Count("inbox")).IsEqualTo(calls == 1 ? 1L : 0L); + } + + [Test] + public async Task Identity_is_scoped_by_consumer_and_other_context_outbox_does_not_enable_inbox() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: false); + var message = Message(); + await Deliver(Pipeline(provider, "first", inbox: true).Build(), message); + await Deliver(Pipeline(provider, "second", inbox: true).Build(), message); + await Assert.That(await database.Count("inbox")).IsEqualTo(2L); + await Assert.That(provider.GetRequiredService().Invocations).IsEqualTo(2); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Concurrent_redelivery_waits_for_commit_or_runs_after_rollback(bool rollback) + { + await using var database = new Database(); + await database.Start(); + await using var firstProvider = database.Services(outbox: true); + await using var secondProvider = database.Services(outbox: true); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + firstProvider.GetRequiredService().AfterSave = async _ => + { + entered.SetResult(); + await release.Task; + if (rollback) throw new InvalidOperationException("Roll back first delivery."); + }; + var message = Message(); + var first = Deliver(Pipeline(firstProvider).Build(), message); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(20)); + var second = Deliver(Pipeline(secondProvider).Build(), message); + try + { + // Observe PostgreSQL's lock wait, rather than guessing from elapsed time or scheduling. + await database.WaitForInboxLock(); + await Assert.That(secondProvider.GetRequiredService().Invocations).IsEqualTo(0); + } + finally { release.TrySetResult(); } + if (rollback) await Assert.That(async () => await first).Throws(); + else await first; + await second; + await Assert.That(secondProvider.GetRequiredService().Invocations).IsEqualTo(rollback ? 1 : 0); + await Assert.That(await database.Count("inbox")).IsEqualTo(1L); + await Assert.That(await database.Count("outbox")).IsEqualTo(1L); + await Assert.That(await database.Orders()).IsEqualTo(1L); + } + + [Test] + [Arguments("handler")] + [Arguments("cancel")] + [Arguments("outbox")] + [Arguments("retry")] + [Arguments("deadletter")] + public async Task Failed_or_noncomplete_work_rolls_back_and_redelivery_runs_handler(string failure) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: true); + var control = provider.GetRequiredService(); + using var cancellation = new CancellationTokenSource(); + control.AfterSave = context => + { + switch (failure) + { + case "handler": throw new InvalidOperationException("Handler failed after save."); + case "cancel": cancellation.Cancel(); break; + case "retry": context.Features.GetRequired().Retry(TimeSpan.Zero); break; + case "deadletter": context.Features.GetRequired().DeadLetter("Rejected"); break; + } + return default; + }; + if (failure == "outbox") + await database.Execute("ALTER TABLE \"Case\"\"Inbox\".\"test_outbox\" ADD CONSTRAINT reject_rows CHECK (false)"); + var settled = 0; + var pipeline = Pipeline(provider).Settle(_ => { settled++; return default; }).Build(); + var message = Message(); + if (failure is "retry" or "deadletter") await Deliver(pipeline, message); + else if (failure == "cancel") + await Assert.That(async () => await Deliver(pipeline, message, cancellation.Token)).Throws(); + else if (failure == "outbox") + await Assert.That(async () => await Deliver(pipeline, message)).Throws(); + else await Assert.That(async () => await Deliver(pipeline, message)).Throws(); + await Assert.That(settled).IsEqualTo(failure is "retry" or "deadletter" ? 1 : 0); + await Assert.That(await database.Count("inbox")).IsEqualTo(0L); + await Assert.That(await database.Count("outbox")).IsEqualTo(0L); + await Assert.That(await database.Orders()).IsEqualTo(0L); + if (failure == "outbox") await database.Execute("ALTER TABLE \"Case\"\"Inbox\".\"test_outbox\" DROP CONSTRAINT reject_rows"); + control.AfterSave = null; + await Deliver(pipeline, message); + await Assert.That(control.Invocations).IsEqualTo(2); + await Assert.That(await database.Count("inbox")).IsEqualTo(1L); + await Assert.That(await database.Count("outbox")).IsEqualTo(1L); + await Assert.That(await database.Orders()).IsEqualTo(1L); + } + + [Test] + public async Task Settlement_failure_after_commit_redelivers_without_repeating_work() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: true); + var calls = 0; + var pipeline = Pipeline(provider).Settle(_ => ++calls == 1 + ? ValueTask.FromException(new InvalidOperationException("Lost acknowledgement.")) : default).Build(); + var message = Message(); + await Assert.That(async () => await Deliver(pipeline, message)).Throws(); + await Deliver(pipeline, message); + await Assert.That(provider.GetRequiredService().Invocations).IsEqualTo(1); + await Assert.That(calls).IsEqualTo(2); + } + + [Test] + public async Task Immediate_retry_uses_a_fresh_scope_and_commits_only_the_successful_attempt() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: true); + var scopes = new List(); + provider.GetRequiredService().AfterSave = context => + { + scopes.Add(context.Services); + return context.Attempt == 1 ? ValueTask.FromException(new InvalidOperationException("Retry the entire unit.")) : default; + }; + var failures = new FailurePipeline(provider, "events", "source", "orders", + new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); + var pipeline = Pipeline(provider, failures: failures).Build(); + var message = Message(); + await Deliver(pipeline, message); + await Deliver(pipeline, message); + await Assert.That(scopes.Count).IsEqualTo(2); + await Assert.That(scopes[0]).IsNotSameReferenceAs(scopes[1]); + await Assert.That(await database.Count("inbox")).IsEqualTo(1L); + await Assert.That(await database.Count("outbox")).IsEqualTo(1L); + await Assert.That(await database.Orders()).IsEqualTo(1L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + + [Test] + [Arguments("not-a-guid")] + [Arguments("00000000-0000-0000-0000-000000000000")] + [Arguments("00000000-0000-4000-8000-000000000001")] + public async Task Invalid_identity_fails_before_handler_or_database_write(string id) + { + await using var provider = new Database().Services(outbox: true); + var pipeline = Pipeline(provider).Build(); + await Assert.That(async () => await Deliver(pipeline, Message() with { MessageId = id })).Throws(); + await Assert.That(provider.GetRequiredService().Invocations).IsEqualTo(0); + } + + [Test] + public async Task Retrying_strategy_is_rejected_during_composition() + { + await using var provider = new Database().Services(outbox: true, retries: true); + await Assert.That(() => Pipeline(provider)).Throws(); + } + + [Test] + public async Task Inbox_follows_the_outbox_context_configuration_of_each_delivery_scope() + { + await using var database = new Database(); + await database.Start(); + var options = Database.Options; + await using var provider = database.Services(outbox: true, contextOptions: () => options); + var pipeline = Pipeline(provider).Build(); + options = new() { Schema = Database.Options.Schema, TablePrefix = "reloaded_" }; + await database.Execute(PostgreSqlOutboxSchema.CreateScript(new() { Schema = options.Schema, TablePrefix = options.TablePrefix })); + var message = Message(); + await Deliver(pipeline, message); + await Deliver(pipeline, message); + await Assert.That(await database.Count("inbox")).IsEqualTo(0L); + await Assert.That(await database.Count("outbox")).IsEqualTo(0L); + await Assert.That(await database.Scalar("SELECT count(*) FROM \"Case\"\"Inbox\".reloaded_inbox")).IsEqualTo(1L); + await Assert.That(await database.Scalar("SELECT count(*) FROM \"Case\"\"Inbox\".reloaded_outbox")).IsEqualTo(1L); + await Assert.That(provider.GetRequiredService().Invocations).IsEqualTo(1); + } + + private static ConsumePipelineBuilder Pipeline(ServiceProvider provider, string consumer = "orders", bool inbox = false, + FailurePipeline? failures = null) + { + var scopes = provider.GetRequiredService(); + var messages = provider.GetRequiredService(); + var builder = failures is null + ? new ConsumePipelineBuilder(scopes, messages, new Serializer(), static (_, error, _) => ValueTask.FromException(error)) + : new ConsumePipelineBuilder(scopes, messages, new Serializer(), failures); + return builder.Handler(provider.GetRequiredService().GetHandler()) + .EntityFrameworkCore(consumer, inbox, inbox ? Database.Options : null); + } + + private static ConsumeMessage Message() => new() + { + MessageType = new("inbox.probe", 1), MessageId = Guid.CreateVersion7().ToString("D"), Body = new ReadOnlySequence(new byte[] { 1 }) + }; + + private static async Task Deliver(ConsumePipeline pipeline, ConsumeMessage message, CancellationToken cancellation = default) + { + using var context = pipeline.RentContext(message, cancellation); + await pipeline.ProcessAsync(context); + } + + public sealed class Control + { + public int Invocations; + public bool Outbox; + public Func? AfterSave; + } + + public sealed class Handler(OrdersContext db, ISender sender, Control control) : IHandler + { + public async ValueTask HandleAsync(Probe message, MessageContext context, CancellationToken cancellationToken) + { + var call = Interlocked.Increment(ref control.Invocations); + db.Add(new Order { Id = Guid.CreateVersion7() }); + if (control.Outbox) await sender.SendAsync(new Probe(call), cancellationToken); + await db.SaveChangesAsync(cancellationToken); + if (control.AfterSave is { } after) await after(context); + } + } + + 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 OtherContext(DbContextOptions options) : DbContext(options); + public sealed class Order { public Guid Id { get; set; } } + [Message("inbox.probe")] + public sealed record Probe(int 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] = 1; destination.Advance(1); } + public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)new Probe(1); + } + private sealed class Transport : ITransport + { + public int Sends; + public string Name => "events"; + public TransportCapabilities GetCapabilities(string endpoint) => new() { DeadLetter = true }; + public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) { Interlocked.Increment(ref 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; + } + + private sealed class Database : IAsyncDisposable + { + internal static EntityFrameworkCoreOutboxOptions Options => new() { Schema = "Case\"Inbox", TablePrefix = "test_" }; + private readonly PostgreSqlFixture _fixture = new(); + internal async Task Start() + { + await _fixture.StartAsync(); + await Execute(PostgreSqlOutboxSchema.CreateScript(new() { Schema = Options.Schema, TablePrefix = Options.TablePrefix }) + + "CREATE TABLE orders (\"Id\" uuid PRIMARY KEY)"); + } + internal ServiceProvider Services(bool outbox, bool retries = false, Func? contextOptions = null) + { + var services = new ServiceCollection(); + services.AddSingleton(new Control { Outbox = outbox }); + services.AddSingleton(); + services.AddSingleton(static sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddRelayerEntityFrameworkCoreOutbox(); + services.AddDbContext((sp, o) => + { + o.UseNpgsql(string.IsNullOrEmpty(_fixture.ConnectionString) ? "Host=unused" : _fixture.ConnectionString, + native => { if (retries) native.EnableRetryOnFailure(); }); + if (outbox) o.AddRelayerOutbox(sp, contextOptions?.Invoke() ?? Options); + }); + // Outbox on another context must not turn on the inbox for OrdersContext. + services.AddDbContext((sp, o) => o.UseNpgsql("Host=unused").AddRelayerOutbox(sp)); + services.AddRelayer(r => + { + r.MessageTypes.Add("inbox.probe"); + r.Handler(); + r.AddTransport("events", t => t.Send("destination")); + }); + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } + internal Task Count(string table) => Scalar($"SELECT count(*) FROM \"Case\"\"Inbox\".\"test_{table}\""); + internal Task Orders() => Scalar("SELECT count(*) FROM orders"); + internal async Task Scalar(string sql) + { + await using var connection = new NpgsqlConnection(_fixture.ConnectionString); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand(sql, connection); + return (long)(await command.ExecuteScalarAsync())!; + } + internal async Task Execute(string sql) + { + await using var connection = new NpgsqlConnection(_fixture.ConnectionString); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand(sql, connection); + await command.ExecuteNonQueryAsync(); + } + internal async Task WaitForInboxLock() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + await using var connection = new NpgsqlConnection(_fixture.ConnectionString); + await connection.OpenAsync(timeout.Token); + while (true) + { + await using var command = new NpgsqlCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %test_inbox%'", connection); + if ((long)(await command.ExecuteScalarAsync(timeout.Token))! > 0) return; + await Task.Delay(10, timeout.Token); + } + } + public ValueTask DisposeAsync() => _fixture.DisposeAsync(); + } +} 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 162faec35..bec0618fd 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj +++ b/tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj @@ -12,6 +12,8 @@ + diff --git a/tests/Relayer.Tests/ConsumePipelineTests.cs b/tests/Relayer.Tests/ConsumePipelineTests.cs index 65597202b..e6b4701d1 100644 --- a/tests/Relayer.Tests/ConsumePipelineTests.cs +++ b/tests/Relayer.Tests/ConsumePipelineTests.cs @@ -7,6 +7,41 @@ namespace Relayer.Tests; public class ConsumePipelineTests { + [Test] + public async Task Middleware_factory_uses_temporary_startup_scope_and_transaction_must_be_first() + { + await using var provider = Provider(); + StartupDependency? startup = null; + var builder = Builder(provider).Handler(Descriptor(provider)); + builder.Use(services => + { + startup = services.GetRequiredService(); + return new TransactionMiddleware(); + }); + await Assert.That(startup!.Disposed).IsTrue(); + await Assert.That(() => builder.Use(new TransactionMiddleware())).Throws(); + builder.Use(new Middleware("inner", [], [])); + var pipeline = builder.Build(); + var invoked = false; + await Assert.That(() => builder.Use(_ => { invoked = true; return new TransactionMiddleware(); })).Throws(); + await Assert.That(invoked).IsFalse(); + using var context = pipeline.RentContext(Message()); + await pipeline.ProcessAsync(context); + var other = Builder(provider).Handler(Descriptor(provider)).Use(new Middleware("outer", [], [])); + await Assert.That(() => other.Use(new TransactionMiddleware())).Throws(); + } + + private sealed class StartupDependency : IDisposable + { + internal bool Disposed { get; private set; } + public void Dispose() => Disposed = true; + } + + private sealed class TransactionMiddleware : IConsumeTransactionMiddleware + { + public ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) => next(context); + } + [Test] public async Task Middleware_wraps_generated_dispatch_in_registration_order_and_scopes_are_fresh() { @@ -288,6 +323,7 @@ public async Task Scope_disposal_failure_propagates_and_does_not_report_successf private static ServiceProvider Provider() { var services = new ServiceCollection(); + services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(new List()); diff --git a/website/docs/reference/ef-core-inbox.md b/website/docs/reference/ef-core-inbox.md new file mode 100644 index 000000000..9b32449c2 --- /dev/null +++ b/website/docs/reference/ef-core-inbox.md @@ -0,0 +1,82 @@ +--- +title: EF Core consumer inbox +description: "Deduplicate deliveries and commit handler changes and outgoing messages in one PostgreSQL transaction." +--- + +`Relayer.Outbox.EntityFrameworkCore` supplies a database boundary for single-message consumers using +the Npgsql EF Core provider. Each handling attempt owns one transaction. An inbox insert claims +`(consumer, message_id)` before the handler runs. The insert, saved business changes and any outgoing +outbox rows commit together after the handler and all inner middleware finish. Native settlement +still runs through the consume pipeline after commit and asynchronous scope disposal. + +Create the [PostgreSQL schema](postgres-schema.md) first. Register an ordinary scoped DbContext and +the [EF Core outbox](ef-core-outbox.md), using the same scoped provider as the handler's `ISender`. +Compose the consumer explicitly at startup: + +```csharp +using Relayer.Outbox.EntityFrameworkCore; + +var pipeline = new ConsumePipelineBuilder(scopeFactory, messageTypes, serializer, failures) + .Handler(handlers.GetHandler()) + .EntityFrameworkCore("orders.billing") + .Use(otherMiddleware) + .Settle(SettleNativeMessageAsync) + .Build(); +``` + +`EntityFrameworkCore` must be the first middleware registration, so the transaction +surrounds all subsequent middleware. The selected context comes from the delivery's DI scope; +no assembly scanning or handler dependency inspection occurs. Its identity is an application-declared +consumer name, distinct from the message type. Keep the name stable across restarts and replicas. +Different consumer names can process the same message independently. + +When that context has `AddRelayerOutbox`, the inbox is enabled automatically and uses that context's +schema and table prefix. Outbox registration on another context does not enable it. `SendAsync` +joins the active transaction; the handler calls `SaveChangesAsync` as usual. Several saves stay in +the same transaction. The middleware commits after the handler returns, including when handling +produces no outgoing messages. No built-in outbox dispatcher is implemented yet. + +## Inbox without an outbox + +For a scoped Npgsql DbContext without `AddRelayerOutbox`, opt in explicitly on that consumer: + +```csharp +builder.EntityFrameworkCore("orders.billing", inbox: true); +``` + +Without `inbox: true`, this declaration still owns the transaction but does not deduplicate. +An optional `EntityFrameworkCoreOutboxOptions` argument selects the schema and prefix for an +inbox-only context. With an outbox, configure those options on `AddRelayerOutbox` instead; its +scoped configuration is authoritative, including configuration reloads for newly created scopes. + +## Redelivery and failure + +The original message ID must be a non-empty UUIDv7. Invalid identities enter normal consume failure +handling before invoking the handler or writing to the database. PostgreSQL's unique constraint +coordinates concurrent instances: a second insert waits for the first transaction. If the first +commits, the duplicate skips the handler and completes normally. If it rolls back, the waiting +delivery inserts its own inbox row and runs the handler. + +Handler errors, failed saves, failed outbox writes and cancellation roll back the transaction before +normal failure handling. A requested `ISettlementFeature.Retry` or `DeadLetter` also rolls back +business changes, inbox and outbox; `Complete` commits. `RequestedDisposition` exposes the pending +request to transaction middleware. An acknowledgement failure after commit leaves durable data +intact, and redelivery skips the handler. Commit failures with an unknown outcome remain safe to +redeliver: the committed inbox row determines whether the handler runs again. + +Each suppressed duplicate records `relayer.inbox.duplicates` on the registered `Relayer` meter, +with the stable consumer name under `relayer.consumer`. Message IDs are never metric dimensions. + +## Boundaries + +Use one database boundary per consumer. The middleware owns transaction completion: handlers must +not commit, roll back, dispose or replace its transaction, use a different database connection for +their durable work, or settle the native message themselves. Save changes in the selected context; +Relayer does not call `SaveChanges` on your behalf. External HTTP calls and direct broker sends are +outside the database transaction and need their own idempotency. + +Context pooling, ambient transactions and batch consumers are unsupported. Composition rejects +pooled contexts, other providers and `EnableRetryOnFailure`. Use Relayer's consumer retry policy so +each retry gets a fresh DI scope and DbContext. Register scoped services for the lifetime of a delivery; +do not share a scope concurrently. Inbox retention and cleanup remain planned; deleting a row ends +its deduplication protection. diff --git a/website/docs/reference/ef-core-outbox.md b/website/docs/reference/ef-core-outbox.md index 0dc43172a..d17d9afd0 100644 --- a/website/docs/reference/ef-core-outbox.md +++ b/website/docs/reference/ef-core-outbox.md @@ -11,147 +11,6 @@ the business data. No `SaveChanges` override or outbox entity mapping is require Enlistment alone persists rows. Enable [unordered direct dispatch](direct-dispatch.md) to send due messages in the background after commit, or register [ordered dispatch and lane leases](ordered-dispatch.md) separately. Register the [PostgreSQL durable store](postgres-store.md) separately for reads, claims and backlog health queries. -Recovery polling, inbox, cleanup and outbox tracing remain planned. -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` do not affect enlistment. Configure ordered worker deadlines -through `PostgreSqlOrderedDispatchOptions`; direct dispatch uses `PostgreSqlDirectDispatchOptions.ClaimDuration`. -Poison-row movement remains planned. - -## 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. +Recovery polling, cleanup and outbox tracing remain planned. +The [EF Core consumer boundary](ef-core-inbox.md) supplies transactional inbox deduplication and +enables it automatically for its selected outbox context. diff --git a/website/docs/reference/outbox-stores.md b/website/docs/reference/outbox-stores.md index e0b7b2e86..1000dd964 100644 --- a/website/docs/reference/outbox-stores.md +++ b/website/docs/reference/outbox-stores.md @@ -9,82 +9,6 @@ are implemented, together with [PostgreSQL durable reads and fenced claims](post and [EF Core transaction enlistment for PostgreSQL](ef-core-outbox.md). [Unordered PostgreSQL direct dispatch](direct-dispatch.md) is available for EF commits. [Ordered PostgreSQL dispatch and lane leases](ordered-dispatch.md) are implemented separately. -Recovery polling and inbox deduplication remain planned. - -## Register a named store - -Use normal keyed DI with an explicit, case-sensitive name. This example assumes an application-supplied -`OrdersOutboxStore` that implements `IOutboxStore`; Relayer does not ship that type: - -```csharp -using Relayer; -using Relayer.HealthChecks; - -services.AddKeyedScoped("orders-store"); -services.AddRelayerOutboxHealthProvider("orders-store"); -services.AddRelayerHealthChecks(new RelayerHealthCheckOptions -{ - OutboxNames = ["orders-store"] -}); -``` - -The optional `Relayer.HealthChecks` package adapts the store's pending count to health thresholds. The core -does not depend on health abstractions. Register stores separately from scoped `IOutboxEnlistment` services: -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, -serialized `OutgoingMessage`, creation time, optional lane, attempt count, last error and optional tenant ID. -Never substitute a CLR type name or generate a new envelope when reading a row. Preserve native header names -and values, the CloudEvents identity and creation context, body, ordering key and delivery time. Reject native -callbacks before transactional writes; callbacks cannot be persisted. - -`ReadPendingAsync(request, destination, cancellationToken)` fills caller-owned `Memory` and returns -the number of rows written. A zero-length buffer returns zero. `OutboxReadRequest` selects one nonnegative lane, -or null for unordered rows, a fixed time instant and an optional exclusive `AfterId`. Results use ascending UUIDv7 -ID order. A cursor bounds a scan; a later sweep must start without a cursor to revisit rows that become eligible. - -Rows are eligible when they are pending, not parked or dead, their `DeliverAt` is null or at most the query time, -and they have no live claim. A claim expires when its expiry is at most the query time. Compare timestamps as -UTC instants. Reads do not claim rows, so the dispatcher must claim again before sending. A read or claim does -not establish ordering: ordered dispatch also needs a lane lease protocol, such as the [PostgreSQL worker](ordered-dispatch.md). - -Providers may reuse payload buffers. Borrowed body, headers and ordering-key memory remain valid until the -next read on that store instance or its disposal. Finish all sends before another read. Callers own the row slots -and clear the slots after use. Store instances need not support concurrent calls. - -## Claims and outcomes - -`OutboxClaim` combines the message ID with a new nonempty fencing token for one attempt. Never reuse a token. -`TryClaimAsync` checks current eligibility atomically and stores the token and expiry. The expiry must be later -than the supplied current time. An absent or ineligible row returns false without mutation. - -`RenewClaimAsync` extends a matching live claim without shortening its expiry. `CompleteAsync` deletes a sent -row. `RecordFailureAsync` increments attempts, persists the error and releases the claim in one operation. -Repeating a failure operation with the released token must not increment attempts again. All three operations -require a matching token and a claim that is still live at the supplied time; otherwise they return false without -mutation. Empty IDs/tokens, invalid claim expiry and null error text are invalid arguments. Poison-row movement -and key parking belong to a separate integration. - -All mutations are atomic and durable before completion. Observe cancellation and propagate database errors. -Cancellation or an error can occur after a database commit; callers must tolerate that uncertainty and -at-least-once delivery. An expired dispatcher cannot update a row reclaimed with a newer token. Fencing database -updates does not undo a broker send, so duplicate delivery after a crash or lost claim remains possible. - -## Eligible backlog - -`GetPendingCountAsync(now, cancellationToken)` uses the same eligibility rules across all lanes without an ID -filter. Count rows, not keys or lanes. Include schedules exactly at `now` and expired claims; exclude future -schedules, live claims and parked/dead rows. Return zero only after a successful query finds no eligible rows. -Return null for an unavailable count and propagate query errors rather than returning zero. - -The [health adapter](../guides/health-checks.md) forwards the query time and cancellation token without changing -the result. Provider implementations must verify these predicates and threshold inputs against real database -fixtures; the core adapter's unit tests do not establish database correctness. +Recovery polling remains planned. +[Inbox deduplication](ef-core-inbox.md) is implemented +through the EF Core consumer boundary, separately from the read/claim store contract. diff --git a/website/docs/reference/postgres-schema.md b/website/docs/reference/postgres-schema.md index db4f3e29b..04fbd95db 100644 --- a/website/docs/reference/postgres-schema.md +++ b/website/docs/reference/postgres-schema.md @@ -5,112 +5,8 @@ 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. +transaction enlistment, dispatch, lease acquisition, poison-row handling or inbox deduplication by itself. Register [EF Core transaction enlistment](ef-core-outbox.md) separately to persist outgoing rows. [Ordered dispatch and lease acquisition](ordered-dispatch.md) and [unordered direct dispatch](direct-dispatch.md) -are implemented separately. Recovery polling, poison-row handling and inbox deduplication remain [planned](../roadmap.md). -SQL Server and MySQL scripts are not implemented. - -## Print SQL - -No NuGet packages are published yet. From a repository checkout, run: - -```shell -dotnet run -c Release --project src/dotnet-relayer -- db script --provider postgres --schema messaging --prefix orders_ -``` - -The packable `dotnet-relayer` tool exposes the same command as `dotnet relayer db script --provider postgres` -after installation. To build and install it locally: - -```shell -dotnet pack src/dotnet-relayer -c Release -o .artifacts/packages -dotnet tool install dotnet-relayer --tool-path .artifacts/tools --add-source .artifacts/packages -``` - -Run `.artifacts/tools/dotnet-relayer db script --provider postgres` to print SQL. The installed tool on `PATH` -also supports `dotnet relayer db script --provider postgres`. SQL goes to stdout; invalid options and unsupported -providers produce stderr and a nonzero exit code without emitting SQL. Apply the output with your normal -PostgreSQL deployment tooling. Use a transaction if the deployment must be atomic. - -For code that manages database deployment directly: - -```csharp -using Relayer.Outbox.PostgreSql; - -var sql = PostgreSqlOutboxSchema.CreateScript(new PostgreSqlOutboxOptions -{ - Schema = "messaging", - TablePrefix = "orders_" -}); -``` - -The defaults are schema `public` and prefix `relayer_`. An empty prefix is allowed. Schema, table and index -names are quoted as PostgreSQL identifiers, including embedded quotes, punctuation and Unicode. Each generated -identifier must fit PostgreSQL's 63 UTF-8 byte limit; invalid names fail before SQL is returned. All deployment -and [store registrations](postgres-store.md) must use the same schema and prefix. - -## Tables and constraints - -- `relayer_outbox` preserves the original UUID, transport, destination, stable message type, serialized headers - and body, creation time, optional ordering key, lane, delivery time and tenant ID. Attempts default to zero; - `last_error` stores failure details. Status defaults to `pending` and permits `pending` or `parked`. -- `relayer_outbox_dead` preserves the message and attempt/error data with a required `failed_at` timestamp. - Dead rows live in this table, outside the eligible backlog. -- `relayer_inbox` uses `(consumer, message_id)` as its primary key and stores `processed_at`. -- `relayer_leases` uses `name` as its primary key and stores `owner` and `expires_at`. - -Lane numbers use PostgreSQL `integer` to match the nonnegative `int` contract. Attempts cannot be negative. -Message IDs and claim tokens cannot be empty UUIDs. A claim token and its expiry must both be null or both be -present. The [PostgreSQL store](postgres-store.md) enforces conditional, live-token updates; columns and constraints alone -do not implement [fencing](outbox-stores.md#claims-and-outcomes). - -The outbox has a partial `(lane, ordering_key, id)` index for parked-key barriers, a partial `(lane, id)` index for `status = 'pending'` and a partial `deliver_at` index for non-null -schedules. The inbox has a `processed_at` retention index. Primary keys create their normal unique indexes. - -Creation uses `IF NOT EXISTS` for schemas, tables and indexes. Running the script again preserves existing data. -It creates missing objects; it does **not** repair incompatible tables or upgrade an older schema. Review existing -definitions before adopting tables with the same names. Future schema changes require explicit migrations. - -## EF Core migration path - -Use a PostgreSQL application migration with the Npgsql EF Core provider. Reference -`Relayer.Outbox.EntityFrameworkCore` and add this call to its `Up` method: - -```csharp -using Relayer.Outbox.EntityFrameworkCore; -using Relayer.Outbox.PostgreSql; - -protected override void Up(MigrationBuilder migrationBuilder) -{ - migrationBuilder.CreateRelayerPostgreSqlSchema(new PostgreSqlOutboxOptions - { - Schema = "messaging", - TablePrefix = "orders_" - }); -} -``` - -The extension adds the same SQL as the CLI to the migration and lets EF own the transaction and migration -history. It rejects other providers. Relayer tables stay outside the application's EF model snapshot, so -no entity mapping, `DbSet`, `EnsureCreated` call or transaction interceptor is required. Keep schema evolution -in explicit SQL migration operations. There is no automatic destructive `Down`: choose a retention policy -before writing a rollback that drops durable messages. Back up durable data before a schema change. - -## Eligible backlog predicate - -A provider's count query across all lanes uses an explicit UTC instant: - -```sql -SELECT count(*) -FROM "public"."relayer_outbox" -WHERE status = 'pending' - AND (deliver_at IS NULL OR deliver_at <= @now) - AND (claim_expires_at IS NULL OR claim_expires_at <= @now); -``` - -Schedules and expired claims exactly at `@now` are included. Future schedules, live claims, parked rows and -rows in the dead table are excluded. The real PostgreSQL tests seed these cases, then verify the health -integration at counts 9, 10, 19 and 20 with thresholds 10 and 20. This fixture validates the schema and predicate; -the [PostgreSQL store](postgres-store.md) implements this predicate in its backlog and claim queries. -[Unordered direct dispatch](direct-dispatch.md) uses these claims after EF commits; -[ordered lane dispatch](ordered-dispatch.md) uses separate lane leases. Recovery polling remains planned. +are implemented separately. Recovery polling and poison-row handling remain [planned](../roadmap.md). +[EF Core consumer inbox](ef-core-inbox.md) implements deduplication using the inbox table. diff --git a/website/docs/reference/postgres-store.md b/website/docs/reference/postgres-store.md index a767d3dae..0e078ac14 100644 --- a/website/docs/reference/postgres-store.md +++ b/website/docs/reference/postgres-store.md @@ -8,61 +8,5 @@ It supplies durable reads, atomic claims, renewal, completion, failure persisten [EF Core transaction enlistment](ef-core-outbox.md) and [ADO.NET/Dapper transactions](postgres-outbox.md) supply atomic enqueue. [Unordered direct dispatch](direct-dispatch.md) can send due rows immediately after an EF commit. [Ordered dispatch with lane leases](ordered-dispatch.md) is available through separate -registration. Recovery polling and inbox deduplication remain planned. - -## Registration - -Apply the schema with your normal deployment tooling first. Keep the schema and prefix identical in deployment -and store registration. The data source belongs to your application; dispose it after its users stop. - -```csharp -using Microsoft.Extensions.DependencyInjection; -using Npgsql; -using Relayer; -using Relayer.HealthChecks; -using Relayer.Outbox.PostgreSql; - -await using var dataSource = NpgsqlDataSource.Create(connectionString); -services.AddRelayerPostgreSqlOutboxStore("orders", dataSource, new PostgreSqlOutboxOptions -{ - Schema = "messaging", - TablePrefix = "orders_" -}); -services.AddRelayerOutboxHealthProvider("orders"); -services.AddRelayerHealthChecks(new RelayerHealthCheckOptions { OutboxNames = ["orders"] }); -``` - -Resolve `IOutboxStore` with `GetRequiredKeyedService("orders")` inside a DI scope. Names are explicit -and case-sensitive. Each scope has its own store. The registration snapshots schema/prefix, validates identifiers, -and does not take ownership of the data source. Health registration requires the optional `Relayer.HealthChecks` package. -Registration does not create tables, enable `IOutboxEnlistment`, or start workers. - -## Reads and mutations - -The store follows the [core contract](outbox-stores.md): - -- Reads select one lane, or unordered rows with a null lane, in ascending PostgreSQL UUID order. They honor the - buffer length and exclusive ID cursor. Body, header bytes, duplicate header names and their order are preserved. -- Reads and counts include due schedules and expired claims exactly at the supplied UTC instant. They exclude - future schedules, parked rows and live claims. Counts span every lane. Dead rows reside in a separate table. -- Claiming uses one conditional `UPDATE`. A competing claim succeeds only after the prior claim expires. -- Renewal uses the greater of the existing and requested expiry. Renewal, completion and failure recording require - the current token and an unexpired claim. Expired or replaced owners return false without mutation. -- Failure recording increments attempts, saves the error and releases the claim atomically. Repeating it with the - released token returns false. Completion deletes only the currently claimed row. - -Use UTC instants consistently. PostgreSQL timestamps have microsecond precision. Await each operation before -starting another on the same store, and finish using borrowed rows before another read. Database errors and -cancellation propagate; they never become an empty backlog. A cancelled mutation might already have committed. -The store does not establish native broker delivery guarantees or ordered lane ownership. - -## Header storage - -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. EF Core interceptors and PostgreSQL outbox transactions -write compatible rows through the shared codec and batch writer. -The store does not generate identities, serialize messages, or rewrite envelopes during reads. +registration. Recovery polling remains planned. +[Inbox deduplication](ef-core-inbox.md) is available through the EF Core consumer boundary. diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md index 53465f347..cbcbc85b2 100644 --- a/website/docs/roadmap.md +++ b/website/docs/roadmap.md @@ -17,30 +17,6 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu - [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. - [Ordered PostgreSQL dispatch and lane leases](reference/ordered-dispatch.md). +- [EF Core consumer inbox](reference/ef-core-inbox.md): PostgreSQL deduplication, concurrent redelivery, atomic business/inbox/outbox commits and duplicate metrics. Automatic for the selected outbox context, opt-in for inbox-only consumers. - [PostgreSQL ADO.NET and Dapper transactions](reference/postgres-outbox.md): scoped enlistment, owned message copies and one atomic batched insert on commit. -- [Unordered PostgreSQL direct dispatch](reference/direct-dispatch.md): background sends immediately after EF commit, fenced claims, native transport batches and fenced batch deletion. Recovery polling, poison-row handling, cleanup and inbox remain planned. -- The consume pipeline and the native receive SPI. -- [Service Bus receive primitives](transports/service-bus-receive.md): the native callback binding and manual settlement view. The complete Service Bus transport remains planned. -- 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. -- Manual settlement requests through `ISettlementFeature`, with exception precedence and durable capability fallbacks. -- Declared topology with validate and provision modes, and JSON export. -- The [in-memory transport](transports/in-memory.md), with native queue and partitioned log semantics. -- The [Kafka adapter](transports/kafka.md), with named producers, serial consumer groups, native batches and checkpoints, durable dead-letter copies, application logging, receive telemetry and Testcontainers conformance. Parallel partition scheduling and health adapters remain planned. -- The packaged [transport conformance suite](transports/conformance.md), passing in-memory queue and log modes, with capability skips and native fixture hooks for third-party adapters. -- The [test harness and standalone handler context](guides/testing.md), with logical send and native dispatch observations, deterministic in-memory idle detection, reset and provider isolation. -- The [performance regression gate](contributing/performance.md), covering end-to-end in-memory send/receive, concurrent delivery, allocation attribution and 100-handler composition. Raw broker comparisons remain planned with each adapter. -- Core tracing primitives, single and batch delivery spans, native settlement wrappers, consume metrics and generated failure logs. Kafka send, serial receive and batch-commit instrumentation are implemented; the other native receive adapters and outbox instrumentation remain planned. -- The optional [health integration](guides/health-checks.md), with connectivity, consumer liveness and backlog checks. The outbox adapter accepts application-provided durable stores; native broker adapters remain planned. - -## Phases - -| Phase | Scope | Exit criteria | -|---|---|---| -| 0 | Core abstractions, pipeline, source generator and analyzers, in-memory transport, test harness, telemetry | Handler round trip under Native AOT; benchmarks in CI | -| 1 | Kafka and Azure Service Bus transports; failure pipeline; DLQ and redrive | Broker-restart and rebalance chaos tests pass | -| 2 | EF Core and PostgreSQL outbox and inbox (lanes, direct dispatch, cleanup) | Crash and duplicate tests with multiple instances pass; at most 5% overhead | -| 3 | SQS/SNS and RabbitMQ; SQL Server and MySQL outbox; topology export; multi-tenancy | Every transport passes the conformance suite | -| 4 | Sagas, request/response, change-data-capture dispatch, more transports | — | - -The [design document](https://github.com/thomhurst/Relayer/blob/main/docs/design.md) describes each planned feature in detail. +- [Unordered PostgreSQL direct dispatch](reference/direct-dispatch.md): background sends immediately after EF commit, fenced claims, native transport batches and fenced batch deletion. Recovery polling, poison-row handling and cleanup remain planned. diff --git a/website/docs/transports/consume-pipeline.md b/website/docs/transports/consume-pipeline.md index 56db2cfc2..e455cdd13 100644 --- a/website/docs/transports/consume-pipeline.md +++ b/website/docs/transports/consume-pipeline.md @@ -8,6 +8,12 @@ handler descriptors and stable identities from `HandlerRegistry` and the frozen `MessageTypeRegistry`. It does not discover CLR types while receiving messages. The first middleware registered with `Use` is outermost; middleware instances are shared by the consumer and must support concurrent calls. +`Use(factory)` can inspect services in a temporary synchronous startup scope to create middleware; +resolved services must support synchronous disposal and the middleware must not retain scoped services. +The [EF Core consumer boundary](../reference/ef-core-inbox.md) +uses this seam to validate its provider and enable inbox deduplication for the selected outbox context. +Middleware implementing `IConsumeTransactionMiddleware` must be registered once, before any other +middleware. Composition rejects another transaction boundary or a boundary placed after middleware. Transport authors can compose and invoke the execution layer as follows: diff --git a/website/sidebars.js b/website/sidebars.js index 0170a520f..19f350622 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -41,12 +41,4 @@ const sidebars = { { type: 'category', label: 'Reference', - items: ['reference/diagnostics', 'reference/outbox-stores', 'reference/postgres-schema', 'reference/postgres-store', 'reference/postgres-outbox', 'reference/ef-core-outbox', 'reference/direct-dispatch', 'reference/ordered-dispatch'], - }, - 'roadmap', - 'contributing/documentation', - 'contributing/performance', - ], -}; - -export default sidebars; + items: ['reference/diagnostics', 'reference/outbox-stores', 'reference/postgres-schema', 'reference/postgres-store', 'reference/postgres-outbox', 'reference/ef-core-outbox', 'reference/direct-dispatch', 'reference/ordered-dispatch', 'reference/ef-core-inbox'], diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 1192802e0..8b7534379 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -107,7 +107,7 @@ function Layers() { ))}
traceparent
-
00-4bf92f35…-00f067aa…-01
+
00-4bf92f35…-00f067aa…-01
@@ -135,7 +135,7 @@ function Hero() { Relayer

- Messaging for .NET that wraps your broker’s own client. Relayer handles retries, dead-lettering, the outbox, + Messaging for .NET that wraps your broker’s own client. Relayer handles retries, dead-lettering, the outbox, tracing and serialization. Kafka, Service Bus, SQS and RabbitMQ keep sending, ordering and settling messages the way they already do.

@@ -294,50 +294,7 @@ const status = [ ['EF Core transaction enlistment for PostgreSQL', 'Implemented enqueue path', true], ['PostgreSQL ADO.NET and Dapper transactions', 'Implemented enqueue path', true], ['Unordered PostgreSQL direct dispatch after EF commit', 'Implemented direct path', true], + ['EF Core consumer inbox for PostgreSQL', 'Implemented deduplication', true], ['Native broker health adapters', 'Planned', false], ['Ordered PostgreSQL dispatch and lane leases', 'Implemented', true], - ['Outbox recovery, cleanup and inbox', 'Planned', false], - ['Send and delivery tracing, settlement, metrics and logs', 'Implemented', true], - ['Native receive and outbox telemetry', 'Planned', false], -]; - -function Status() { - return ( -
-
- - Where it stands - -

- Relayer is built in the open. This is what works on main today. -

- - - {status.map(([area, state, done]) => ( - - - - - ))} - -
{area}{state}
- See the full roadmap -
-
- ); -} - -export default function Home() { - return ( - - -
- - - -
-
- ); -} + ['Outbox recovery and cleanup', 'Planned', false], From f145d6b0d2499daa2bbfca0d91d5cb8a1c1d729a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:48:37 +0000 Subject: [PATCH 2/2] fix: finalize inbox settlement before transaction commit (#35) --- docs/decisions.md | 5 +- docs/design.md | 4 +- .../EntityFrameworkCoreConsumer.cs | 11 ++ .../EntityFrameworkCoreConsumerExtensions.cs | 2 + src/Relayer/Failures/Failures.cs | 1 + .../InboxTests.cs | 49 +++++- website/docs/guides/failure-handling.md | 2 +- website/docs/reference/ef-core-inbox.md | 12 +- website/docs/reference/ef-core-outbox.md | 143 ++++++++++++++++++ website/docs/reference/outbox-stores.md | 78 ++++++++++ website/docs/reference/postgres-outbox.md | 4 +- website/docs/reference/postgres-schema.md | 105 +++++++++++++ website/docs/reference/postgres-store.md | 57 +++++++ website/docs/roadmap.md | 25 +++ website/sidebars.js | 8 + website/src/pages/index.js | 48 +++++- 16 files changed, 545 insertions(+), 9 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 587e308eb..3b752f1af 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -46,6 +46,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D33](#d33-commit-triggered-dispatch-transfers-owned-buffers-to-a-named-worker) | Commit-triggered dispatch transfers owned buffers to a named worker | Accepted | | [D34](#d34-ordered-postgresql-dispatch-drains-a-locked-lane-before-transfer) | Ordered PostgreSQL lane ownership and transfer | Accepted | | [D35](#d35-direct-dispatch-bounds-endpoint-capability-retention) | Direct dispatch bounds endpoint capability retention | Accepted | +| [D36](#d36-an-explicit-ef-core-consumer-boundary-owns-the-inbox-transaction) | An explicit EF Core consumer boundary owns the inbox transaction | Accepted | --- @@ -659,7 +660,9 @@ normal native settlement. A rollback lets the waiting delivery process the origi **Consequences.** Handler saves do not commit the unit. Exceptions, cancellation and non-complete settlement requests roll back business data, inbox and outgoing rows before ordinary failure handling. -Successful handling commits before scope disposal and native settlement. Native acknowledgement loss +Successful handling requests completion if no outcome is pending, then commits before scope disposal +and native settlement. The one-request rule rejects any later settlement request, so disposal cannot +retry or dead-letter work after commit. Native acknowledgement loss therefore redelivers safely. Retrying EF strategies, pooled contexts, ambient transactions and batch consumers are rejected; Relayer retries with fresh scopes instead. Handlers must not end the owned transaction or perform native settlement. Inbox retention remains separate work. diff --git a/docs/design.md b/docs/design.md index 17de88550..3e16a061f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -531,7 +531,9 @@ The implemented PostgreSQL EF Core consumer boundary explicitly selects its scop composition time, validates its provider and owns the transaction around the complete handler attempt. It inserts the inbox key before dispatch with `ON CONFLICT DO NOTHING`; the database unique constraint coordinates overlapping instances and permits a waiting delivery to run if the first rolls back. -Outbox configuration on the selected context enables inbox deduplication automatically (D32). +Outbox configuration on the selected context enables inbox deduplication automatically (D36). +Before commit the boundary requests completion if no settlement outcome is pending. The existing +one-request rule rejects settlement changes during scope disposal after the work is durable. See [consumer configuration and failure boundaries](https://relayer.tomlonghurst.dev/docs/reference/ef-core-inbox). ### 6.6 Multi-tenancy diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs index dfb00a486..f237d5b60 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumer.cs @@ -32,6 +32,7 @@ public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) // The unique key waits for an overlapping transaction. A rollback lets this insert succeed. if (await command.ExecuteNonQueryAsync(cancellation).ConfigureAwait(false) == 0) { + RequestCompletion(context); await transaction.CommitAsync(cancellation).ConfigureAwait(false); instrumentation.RecordInboxDuplicate(consumer); return; @@ -44,7 +45,10 @@ public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) if (disposition is { Kind: not DispositionKind.Complete }) await transaction.RollbackAsync(cancellation).ConfigureAwait(false); else + { + RequestCompletion(context); await transaction.CommitAsync(cancellation).ConfigureAwait(false); + } } finally { @@ -53,6 +57,13 @@ public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next) } } + private static void RequestCompletion(MessageContext context) + { + // Fix the outcome before commit. Scope disposers cannot reject work that is already durable. + if (context.Features.Get() is { RequestedDisposition: null } settlement) + settlement.Complete(); + } + internal static Guid ParseMessageId(string messageId) { if (!Guid.TryParse(messageId, out var id) || id == Guid.Empty || id.Version != 7) diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs index 1a44279b9..9d35ac25f 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreConsumerExtensions.cs @@ -10,6 +10,8 @@ public static class EntityFrameworkCoreConsumerExtensions /// Wraps handling in one PostgreSQL transaction. Inbox is automatic with AddRelayerOutbox, otherwise opt in. /// /// Register first, before other middleware. Handlers save changes but must not commit, roll back or replace this transaction. + /// Request retry or dead-letter before returning from handling. Before commit the boundary requests completion + /// if no outcome is pending; further settlement requests, including during scope disposal, throw. /// Use a stable consumer identity across replicas and restarts. Batch consumers are not supported. /// public static ConsumePipelineBuilder EntityFrameworkCore(this ConsumePipelineBuilder builder, diff --git a/src/Relayer/Failures/Failures.cs b/src/Relayer/Failures/Failures.cs index 957e7fffb..d7c38b11a 100644 --- a/src/Relayer/Failures/Failures.cs +++ b/src/Relayer/Failures/Failures.cs @@ -24,6 +24,7 @@ public interface IFailureClassifier /// /// Get from MessageContext.Features. One request is allowed per attempt. A handler or middleware exception /// overrides the request; cancellation, scope disposal and durable-write failures prevent settlement. +/// Transaction boundaries may request completion before commit; further requests during scope disposal then throw. /// Do not retain this pooled feature beyond processing. Native settlement is deferred until durable work succeeds. /// public interface ISettlementFeature diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs index a8a309616..a9f30d822 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs @@ -189,6 +189,47 @@ public async Task Settlement_failure_after_commit_redelivers_without_repeating_w await Assert.That(calls).IsEqualTo(2); } + [Test] + [Arguments(false, false, "retry")] + [Arguments(false, false, "deadletter")] + [Arguments(false, true, "retry")] + [Arguments(false, true, "deadletter")] + [Arguments(true, false, "retry")] + [Arguments(true, false, "deadletter")] + [Arguments(true, true, "retry")] + [Arguments(true, true, "deadletter")] + public async Task Settlement_requests_during_disposal_cannot_change_a_committed_outcome(bool failures, bool duplicate, string request) + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(outbox: true); + var control = provider.GetRequiredService(); + var failurePipeline = failures ? new FailurePipeline(provider, "events", "source", "orders", new()) : null; + var settled = 0; + var pipeline = Pipeline(provider, failures: failurePipeline).Settle(_ => { settled++; return default; }).Build(); + var message = Message(); + if (duplicate) await Deliver(pipeline, message); + using var context = pipeline.RentContext(message); + control.OnDispose = () => + { + var settlement = context.Features.GetRequired(); + if (request == "retry") settlement.Retry(TimeSpan.Zero); + else settlement.DeadLetter("Rejected during disposal"); + }; + await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws() + .WithMessage("Only one settlement request is allowed per processing attempt."); + control.OnDispose = null; + await Assert.That(settled).IsEqualTo(duplicate ? 1 : 0); + await Assert.That(await database.Count("inbox")).IsEqualTo(1L); + await Assert.That(await database.Count("outbox")).IsEqualTo(1L); + await Assert.That(await database.Orders()).IsEqualTo(1L); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + // A fresh attempt acknowledges the committed duplicate without repeating business work. + await Deliver(pipeline, message); + await Assert.That(control.Invocations).IsEqualTo(1); + await Assert.That(settled).IsEqualTo(duplicate ? 2 : 1); + } + [Test] public async Task Immediate_retry_uses_a_fresh_scope_and_commits_only_the_successful_attempt() { @@ -282,6 +323,7 @@ public sealed class Control public int Invocations; public bool Outbox; public Func? AfterSave; + public Action? OnDispose; } public sealed class Handler(OrdersContext db, ISender sender, Control control) : IHandler @@ -296,9 +338,14 @@ public async ValueTask HandleAsync(Probe message, MessageContext context, Cancel } } - public sealed class OrdersContext(DbContextOptions options) : DbContext(options) + public sealed class OrdersContext(DbContextOptions options, Control control) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("orders").HasKey(x => x.Id); + public override async ValueTask DisposeAsync() + { + await base.DisposeAsync(); + control.OnDispose?.Invoke(); + } } public sealed class OtherContext(DbContextOptions options) : DbContext(options); public sealed class Order { public Guid Id { get; set; } } diff --git a/website/docs/guides/failure-handling.md b/website/docs/guides/failure-handling.md index 61aa82641..33e9c3062 100644 --- a/website/docs/guides/failure-handling.md +++ b/website/docs/guides/failure-handling.md @@ -74,7 +74,7 @@ These calls queue a decision; they do not acknowledge the native delivery inline Requests apply after the handler, consume middleware and async scope disposal succeed. `Complete()` also waits for buffered sends to flush. If the handler or middleware throws after any request, the exception wins: the request is cleared and the normal classification, retry and dead-letter policy runs. Each immediate retry starts without a request. Cancellation, scope-disposal errors, send-flush errors and durable fallback errors propagate without a settlement decision. -With an executable `FailurePipeline`, `Retry` and `DeadLetter` discard buffered direct sends, including sends made during scope disposal. They do not roll back a transaction or undo calls to native clients; the application owns those effects. `Complete` and automatic completion flush successful direct sends as usual. +With an executable `FailurePipeline`, `Retry` and `DeadLetter` discard buffered direct sends, including sends made during scope disposal. The [EF Core consumer boundary](../reference/ef-core-inbox.md) also rolls back its owned transaction for these requests. Without that boundary, the application owns transaction rollback. Calls to native clients remain the application's responsibility. The boundary requests completion before commit when no outcome is pending; further settlement requests during scope disposal throw because the database work is already durable. `Complete` and automatic completion flush successful direct sends as usual. `Retry(delay)` requests a new delivery using the exact delay, without jitter or the configured in-process retry sequence. `FailurePipeline` chooses native redelivery, then a scheduled copy, then a durable scheduler, using the same capability limits and executors as exception handling. A delay without an executor throws at the request call with an actionable message. The request can then be handled by the normal exception policy. Manual dead-lettering uses native dead-lettering or a durable copy. Copies include the requested reason in `FailureHeaders.DeadLetterReason` (`relayer.dead_letter.reason`). Prior exception history is preserved; manual outcomes do not invent an exception. diff --git a/website/docs/reference/ef-core-inbox.md b/website/docs/reference/ef-core-inbox.md index 9b32449c2..34b2cb8d3 100644 --- a/website/docs/reference/ef-core-inbox.md +++ b/website/docs/reference/ef-core-inbox.md @@ -34,7 +34,9 @@ When that context has `AddRelayerOutbox`, the inbox is enabled automatically and schema and table prefix. Outbox registration on another context does not enable it. `SendAsync` joins the active transaction; the handler calls `SaveChangesAsync` as usual. Several saves stay in the same transaction. The middleware commits after the handler returns, including when handling -produces no outgoing messages. No built-in outbox dispatcher is implemented yet. +produces no outgoing messages. To send due unordered rows after commit, configure +[unordered direct dispatch](direct-dispatch.md) on the selected outbox context. Without a dispatcher, +committed rows remain pending. ## Inbox without an outbox @@ -60,7 +62,13 @@ delivery inserts its own inbox row and runs the handler. Handler errors, failed saves, failed outbox writes and cancellation roll back the transaction before normal failure handling. A requested `ISettlementFeature.Retry` or `DeadLetter` also rolls back business changes, inbox and outbox; `Complete` commits. `RequestedDisposition` exposes the pending -request to transaction middleware. An acknowledgement failure after commit leaves durable data +request to transaction middleware; custom `ISettlementFeature` implementations must supply this +property. Make settlement requests before the handler and inner middleware +return. Before committing, the boundary requests `Complete` when no outcome is pending, including +for duplicates. The one-request-per-attempt rule then rejects further requests during scope disposal +with `InvalidOperationException`; disposal cannot retry or dead-letter already committed work. A +disposal error prevents native settlement, and redelivery acknowledges the committed duplicate. +An acknowledgement failure after commit leaves durable data intact, and redelivery skips the handler. Commit failures with an unknown outcome remain safe to redeliver: the committed inbox row determines whether the handler runs again. diff --git a/website/docs/reference/ef-core-outbox.md b/website/docs/reference/ef-core-outbox.md index d17d9afd0..351b927d1 100644 --- a/website/docs/reference/ef-core-outbox.md +++ b/website/docs/reference/ef-core-outbox.md @@ -14,3 +14,146 @@ Register the [PostgreSQL durable store](postgres-store.md) separately for reads, Recovery polling, cleanup and outbox tracing remain planned. The [EF Core consumer boundary](ef-core-inbox.md) supplies transactional inbox deduplication and enables it automatically for its selected outbox context. +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` do not affect enlistment. Configure ordered worker deadlines +through `PostgreSqlOrderedDispatchOptions`; direct dispatch uses `PostgreSqlDirectDispatchOptions.ClaimDuration`. +Poison-row movement remains planned. + +## 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 1000dd964..77f939c40 100644 --- a/website/docs/reference/outbox-stores.md +++ b/website/docs/reference/outbox-stores.md @@ -12,3 +12,81 @@ and [EF Core transaction enlistment for PostgreSQL](ef-core-outbox.md). Recovery polling remains planned. [Inbox deduplication](ef-core-inbox.md) is implemented through the EF Core consumer boundary, separately from the read/claim store contract. + +## Register a named store + +Use normal keyed DI with an explicit, case-sensitive name. This example assumes an application-supplied +`OrdersOutboxStore` that implements `IOutboxStore`; Relayer does not ship that type: + +```csharp +using Relayer; +using Relayer.HealthChecks; + +services.AddKeyedScoped("orders-store"); +services.AddRelayerOutboxHealthProvider("orders-store"); +services.AddRelayerHealthChecks(new RelayerHealthCheckOptions +{ + OutboxNames = ["orders-store"] +}); +``` + +The optional `Relayer.HealthChecks` package adapts the store's pending count to health thresholds. The core +does not depend on health abstractions. Register stores separately from scoped `IOutboxEnlistment` services: +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, +serialized `OutgoingMessage`, creation time, optional lane, attempt count, last error and optional tenant ID. +Never substitute a CLR type name or generate a new envelope when reading a row. Preserve native header names +and values, the CloudEvents identity and creation context, body, ordering key and delivery time. Reject native +callbacks before transactional writes; callbacks cannot be persisted. + +`ReadPendingAsync(request, destination, cancellationToken)` fills caller-owned `Memory` and returns +the number of rows written. A zero-length buffer returns zero. `OutboxReadRequest` selects one nonnegative lane, +or null for unordered rows, a fixed time instant and an optional exclusive `AfterId`. Results use ascending UUIDv7 +ID order. A cursor bounds a scan; a later sweep must start without a cursor to revisit rows that become eligible. + +Rows are eligible when they are pending, not parked or dead, their `DeliverAt` is null or at most the query time, +and they have no live claim. A claim expires when its expiry is at most the query time. Compare timestamps as +UTC instants. Reads do not claim rows, so the dispatcher must claim again before sending. A read or claim does +not establish ordering: ordered dispatch also needs a lane lease protocol, such as the [PostgreSQL worker](ordered-dispatch.md). + +Providers may reuse payload buffers. Borrowed body, headers and ordering-key memory remain valid until the +next read on that store instance or its disposal. Finish all sends before another read. Callers own the row slots +and clear the slots after use. Store instances need not support concurrent calls. + +## Claims and outcomes + +`OutboxClaim` combines the message ID with a new nonempty fencing token for one attempt. Never reuse a token. +`TryClaimAsync` checks current eligibility atomically and stores the token and expiry. The expiry must be later +than the supplied current time. An absent or ineligible row returns false without mutation. + +`RenewClaimAsync` extends a matching live claim without shortening its expiry. `CompleteAsync` deletes a sent +row. `RecordFailureAsync` increments attempts, persists the error and releases the claim in one operation. +Repeating a failure operation with the released token must not increment attempts again. All three operations +require a matching token and a claim that is still live at the supplied time; otherwise they return false without +mutation. Empty IDs/tokens, invalid claim expiry and null error text are invalid arguments. Poison-row movement +and key parking belong to a separate integration. + +All mutations are atomic and durable before completion. Observe cancellation and propagate database errors. +Cancellation or an error can occur after a database commit; callers must tolerate that uncertainty and +at-least-once delivery. An expired dispatcher cannot update a row reclaimed with a newer token. Fencing database +updates does not undo a broker send, so duplicate delivery after a crash or lost claim remains possible. + +## Eligible backlog + +`GetPendingCountAsync(now, cancellationToken)` uses the same eligibility rules across all lanes without an ID +filter. Count rows, not keys or lanes. Include schedules exactly at `now` and expired claims; exclude future +schedules, live claims and parked/dead rows. Return zero only after a successful query finds no eligible rows. +Return null for an unavailable count and propagate query errors rather than returning zero. + +The [health adapter](../guides/health-checks.md) forwards the query time and cancellation token without changing +the result. Provider implementations must verify these predicates and threshold inputs against real database +fixtures; the core adapter's unit tests do not establish database correctness. diff --git a/website/docs/reference/postgres-outbox.md b/website/docs/reference/postgres-outbox.md index 9dbd08c95..5b6a537e1 100644 --- a/website/docs/reference/postgres-outbox.md +++ b/website/docs/reference/postgres-outbox.md @@ -6,7 +6,9 @@ description: "Commit business changes and buffered messages atomically through a `Relayer.Outbox.PostgreSql` registers a scoped `PostgreSqlOutbox` and `IOutboxEnlistment`. Messages sent in its active transaction are copied into owned buffers. `Commit` or `CommitAsync` writes all messages in one PostgreSQL insert, then commits the native transaction containing your business changes. -No broker send occurs on this path. Dispatch workers, lane ownership and inbox deduplication remain planned. +No broker send occurs on this path. ADO.NET commit-triggered dispatch remains planned. +[Ordered PostgreSQL dispatch and lane leases](ordered-dispatch.md) are available through separate registration. +[Inbox deduplication](ef-core-inbox.md) is available through the EF Core consumer boundary. Use [EF Core enlistment](ef-core-outbox.md) instead when EF owns the transaction. ## Registration diff --git a/website/docs/reference/postgres-schema.md b/website/docs/reference/postgres-schema.md index 04fbd95db..34672f038 100644 --- a/website/docs/reference/postgres-schema.md +++ b/website/docs/reference/postgres-schema.md @@ -10,3 +10,108 @@ Register [EF Core transaction enlistment](ef-core-outbox.md) separately to persi [Ordered dispatch and lease acquisition](ordered-dispatch.md) and [unordered direct dispatch](direct-dispatch.md) are implemented separately. Recovery polling and poison-row handling remain [planned](../roadmap.md). [EF Core consumer inbox](ef-core-inbox.md) implements deduplication using the inbox table. +SQL Server and MySQL scripts are not implemented. + +## Print SQL + +No NuGet packages are published yet. From a repository checkout, run: + +```shell +dotnet run -c Release --project src/dotnet-relayer -- db script --provider postgres --schema messaging --prefix orders_ +``` + +The packable `dotnet-relayer` tool exposes the same command as `dotnet relayer db script --provider postgres` +after installation. To build and install it locally: + +```shell +dotnet pack src/dotnet-relayer -c Release -o .artifacts/packages +dotnet tool install dotnet-relayer --tool-path .artifacts/tools --add-source .artifacts/packages +``` + +Run `.artifacts/tools/dotnet-relayer db script --provider postgres` to print SQL. The installed tool on `PATH` +also supports `dotnet relayer db script --provider postgres`. SQL goes to stdout; invalid options and unsupported +providers produce stderr and a nonzero exit code without emitting SQL. Apply the output with your normal +PostgreSQL deployment tooling. Use a transaction if the deployment must be atomic. + +For code that manages database deployment directly: + +```csharp +using Relayer.Outbox.PostgreSql; + +var sql = PostgreSqlOutboxSchema.CreateScript(new PostgreSqlOutboxOptions +{ + Schema = "messaging", + TablePrefix = "orders_" +}); +``` + +The defaults are schema `public` and prefix `relayer_`. An empty prefix is allowed. Schema, table and index +names are quoted as PostgreSQL identifiers, including embedded quotes, punctuation and Unicode. Each generated +identifier must fit PostgreSQL's 63 UTF-8 byte limit; invalid names fail before SQL is returned. All deployment +and [store registrations](postgres-store.md) must use the same schema and prefix. + +## Tables and constraints + +- `relayer_outbox` preserves the original UUID, transport, destination, stable message type, serialized headers + and body, creation time, optional ordering key, lane, delivery time and tenant ID. Attempts default to zero; + `last_error` stores failure details. Status defaults to `pending` and permits `pending` or `parked`. +- `relayer_outbox_dead` preserves the message and attempt/error data with a required `failed_at` timestamp. + Dead rows live in this table, outside the eligible backlog. +- `relayer_inbox` uses `(consumer, message_id)` as its primary key and stores `processed_at`. +- `relayer_leases` uses `name` as its primary key and stores `owner` and `expires_at`. + +Lane numbers use PostgreSQL `integer` to match the nonnegative `int` contract. Attempts cannot be negative. +Message IDs and claim tokens cannot be empty UUIDs. A claim token and its expiry must both be null or both be +present. The [PostgreSQL store](postgres-store.md) enforces conditional, live-token updates; columns and constraints alone +do not implement [fencing](outbox-stores.md#claims-and-outcomes). + +The outbox has a partial `(lane, ordering_key, id)` index for parked-key barriers, a partial `(lane, id)` index for `status = 'pending'` and a partial `deliver_at` index for non-null +schedules. The inbox has a `processed_at` retention index. Primary keys create their normal unique indexes. + +Creation uses `IF NOT EXISTS` for schemas, tables and indexes. Running the script again preserves existing data. +It creates missing objects; it does **not** repair incompatible tables or upgrade an older schema. Review existing +definitions before adopting tables with the same names. Future schema changes require explicit migrations. + +## EF Core migration path + +Use a PostgreSQL application migration with the Npgsql EF Core provider. Reference +`Relayer.Outbox.EntityFrameworkCore` and add this call to its `Up` method: + +```csharp +using Relayer.Outbox.EntityFrameworkCore; +using Relayer.Outbox.PostgreSql; + +protected override void Up(MigrationBuilder migrationBuilder) +{ + migrationBuilder.CreateRelayerPostgreSqlSchema(new PostgreSqlOutboxOptions + { + Schema = "messaging", + TablePrefix = "orders_" + }); +} +``` + +The extension adds the same SQL as the CLI to the migration and lets EF own the transaction and migration +history. It rejects other providers. Relayer tables stay outside the application's EF model snapshot, so +no entity mapping, `DbSet`, `EnsureCreated` call or transaction interceptor is required. Keep schema evolution +in explicit SQL migration operations. There is no automatic destructive `Down`: choose a retention policy +before writing a rollback that drops durable messages. Back up durable data before a schema change. + +## Eligible backlog predicate + +A provider's count query across all lanes uses an explicit UTC instant: + +```sql +SELECT count(*) +FROM "public"."relayer_outbox" +WHERE status = 'pending' + AND (deliver_at IS NULL OR deliver_at <= @now) + AND (claim_expires_at IS NULL OR claim_expires_at <= @now); +``` + +Schedules and expired claims exactly at `@now` are included. Future schedules, live claims, parked rows and +rows in the dead table are excluded. The real PostgreSQL tests seed these cases, then verify the health +integration at counts 9, 10, 19 and 20 with thresholds 10 and 20. This fixture validates the schema and predicate; +the [PostgreSQL store](postgres-store.md) implements this predicate in its backlog and claim queries. +[Unordered direct dispatch](direct-dispatch.md) uses these claims after EF commits; +[ordered lane dispatch](ordered-dispatch.md) uses separate lane leases. Recovery polling remains planned. diff --git a/website/docs/reference/postgres-store.md b/website/docs/reference/postgres-store.md index 0e078ac14..b33b54d33 100644 --- a/website/docs/reference/postgres-store.md +++ b/website/docs/reference/postgres-store.md @@ -10,3 +10,60 @@ supply atomic enqueue. [Unordered direct dispatch](direct-dispatch.md) can send an EF commit. [Ordered dispatch with lane leases](ordered-dispatch.md) is available through separate registration. Recovery polling remains planned. [Inbox deduplication](ef-core-inbox.md) is available through the EF Core consumer boundary. + +## Registration + +Apply the schema with your normal deployment tooling first. Keep the schema and prefix identical in deployment +and store registration. The data source belongs to your application; dispose it after its users stop. + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Relayer; +using Relayer.HealthChecks; +using Relayer.Outbox.PostgreSql; + +await using var dataSource = NpgsqlDataSource.Create(connectionString); +services.AddRelayerPostgreSqlOutboxStore("orders", dataSource, new PostgreSqlOutboxOptions +{ + Schema = "messaging", + TablePrefix = "orders_" +}); +services.AddRelayerOutboxHealthProvider("orders"); +services.AddRelayerHealthChecks(new RelayerHealthCheckOptions { OutboxNames = ["orders"] }); +``` + +Resolve `IOutboxStore` with `GetRequiredKeyedService("orders")` inside a DI scope. Names are explicit +and case-sensitive. Each scope has its own store. The registration snapshots schema/prefix, validates identifiers, +and does not take ownership of the data source. Health registration requires the optional `Relayer.HealthChecks` package. +Registration does not create tables, enable `IOutboxEnlistment`, or start workers. + +## Reads and mutations + +The store follows the [core contract](outbox-stores.md): + +- Reads select one lane, or unordered rows with a null lane, in ascending PostgreSQL UUID order. They honor the + buffer length and exclusive ID cursor. Body, header bytes, duplicate header names and their order are preserved. +- Reads and counts include due schedules and expired claims exactly at the supplied UTC instant. They exclude + future schedules, parked rows and live claims. Counts span every lane. Dead rows reside in a separate table. +- Claiming uses one conditional `UPDATE`. A competing claim succeeds only after the prior claim expires. +- Renewal uses the greater of the existing and requested expiry. Renewal, completion and failure recording require + the current token and an unexpired claim. Expired or replaced owners return false without mutation. +- Failure recording increments attempts, saves the error and releases the claim atomically. Repeating it with the + released token returns false. Completion deletes only the currently claimed row. + +Use UTC instants consistently. PostgreSQL timestamps have microsecond precision. Await each operation before +starting another on the same store, and finish using borrowed rows before another read. Database errors and +cancellation propagate; they never become an empty backlog. A cancelled mutation might already have committed. +The store does not establish native broker delivery guarantees or ordered lane ownership. + +## Header storage + +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. EF Core interceptors and PostgreSQL outbox transactions +write compatible rows through the shared codec and batch writer. +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 cbcbc85b2..ea6968843 100644 --- a/website/docs/roadmap.md +++ b/website/docs/roadmap.md @@ -20,3 +20,28 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu - [EF Core consumer inbox](reference/ef-core-inbox.md): PostgreSQL deduplication, concurrent redelivery, atomic business/inbox/outbox commits and duplicate metrics. Automatic for the selected outbox context, opt-in for inbox-only consumers. - [PostgreSQL ADO.NET and Dapper transactions](reference/postgres-outbox.md): scoped enlistment, owned message copies and one atomic batched insert on commit. - [Unordered PostgreSQL direct dispatch](reference/direct-dispatch.md): background sends immediately after EF commit, fenced claims, native transport batches and fenced batch deletion. Recovery polling, poison-row handling and cleanup remain planned. +- The consume pipeline and the native receive SPI. +- [Service Bus receive primitives](transports/service-bus-receive.md): the native callback binding and manual settlement view. The complete Service Bus transport remains planned. +- 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. +- Manual settlement requests through `ISettlementFeature`, with exception precedence and durable capability fallbacks. +- Declared topology with validate and provision modes, and JSON export. +- The [in-memory transport](transports/in-memory.md), with native queue and partitioned log semantics. +- The [Kafka adapter](transports/kafka.md), with named producers, serial consumer groups, native batches and checkpoints, durable dead-letter copies, application logging, receive telemetry and Testcontainers conformance. Parallel partition scheduling and health adapters remain planned. +- The packaged [transport conformance suite](transports/conformance.md), passing in-memory queue and log modes, with capability skips and native fixture hooks for third-party adapters. +- The [test harness and standalone handler context](guides/testing.md), with logical send and native dispatch observations, deterministic in-memory idle detection, reset and provider isolation. +- The [performance regression gate](contributing/performance.md), covering end-to-end in-memory send/receive, concurrent delivery, allocation attribution and 100-handler composition. Raw broker comparisons remain planned with each adapter. +- Core tracing primitives, single and batch delivery spans, native settlement wrappers, consume metrics and generated failure logs. Kafka send, serial receive and batch-commit instrumentation are implemented; the other native receive adapters and outbox instrumentation remain planned. +- The optional [health integration](guides/health-checks.md), with connectivity, consumer liveness and backlog checks. The outbox adapter accepts application-provided durable stores; native broker adapters remain planned. + +## Phases + +| Phase | Scope | Exit criteria | +|---|---|---| +| 0 | Core abstractions, pipeline, source generator and analyzers, in-memory transport, test harness, telemetry | Handler round trip under Native AOT; benchmarks in CI | +| 1 | Kafka and Azure Service Bus transports; failure pipeline; DLQ and redrive | Broker-restart and rebalance chaos tests pass | +| 2 | EF Core and PostgreSQL outbox and inbox (lanes, direct dispatch, cleanup) | Crash and duplicate tests with multiple instances pass; at most 5% overhead | +| 3 | SQS/SNS and RabbitMQ; SQL Server and MySQL outbox; topology export; multi-tenancy | Every transport passes the conformance suite | +| 4 | Sagas, request/response, change-data-capture dispatch, more transports | — | + +The [design document](https://github.com/thomhurst/Relayer/blob/main/docs/design.md) describes each planned feature in detail. diff --git a/website/sidebars.js b/website/sidebars.js index 19f350622..b6c8b9f11 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -42,3 +42,11 @@ const sidebars = { type: 'category', label: 'Reference', items: ['reference/diagnostics', 'reference/outbox-stores', 'reference/postgres-schema', 'reference/postgres-store', 'reference/postgres-outbox', 'reference/ef-core-outbox', 'reference/direct-dispatch', 'reference/ordered-dispatch', 'reference/ef-core-inbox'], + }, + 'roadmap', + 'contributing/documentation', + 'contributing/performance', + ], +}; + +export default sidebars; diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 8b7534379..b6381d424 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -107,7 +107,7 @@ function Layers() { ))}
traceparent
-
00-4bf92f35…-00f067aa…-01
+
00-4bf92f35…-00f067aa…-01
@@ -135,7 +135,7 @@ function Hero() { Relayer

- Messaging for .NET that wraps your broker’s own client. Relayer handles retries, dead-lettering, the outbox, + Messaging for .NET that wraps your broker’s own client. Relayer handles retries, dead-lettering, the outbox, tracing and serialization. Kafka, Service Bus, SQS and RabbitMQ keep sending, ordering and settling messages the way they already do.

@@ -298,3 +298,47 @@ const status = [ ['Native broker health adapters', 'Planned', false], ['Ordered PostgreSQL dispatch and lane leases', 'Implemented', true], ['Outbox recovery and cleanup', 'Planned', false], + ['Send and delivery tracing, settlement, metrics and logs', 'Implemented', true], + ['Native receive and outbox telemetry', 'Planned', false], +]; + +function Status() { + return ( +
+
+ + Where it stands + +

+ Relayer is built in the open. This is what works on main today. +

+ + + {status.map(([area, state, done]) => ( + + + + + ))} + +
{area}{state}
+ See the full roadmap +
+
+ ); +} + +export default function Home() { + return ( + + +
+ + + +
+
+ ); +}