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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,28 @@ jobs:
fi
.artifacts/pubsub-aot/Relayer.GooglePubSub.AotSmoke

# This remains a strict gate. MongoDB.Driver's upstream analysis diagnostics currently
# block the MongoDB provider draft; do not suppress them to promote that work.
- name: MongoDB Native AOT persistence smoke test
if: steps.solution.outputs.present == 'true'
run: |
dotnet publish tests/Relayer.Outbox.MongoDB.AotSmoke -c Release -r linux-x64 -o .artifacts/mongodb-aot-smoke
mongo_container=$(docker run --detach --rm --publish 127.0.0.1::27017 mongo:8.0.16 --replSet rs0 --bind_ip_all)
trap 'docker rm --force "$mongo_container"' EXIT
for attempt in {1..60}; do
if docker exec "$mongo_container" mongosh --quiet --eval 'db.adminCommand({ping:1})' >/dev/null 2>&1; then break; fi
if [ "$attempt" -eq 60 ]; then docker logs "$mongo_container"; exit 1; fi
sleep 1
done
docker exec "$mongo_container" mongosh --quiet --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
for attempt in {1..60}; do
if docker exec "$mongo_container" mongosh --quiet --eval 'if (!db.hello().isWritablePrimary) quit(1)' >/dev/null 2>&1; then break; fi
if [ "$attempt" -eq 60 ]; then docker logs "$mongo_container"; exit 1; fi
sleep 1
done
mongo_port=$(docker port "$mongo_container" 27017/tcp | sed 's/.*://')
.artifacts/mongodb-aot-smoke/Relayer.Outbox.MongoDB.AotSmoke "mongodb://127.0.0.1:$mongo_port/?directConnection=true&serverSelectionTimeoutMS=10000"

# Tests for the issue/PR loop's merge gate and the Claude review helper. They run here, not in
# their own workflow, so `CI Passed` (and therefore auto-merge) waits for them.
agent-tooling:
Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@
<ItemGroup Label="Outbox">
<PackageVersion Include="Microsoft.Data.SqlClient" Version="7.1.1" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
<PackageVersion Include="MongoDB.Driver" Version="3.13.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.14" />
<PackageVersion Include="Npgsql" Version="10.0.3" />
<PackageVersion Include="MySqlConnector" Version="2.6.2" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
</ItemGroup>

<ItemGroup Label="Testing and benchmarks">
<PackageVersion Include="Testcontainers.MongoDb" Version="4.16.0" />
<PackageVersion Include="Dapper" Version="2.1.89" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.14" />
Expand Down
3 changes: 3 additions & 0 deletions Relayer.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<Project Path="src/Relayer.Outbox.EntityFrameworkCore/Relayer.Outbox.EntityFrameworkCore.csproj" />
<Project Path="src/Relayer.Outbox.MySql/Relayer.Outbox.MySql.csproj" />
<Project Path="src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj" />
<Project Path="src/Relayer.Outbox.MongoDB/Relayer.Outbox.MongoDB.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Relayer.Aspire.Tests/Relayer.Aspire.Tests.csproj" />
Expand All @@ -51,6 +52,8 @@
<Project Path="tests/Relayer.Tracing.Tests/Relayer.Tracing.Tests.csproj" />
<Project Path="tests/Relayer.Outbox.MySql.Tests/Relayer.Outbox.MySql.Tests.csproj" />
<Project Path="tests/Relayer.Outbox.PostgreSql.Tests/Relayer.Outbox.PostgreSql.Tests.csproj" />
<Project Path="tests/Relayer.Outbox.MongoDB.Tests/Relayer.Outbox.MongoDB.Tests.csproj" />
<Project Path="tests/Relayer.Outbox.MongoDB.AotSmoke/Relayer.Outbox.MongoDB.AotSmoke.csproj" />
<Project Path="tests/Relayer.SourceGenerators.Tests/Relayer.SourceGenerators.Tests.csproj" />
</Folder>
<Folder Name="/benchmarks/">
Expand Down
32 changes: 32 additions & 0 deletions benchmarks/Relayer.Benchmarks/MongoDBOutboxCodecBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using BenchmarkDotNet.Attributes;
using Relayer.Outbox.MongoDB;

namespace Relayer.Benchmarks;

/// <summary>Persistence encoding cost by payload size, excluding native driver I/O and native BSON document wrappers.</summary>
[MemoryDiagnoser]
public class MongoDBOutboxCodecBenchmarks
{
[Params(128, 4096)]
public int BodyBytes { get; set; }

[Params(false, true)]
public bool Ordered { get; set; }

private readonly MongoDBOutboxBuffer _buffer = new();
private OutboxRecord _record;

[GlobalSetup]
public void Setup()
{
var body = new byte[BodyBytes];
new Random(42).NextBytes(body);
_record = new(Guid.CreateVersion7(), "events", "order;v=1", new("orders", body,
new KeyValuePair<string, WireString>[] { new("type", new("order;v=1")), new("traceparent", new("original-creation-context")) },
Ordered ? new WireString("customer-é") : null), DateTimeOffset.UtcNow);
_buffer.Encode(_record, 32);
}

[Benchmark]
public int Encode() => _buffer.Encode(_record, 32);
}
1 change: 1 addition & 0 deletions benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Relayer.Outbox.PostgreSql\Relayer.Outbox.PostgreSql.csproj" />
<ProjectReference Include="../../src/Relayer.Outbox.MySql/Relayer.Outbox.MySql.csproj" />
<ProjectReference Include="../../src/Relayer.Outbox.MongoDB/Relayer.Outbox.MongoDB.csproj" />
<ProjectReference Include="..\..\src\Relayer\Relayer.csproj" />
<ProjectReference Include="..\..\src\Relayer.Outbox.EntityFrameworkCore\Relayer.Outbox.EntityFrameworkCore.csproj" />
<ProjectReference Include="../../src/Relayer.Kafka/Relayer.Kafka.csproj" />
Expand Down
32 changes: 32 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D64](#d64-sql-server-ordered-dispatch-reuses-native-locks-and-sequence-ranges) | SQL Server ordered dispatch reuses native locks and sequence ranges | Accepted |
| [D65](#d65-mysql-maintenance-uses-native-session-admission-and-existing-dispatch) | MySQL maintenance uses native session admission and existing dispatch | Accepted |
| [D66](#d66-durable-local-work-reuses-outbox-rows-and-native-postgresql-transactions) | Durable local work reuses outbox rows and native PostgreSQL transactions | Accepted |
| [D68](#d68-mongodb-enlistment-writes-through-the-active-native-session) | MongoDB enlistment writes through the active native session | Accepted |

---

Expand Down Expand Up @@ -1589,3 +1590,34 @@ in #459. They must carry row identity and claim token into each attempt and roll
Native row locks serialize deletion with competing claims. Rollback restores both business work and the row;
a successful deletion remains provisional until commit. This permits atomic completion only for work in
that same transaction, not exactly-once external effects. Existing broker dispatch and settlement are unchanged.

## D68. MongoDB enlistment writes through the active native session

**Context.** MongoDB transactions are native session operations rather than ADO.NET transactions. Replacing
their commit or retry protocol would hide native semantics. Relayer must own borrowed payload bytes before a
send completes, and an association must not silently follow a session into a different transaction.

**Decision.** Associate one active application-owned `IClientSessionHandle` with the scoped outbox through
`EnlistTransaction`. Write outgoing rows immediately into that native transaction, consuming a reusable BSON
buffer before completing each send. The application owns native commit, abort, disposal and complete-unit
retry. An association captures the native transaction number; a reused session cannot reactivate it. A native
`WithTransactionAsync` callback creates and disposes an association on every invocation. Operations remain
sequential, as required by the driver. Collection, client and transaction configuration are not replaced.

Use the driver's `RawBsonDocument` and `ByteArrayBuffer` to submit a fixed-schema BSON buffer. The native
`BsonBinaryWriter.WriteBytes(byte[])` API cannot write arbitrary `ReadOnlyMemory<byte>` slices without an
exact-sized array copy. Encode that fixed storage document into reusable capacity instead, avoiding temporary
body/header arrays and reflection-based class maps. Native session, transaction, retry and write protocols
remain entirely with the driver; this encoder does not implement those capabilities.

Persist UUIDs in standard binary byte order and instant fields as UTC ticks, preserving UUIDv7 ordering and
sub-millisecond claim boundaries. Explicit deployment creates indexed collections; named scoped stores implement
the shared durable read/claim protocol. Native BSON command responses require constructor roots for built-in
dynamic serializers under Native AOT, without replacing global configuration. Driver 3.13.0 still emits AOT
and trimming diagnostics, so strict publish remains a release blocker rather than weakening the repository gate.

**Consequences.** Business writes and outbox writes share native commit/abort visibility. Each send uses a native
insert round trip; no extra application-side durable-write batch or commit interception is required. This is a
new provider, not a change to PostgreSQL batching. Native driver allocations remain separate from the reusable
Relayer codec. MongoDB inbox, direct dispatch, ordered leases, recovery and retention are separate integrations;
storage registration alone does not start workers or advertise scheduling.
3 changes: 2 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,8 @@ The outbox is the area where every existing library has had correctness bugs, so
- **EF Core:** Relayer registers a `SaveChangesInterceptor` and a `DbTransactionInterceptor`. Before an implicit save, `context.EnlistRelayerOutbox()` explicitly selects the context that owns buffered sends. An explicit EF transaction activates enlistment automatically when unambiguous. `SaveChangesAsync`, or committing the EF transaction directly, writes business data and outgoing rows atomically. You do not need to override `SaveChanges` (Silverback #164), and it works with **multiple DbContexts** (Silverback #163). Commit through EF's `IDbContextTransaction`, including its `UseTransaction` wrapper: calling the underlying `DbTransaction.Commit` bypasses EF interception. D31 records ownership and failure boundaries; [the site](https://relayer.tomlonghurst.dev/docs/reference/ef-core-outbox) documents implemented PostgreSQL enlistment and remaining dispatch work.
- **ADO.NET / Dapper:** `await using var tx = await outbox.BeginTransactionAsync(connection)` returns a `DbTransaction` subclass. Commit writes the shared outbox batch before the native commit. Create business commands through `tx.Connection`, including Dapper calls: Npgsql commands from the original connection cannot accept a wrapper transaction (D32). Rollback and disposal discard buffered messages. See [PostgreSQL transactions](../website/docs/reference/postgres-outbox.md) for ownership and recovery boundaries. SQL Server follows the same command-connection lifecycle (D47), flushing reusable rows through native `SqlBulkCopy` on the business transaction. Its opt-in unordered commit dispatcher uses native fenced batches (D49); see [SQL Server transactions and dispatch](../website/docs/reference/sqlserver-store.md). SQL Server offers an opt-in ADO.NET consumer inbox boundary using native key-range locking and the same outbox transaction (D59). SQL Server ordered dispatch uses conditional lane leases and native sequence ranges (D64); EF Core remains planned; unordered recovery and maintenance are implemented (D62). MySQL ADO.NET/Dapper enqueue (D48) also supports opt-in commit-triggered unordered dispatch using native MySqlBatch and fenced row counts (D55); its opt-in ADO.NET/Dapper consumer boundary commits inbox identity, business writes and outgoing rows atomically before settlement; ordered workers use database-assigned insertion sequences and fenced InnoDB lane leases (D50, D63); leased unordered recovery, poison isolation and bounded dead/inbox retention reuse the direct dispatcher (D65).

- **MongoDB / DynamoDB:** use their session and transaction APIs in the same style.
- **MongoDB:** the persistence foundation associates an already-active native session transaction with the scoped sender. Each send writes into that transaction before returning; the application commits, aborts and retries natively (D68). [Status and usage](../website/docs/reference/mongodb-outbox.md) include the upstream AOT release blocker. Inbox and workers remain planned.
- **DynamoDB:** use its native transaction API; integration remains planned.

### 6.3 Schema

Expand Down
86 changes: 86 additions & 0 deletions src/Relayer.Outbox.MongoDB/MongoDBOutbox.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using System.Runtime.CompilerServices;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Relayer.Outbox.MongoDB;

/// <summary>Scoped outgoing writes into an application-owned native MongoDB transaction.</summary>
/// <remarks>Await every send sequentially. The caller starts, commits, aborts and disposes the native session.</remarks>
public sealed class MongoDBOutbox : IOutboxEnlistment
{
private readonly IMongoDatabase _database;
private readonly IMongoCollection<RawBsonDocument> _collection;
private readonly int _lanes;
private readonly MongoDBOutboxBuffer _buffer = new();
private Binding? _binding;
private int _writing;

/// <summary>Uses the application's database and native client configuration unchanged.</summary>
public MongoDBOutbox(IMongoDatabase database, MongoDBOutboxOptions? options = null)
{
ArgumentNullException.ThrowIfNull(database);
options ??= new();
options.Validate();
MongoDBSerializerRoots.Preserve();
_database = database;
_collection = database.GetCollection<RawBsonDocument>(options.CollectionPrefix + "outbox");
_lanes = options.Lanes;
}

/// <inheritdoc />
public bool IsActive => _binding is { IsActive: true };

/// <summary>Associates this scope's sender with one already-active native transaction.</summary>
/// <remarks>
/// Dispose the returned association when the transaction ends, including inside each WithTransactionAsync retry.
/// Relayer does not commit, retry, abort, dispose or change configuration on the caller's session.
/// </remarks>
public IDisposable EnlistTransaction(IClientSessionHandle session)
{
ArgumentNullException.ThrowIfNull(session);
if (_binding is not null) throw new InvalidOperationException("Dispose the current MongoDB outbox association before enlisting another transaction.");
if (!ReferenceEquals(session.Client, _database.Client)) throw new ArgumentException("The session must belong to the outbox database's MongoClient.", nameof(session));
if (!session.IsInTransaction) throw new InvalidOperationException("Start a native MongoDB transaction before enlisting it in Relayer.");
return _binding = new(this, session);
}

/// <inheritdoc />
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
public async ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_binding is not { IsActive: true } binding)
throw new InvalidOperationException("Enlist an active native MongoDB transaction before sending through the outbox.");
if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0)
throw new InvalidOperationException("MongoDB transactions require sequential operations. Await each outbox send before starting another.");
try
{
using var document = _buffer.Write(record, _lanes);
// The native driver has consumed the borrowed bytes and stored them in the transaction before returning.
await _collection.InsertOneAsync(binding.Session, document, cancellationToken: cancellationToken).ConfigureAwait(false);
}
finally { Volatile.Write(ref _writing, 0); }
}

private sealed class Binding : IDisposable
{
private readonly MongoDBOutbox _owner;
private readonly long _transactionNumber;
internal IClientSessionHandle Session { get; }
internal bool IsActive => Session.IsInTransaction && Session.WrappedCoreSession.CurrentTransaction.TransactionNumber == _transactionNumber;

internal Binding(MongoDBOutbox owner, IClientSessionHandle session)
{
_owner = owner;
Session = session;
_transactionNumber = session.WrappedCoreSession.CurrentTransaction.TransactionNumber;
}

public void Dispose()
{
if (Volatile.Read(ref _owner._writing) != 0)
throw new InvalidOperationException("Await the active MongoDB outbox send before disposing its transaction association.");
if (ReferenceEquals(_owner._binding, this)) _owner._binding = null;
}
}
}
Loading
Loading