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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions benchmarks/Relayer.Benchmarks/MySqlOutboxDispatchBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using BenchmarkDotNet.Attributes;
using Relayer.Outbox.MySql;

namespace Relayer.Benchmarks;

/// <summary>Attributes commit-to-worker buffer transfer and grouping separately from native database allocations.</summary>
[MemoryDiagnoser]
public class MySqlOutboxDispatchBenchmarks
{
private readonly List<BufferedOutboxMessage> _source = [];
private readonly OutboxDispatchBatch _batch = new();
private OutboxRecord[] _records = null!;
private DateTimeOffset _now;

[Params(1, 64)]
public int Rows { get; set; }

[GlobalSetup]
public void Setup()
{
_now = DateTimeOffset.UtcNow;
_records = new OutboxRecord[Rows];
var body = new byte[1024];
KeyValuePair<string, WireString>[] headers = [new("ce_type", new WireString("dispatch.probe;v=1"))];
for (var i = 0; i < Rows; i++)
{
_source.Add(new());
_records[i] = new(Guid.CreateVersion7(), "events", "dispatch.probe;v=1",
new OutgoingMessage(i % 2 == 0 ? "alpha" : "beta", body, headers), _now);
}
// Both halves of the buffer swap and header decode must reach their high-water marks.
BufferOnly();
TransferAndGroup();
TransferAndGroup();
}

[Benchmark(Baseline = true)]
public int BufferOnly()
{
var bytes = 0;
for (var i = 0; i < Rows; i++)
{
_source[i].Copy(_records[i], 32);
bytes += _source[i].ToMessage().Body.Length;
_source[i].Clear();
}
return bytes;
}

[Benchmark]
public int TransferAndGroup()
{
for (var i = 0; i < Rows; i++) _source[i].Copy(_records[i], 32);
_batch.Take(_source, Rows, _now);
_batch.Sort();
var bytes = 0;
for (var i = 0; i < _batch.Count; i++) bytes += _batch.Rows[i].ToMessage().Body.Length;
_batch.Clear();
return bytes;
}
}

/// <summary>Measures reusable native batch parameter preparation as the dispatch group grows.</summary>
[MemoryDiagnoser]
public class MySqlDispatchMutationBenchmarks
{
private readonly MySqlDispatchMutations _mutations = new("UPDATE outbox SET claim_token = @token WHERE id = @id");
private OutboxClaim[] _claims = null!;
private DateTimeOffset _now;
private DateTimeOffset _expires;

[Params(1, 64)]
public int Rows { get; set; }

[GlobalSetup]
public void Setup()
{
_now = DateTimeOffset.UtcNow;
_expires = _now.AddMinutes(1);
_claims = new OutboxClaim[Rows];
for (var i = 0; i < Rows; i++) _claims[i] = new(Guid.NewGuid(), Guid.NewGuid());
PrepareClaims();
}

[Benchmark]
public void PrepareClaims() => _mutations.Prepare(_claims, _now, _expires);

[GlobalCleanup]
public void Cleanup() => _mutations.Dispose();
}
25 changes: 25 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D52](#d52-allocations-a-native-api-requires-count-as-native-client-cost) | Allocations a native API requires count as native-client cost | Accepted |
| [D53](#d53-singleton-only-consumers-open-delivery-scopes-on-demand) | Singleton-only consumers open delivery scopes on demand | Accepted |
| [D54](#d54-service-bus-processors-drain-durable-work-before-settlement) | Service Bus processors drain durable work before settlement | Accepted |
| [D55](#d55-mysql-direct-dispatch-reuses-native-batches-and-fenced-row-counts) | MySQL commit-triggered direct dispatch | Accepted |

---

Expand Down Expand Up @@ -1135,3 +1136,27 @@ D52 classifies the required suspended callback Task as native-client cost, pinne
ReceiveAndDelete can settle before work is durable. Treating the native stop token as the drain deadline
abandons successfully completed work at shutdown. Scheduling subscription retries through their topic
changes native routing. Adding health dependencies to every transport user violates optional integration.

## D55. MySQL direct dispatch reuses native batches and fenced row counts

**Context.** MySQL enqueue (D48) commits durable rows but has no commit-triggered sender.
MySqlConnector 2.6.2 already provides packet construction, execution and cancellation through
[MySqlBatch](https://github.com/mysql-net/MySqlConnector/blob/2.6.2/src/MySqlConnector/MySqlBatch.cs).
Its per-command `RecordsAffected` is hardcoded to zero, tracked in
[MySqlConnector #1696](https://github.com/mysql-net/MySqlConnector/issues/1696). MySQL's Event
Scheduler executes SQL at scheduled times; it cannot notify application-owned native transports
of a local transaction commit.

**Decision.** Apply D33/D35's bounded owned-buffer handoff and capability cache to ADO.NET
MySQL commits. Reuse native conditional InnoDB updates/deletes, `MySqlBatch` and `SELECT ROW_COUNT()`
for each fenced outcome. Keep UUID and timestamp parameter storage reusable, as in D48. Do not
implement a second packet protocol or replace native transport sends. The writer and worker's
explicit database, server, port and table prefix must agree; validate before the transaction.

**Consequences.** MySQL batching remains experimental upstream and does not promise one round
trip. Partial claim batches may leave expiring claims after an error; no send begins without all
outcomes being read. Completion failure never increments broker failure attempts. Queue overflow,
shutdown, expiry and post-send database errors leave durable work with the same at-least-once
boundary as D33. Ordered dispatch, inbox and recovery remain separate deliverables; no eventual
delivery guarantee is inferred from commit notification alone. See the
[MySQL reference](../website/docs/reference/mysql-store.md#commit-triggered-unordered-dispatch).
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ The outbox is the area where every existing library has had correctness bugs, so
### 6.2 Enlisting: hard to misuse

- **EF Core:** Relayer registers a `SaveChangesInterceptor` and a `DbTransactionInterceptor`. 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 EF Core, inbox, ordered dispatch and recovery remain planned.
- **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 EF Core, inbox, ordered dispatch and recovery remain planned. MySQL ADO.NET/Dapper enqueue (D48) also supports opt-in commit-triggered unordered dispatch using native MySqlBatch and fenced row counts (D55); its inbox, ordered and recovery workers remain planned.
- **MongoDB / DynamoDB:** use their session and transaction APIs in the same style.

### 6.3 Schema
Expand Down
14 changes: 14 additions & 0 deletions src/Relayer.Outbox.MySql/MySqlDirectDispatchOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Relayer.Outbox.MySql;

/// <summary>Limits for commit-triggered, unordered MySQL outbox dispatch.</summary>
public sealed class MySqlDirectDispatchOptions
{
/// <summary>Maximum queued commits. Overflow leaves durable rows pending and logs an error.</summary>
public int QueueCapacity { get; init; } = 256;

/// <summary>Maximum messages claimed and sent together, also bounded by the native endpoint limit.</summary>
public int BatchSize { get; init; } = 100;

/// <summary>Lifetime of a fenced claim. A send that outlives it can be delivered again.</summary>
public TimeSpan ClaimDuration { get; init; } = TimeSpan.FromSeconds(30);
}
89 changes: 89 additions & 0 deletions src/Relayer.Outbox.MySql/MySqlDirectDispatchRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System.Globalization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Relayer.Transports;

namespace Relayer.Outbox.MySql;

/// <summary>Registers explicitly named MySQL durable read/claim stores.</summary>
public static partial class MySqlOutboxServiceCollectionExtensions
{
/// <summary>Registers a named durable store and a hosted worker for unordered, commit-triggered sends.</summary>
/// <remarks>
/// Select this name with MySqlOutboxOptions.DispatchStoreName on participating scopes.
/// The application owns the data source; its native connection string must specify Database.
/// Writers must use the same database spelling. This does not dispatch ordered or future-due rows or run recovery polling.
/// </remarks>
public static IServiceCollection AddRelayerMySqlDirectDispatch(this IServiceCollection services,
string storeName, MySqlConnector.MySqlDataSource dataSource, MySqlOutboxOptions? storeOptions = null,
MySqlDirectDispatchOptions? dispatchOptions = null)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentException.ThrowIfNullOrWhiteSpace(storeName);
ArgumentNullException.ThrowIfNull(dataSource);
_ = MySqlDirectDispatcher.ValidateDataSource(dataSource);
if (services.Any(descriptor => descriptor.ServiceType == typeof(MySqlDirectDispatcher) && Equals(descriptor.ServiceKey, storeName)))
throw new InvalidOperationException($"Direct outbox dispatch store '{storeName}' is already registered.");
dispatchOptions ??= new();
if (dispatchOptions.QueueCapacity is <= 0 or int.MaxValue || dispatchOptions.BatchSize <= 0 || dispatchOptions.ClaimDuration <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(dispatchOptions), "QueueCapacity and BatchSize must be positive, QueueCapacity must be below Int32.MaxValue, and ClaimDuration must be positive.");
storeOptions ??= new();
var snapshot = new MySqlOutboxOptions { TablePrefix = storeOptions.TablePrefix, Lanes = storeOptions.Lanes };
_ = MySqlOutboxSchema.CreateScript(snapshot);
services.AddRelayerMySqlOutboxStore(storeName, dataSource, snapshot);
services.AddSingleton(new DispatchSettings(storeName, dispatchOptions));
services.AddOptions<MySqlDirectDispatchOptions>();
services.TryAddSingleton<IOptionsFactory<MySqlDirectDispatchOptions>, DispatchOptionsFactory>();
services.AddKeyedSingleton<MySqlDirectDispatcher>(storeName, (provider, _) =>
new MySqlDirectDispatcher(dataSource, snapshot,
provider.GetRequiredService<IOptionsMonitor<MySqlDirectDispatchOptions>>().Get(storeName),
provider.GetServices<ITransport>(), provider.GetRequiredService<ILogger<MySqlDirectDispatcher>>(),
instrumentation: provider.GetService<RelayerInstrumentation>()));
services.AddSingleton<IHostedService>(provider => provider.GetRequiredKeyedService<MySqlDirectDispatcher>(storeName));
return services;
}

/// <summary>Binds immutable direct-dispatch limits from configuration at registration.</summary>
public static IServiceCollection AddRelayerMySqlDirectDispatch(this IServiceCollection services,
string storeName, MySqlConnector.MySqlDataSource dataSource, IConfiguration configuration,
MySqlOutboxOptions? storeOptions = null)
{
ArgumentNullException.ThrowIfNull(configuration);
var defaults = new MySqlDirectDispatchOptions();
return services.AddRelayerMySqlDirectDispatch(storeName, dataSource, storeOptions, new MySqlDirectDispatchOptions
{
QueueCapacity = Read(configuration, nameof(defaults.QueueCapacity), defaults.QueueCapacity),
BatchSize = Read(configuration, nameof(defaults.BatchSize), defaults.BatchSize),
ClaimDuration = Read(configuration, nameof(defaults.ClaimDuration), defaults.ClaimDuration)
});
}

private static T Read<T>(IConfiguration configuration, string key, T fallback) where T : IParsable<T>
{
var value = configuration[key];
if (value is null) return fallback;
if (T.TryParse(value, CultureInfo.InvariantCulture, out var parsed)) return parsed;
throw new OptionsValidationException(Options.DefaultName, typeof(MySqlDirectDispatchOptions), [$"{key}: '{value}' is invalid."]);
}

private sealed record DispatchSettings(string Name, MySqlDirectDispatchOptions Options);

private sealed class DispatchOptionsFactory(IEnumerable<DispatchSettings> settings,
IEnumerable<IConfigureOptions<MySqlDirectDispatchOptions>> setups,
IEnumerable<IPostConfigureOptions<MySqlDirectDispatchOptions>> postConfigures,
IEnumerable<IValidateOptions<MySqlDirectDispatchOptions>> validations)
: OptionsFactory<MySqlDirectDispatchOptions>(setups, postConfigures, validations)
{
protected override MySqlDirectDispatchOptions CreateInstance(string name)
{
foreach (var setting in settings)
if (setting.Name == name) return setting.Options;
return new();
}
}

}
Loading
Loading