Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public sealed class PostgresOutboxProcessor
/// The signal used to wake the processor when new outbox messages are enqueued.
/// </param>
/// <param name="options">
/// The outbox options containing the SQL queries and connection factory.
/// The options for this outbox processor.
/// </param>
internal PostgresOutboxProcessor(
ILogger<PostgresOutboxProcessor> logger,
Expand All @@ -56,7 +56,7 @@ internal PostgresOutboxProcessor(
_signal = signal;
_contextPool = pools.DispatchContext;
_options = options;
_timeProvider = services.GetService<TimeProvider>() ?? TimeProvider.System;
_timeProvider = services.GetTimeProvider();
}

/// <summary>
Expand All @@ -66,36 +66,40 @@ internal PostgresOutboxProcessor(
/// <param name="cancellationToken">A token that signals when the processor should stop.</param>
public async Task ProcessAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
using var signalCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

try
{
using var joinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var signaled = _signal.WaitAsync(signalCts.Token);

try
while (!cancellationToken.IsCancellationRequested)
{
var signaled = _signal.WaitAsync(joinedCts.Token);

var nextPollingInterval = await ProcessPendingAsync(cancellationToken);
var delay = _options.PollingInterval;

if (nextPollingInterval is not null)
if (nextPollingInterval is { } interval && interval < delay)
{
_logger.OutboxProcessorSleeping(nextPollingInterval.Value);

await Task.WhenAny(Task.Delay(nextPollingInterval.Value, cancellationToken), signaled);
delay = interval;
_logger.OutboxProcessorSleeping(delay);
}
else

using var delayCts = new CancellationTokenSource();
await Task.WhenAny(Task.Delay(delay, delayCts.Token), signaled);
delayCts.TryCancel();

if (signaled.IsCompleted)
{
await signaled;
signaled = _signal.WaitAsync(signalCts.Token);
}
}
catch (OperationCanceledException)
{
joinedCts.TryCancel();
}
catch
{
joinedCts.TryCancel();
throw;
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
finally
{
signalCts.TryCancel();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Mocha.EntityFrameworkCore;
Expand All @@ -11,46 +12,54 @@
namespace Mocha.Outbox;

/// <summary>
/// Provides extension methods on <see cref="IEntityFrameworkCoreBuilder"/> for registering
/// the Postgres outbox infrastructure including the outbox processor, worker, and message persistence.
/// Registers the Postgres outbox for an Entity Framework Core <see cref="DbContext"/>.
/// </summary>
public static class OutboxServiceCollectionExtensions
{
/// <summary>
/// Registers the full Postgres outbox pipeline: table info discovery from the EF Core model,
/// the <see cref="PostgresOutboxProcessor"/>, a hosted background worker, and a scoped
/// <see cref="IMessageOutbox"/> backed by direct Npgsql inserts.
/// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit.
/// </summary>
/// <remarks>
/// This method also calls <see cref="OutboxEntityFrameworkCorePersistenceBuilderExtensions.UseOutboxCore"/>
/// to register the EF Core interceptors that signal the processor on save and commit.
/// </remarks>
/// <param name="builder">The Entity Framework Core builder to configure.</param>
/// <returns>The same <paramref name="builder"/> instance for chaining.</returns>
public static IEntityFrameworkCoreBuilder UsePostgresOutbox(this IEntityFrameworkCoreBuilder builder)
=> builder.UsePostgresOutbox(static _ => { });

/// <summary>
/// Registers the full Postgres outbox pipeline with the specified <see cref="PostgresOutboxOptions"/>.
/// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit.
/// </summary>
/// <param name="builder">The Entity Framework Core builder to configure.</param>
/// <param name="configure">A delegate that configures the <see cref="PostgresOutboxOptions"/>.</param>
/// <param name="configure">Configures the <see cref="PostgresOutboxOptions"/>.</param>
/// <returns>The same <paramref name="builder"/> instance for chaining.</returns>
public static IEntityFrameworkCoreBuilder UsePostgresOutbox(
this IEntityFrameworkCoreBuilder builder,
Action<PostgresOutboxOptions> configure)
{
ArgumentNullException.ThrowIfNull(configure);

var contextType = builder.ContextType;
builder.UseOutboxCore();
builder.Services.AddOptions<PostgresOutboxOptions>(builder.Name).Configure(configure);

var contextType = builder.ContextType;

if (builder.Services.Any(descriptor =>
descriptor.ServiceType == typeof(PostgresOutboxProcessor)
&& Equals(descriptor.ServiceKey, contextType)))
{
return builder;
}

builder.Services.AddOptions<PostgresOutboxOptions>(builder.Name)
.Validate(
options => options.PollingInterval > TimeSpan.Zero,
$"{nameof(PostgresOutboxOptions)}.{nameof(PostgresOutboxOptions.PollingInterval)} "
+ "must be greater than zero.");

builder
.Services.AddOptions<PostgresTableInfo>(builder.Name)
.Configure<IServiceProvider>((options, sp) =>
{
using var scope = sp.CreateScope();
var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType);
var dbContext = scope.ServiceProvider.GetRequiredDbContext(contextType);
var model = dbContext.Model;

ConfigureOutboxTableInfo(options.Outbox, model);
Expand All @@ -62,15 +71,17 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox(
{
options.CreateConnection = services =>
{
var dbContext = (DbContext)services.GetRequiredService(contextType);
var dbContext = services.GetRequiredDbContext(contextType);
return (NpgsqlConnection)((ICloneable)dbContext.Database.GetDbConnection()).Clone();
};

var tableInfo = tableInfoMonitor.Get(builder.Name);
options.Queries = PostgresMessageOutboxQueries.From(tableInfo.Outbox);
});
})
.Configure<IOptionsMonitor<PostgresOutboxOptions>>((options, outboxOptions) =>
options.PollingInterval = outboxOptions.Get(builder.Name).PollingInterval);

builder.Services.AddSingleton(sp =>
builder.Services.AddKeyedSingleton(contextType, (sp, _) =>
{
var optionsMonitor = sp.GetRequiredService<IOptionsMonitor<PostgresMessageOutboxOptions>>();
var options = optionsMonitor.Get(builder.Name);
Expand All @@ -79,19 +90,15 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox(
sp,
sp.GetRequiredService<IMessagingRuntime>(),
sp.GetRequiredService<IMessagingPools>(),
sp.GetRequiredService<IOutboxSignal>(),
sp.GetRequiredKeyedService<IOutboxSignal>(contextType),
options);
});

builder.Services.AddSingleton<PostgresMessageBusOutboxWorker>();

builder.Services.AddHostedService(sp => sp.GetRequiredService<PostgresMessageBusOutboxWorker>());
builder.Services.AddSingleton<IHostedService>(sp =>
new PostgresMessageBusOutboxWorker(sp.GetRequiredKeyedService<PostgresOutboxProcessor>(contextType)));

builder.Services.TryAddScoped<IMessageOutbox>(sp =>
PostgresMessageOutbox.Create(contextType, builder.Name, sp)
);

builder.UseOutboxCore();
PostgresMessageOutbox.Create(contextType, builder.Name, sp));

return builder;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json;
using System.Transactions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
Expand All @@ -13,14 +14,8 @@
namespace Mocha.Outbox;

/// <summary>
/// Implements <see cref="IMessageOutbox"/> for Postgres by inserting serialized message envelopes
/// into the outbox table using raw SQL through the DbContext Npgsql connection.
/// Stores message envelopes in the PostgreSQL outbox.
/// </summary>
/// <remarks>
/// An active database or ambient transaction defers the outbox signal until commit.
/// A publish or send without a transaction throws when a transaction is required,
/// and otherwise signals immediately after insert.
/// </remarks>
internal sealed class PostgresMessageOutbox : IMessageOutbox, IDisposable
{
private readonly DbContext _originalDbContext;
Expand Down Expand Up @@ -60,8 +55,8 @@ public PostgresMessageOutbox(
/// <returns>A new <see cref="PostgresMessageOutbox"/> configured for the specified DbContext.</returns>
public static PostgresMessageOutbox Create(Type contextType, string optionsName, IServiceProvider services)
{
var dbContext = (DbContext)services.GetRequiredService(contextType);
var signal = services.GetRequiredService<IOutboxSignal>();
var dbContext = services.GetRequiredDbContext(contextType);
var signal = services.GetRequiredKeyedService<IOutboxSignal>(contextType);
var outboxOptionsMonitor = services.GetRequiredService<IOptionsMonitor<PostgresMessageOutboxOptions>>();
var outboxOptions = outboxOptionsMonitor.Get(optionsName);
var insertSql = outboxOptions.Queries.InsertEnvelope;
Expand All @@ -71,7 +66,7 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName,
}

/// <summary>
/// Serializes the message envelope and inserts it into the Postgres outbox table.
/// Serializes the message envelope and stores it in the Postgres outbox table.
/// </summary>
/// <remarks>
/// With an active database transaction, the signal is deferred to the transaction commit interceptor.
Expand All @@ -85,13 +80,9 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName,
/// </exception>
public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken cancellationToken)
{
if (_requireTransaction && !HasTransaction() && RequiresTransaction(envelope))
if (_requireTransaction && RequiresTransaction(envelope) && !HasTransaction())
{
throw new InvalidOperationException(
$"The outbox for DbContext '{_originalDbContext.GetType().FullName}' "
+ "requires a transaction to publish or send a message. "
+ "Begin a transaction on that DbContext, use UseTransaction() for consumers, "
+ "or set RequireTransaction to false in UsePostgresOutbox().");
throw ThrowHelper.OutboxRequiresTransaction(_originalDbContext.GetType());
}

await _semaphore.WaitAsync(cancellationToken);
Expand Down Expand Up @@ -119,7 +110,15 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken

await command.ExecuteNonQueryAsync(cancellationToken);

if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is not NpgsqlTransaction)
if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is NpgsqlTransaction)
{
// A context without the messaging extension has no outbox state and no commit interceptor.
if (_originalDbContext.GetInfrastructure().GetService<DbContextOutboxState>() is { } state)
{
state.HasUncommittedMessages = true;
}
}
else
{
_signal.SetAfterAmbientTransaction();
}
Expand All @@ -137,7 +136,17 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken
}

private bool HasTransaction()
=> _originalDbContext.Database.CurrentTransaction is not null || Transaction.Current is not null;
=> _originalDbContext.Database.CurrentTransaction is not null
|| HasSystemTransaction(_originalDbContext);

/// <summary>
/// Returns whether the connection of the context takes part in a <see cref="Transaction"/>, either enlisted
/// explicitly or joined as the ambient transaction.
/// </summary>
private static bool HasSystemTransaction(DbContext context)
=> context.GetService<IDbContextTransactionManager>() is ITransactionEnlistmentManager manager
? manager.EnlistedTransaction is not null || manager.CurrentAmbientTransaction is not null
: Transaction.Current is not null;

// Replies and faults can be dispatched after the handler transaction rolls back.
private static bool RequiresTransaction(MessageEnvelope envelope)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ internal sealed class PostgresMessageOutboxOptions
/// </summary>
public int CriticalAttemptInterval { get; set; } = 10;

/// <summary>
/// Gets or sets how long an idle processor waits before checking for messages when no notification arrives.
/// </summary>
public TimeSpan PollingInterval { get; set; }

/// <summary>
/// Gets or sets how long the processor waits before it looks again for a due message that another
/// instance holds.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ namespace Mocha.Outbox;
/// </summary>
public sealed class PostgresOutboxOptions
{
/// <summary>
/// Gets or sets how long an idle worker waits before checking the database for messages to send
/// when no notification arrives. The default is 10 seconds.
/// </summary>
public TimeSpan PollingInterval { get; set; } = TimeSpan.FromSeconds(10);

/// <summary>
/// Gets or sets whether a publish or send through the outbox requires an active database or ambient
/// transaction and throws an <see cref="InvalidOperationException"/> without one. The default is <c>true</c>.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Mocha.EntityFrameworkCore;

namespace Mocha.Outbox;

internal static class ThrowHelper
{
public static InvalidOperationException OutboxRequiresTransaction(Type contextType)
=> new(
$"{nameof(IMessageBus)} publishes and sends are stored in the outbox of the first {nameof(DbContext)} "
+ $"registered with {nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}(), "
+ $"'{contextType.FullName}', and require a transaction on that {nameof(DbContext)}. "
+ $"Begin a transaction on it, use {nameof(EntityFrameworkCoreBuilderExtensions.UseTransaction)}() "
+ "on it for consumers, "
+ $"or set {nameof(PostgresOutboxOptions.RequireTransaction)} to false in "
+ $"{nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}().");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Mocha.EntityFrameworkCore;

internal static class DbContextMessagingServicesExtensions
{
/// <summary>
/// Gets the application services carried by the messaging extension of the context options.
/// The context options must contain the messaging extension.
/// </summary>
public static MessagingDbContextServices GetMessagingServices(this DbContext context)
=> context.GetService<IDbContextOptions>().FindExtension<MessagingDbContextOptionsExtension>()!.Services;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ internal static class DbContextOptionsBuilderExtensions
/// </summary>
/// <param name="optionsBuilder">The DbContext options builder to extend.</param>
/// <param name="options">The messaging options carrying service configuration delegates.</param>
/// <param name="services">The application services that the messaging interceptors and outbox use.</param>
/// <returns>The same <paramref name="optionsBuilder"/> instance for chaining.</returns>
public static DbContextOptionsBuilder AddMessagingExtensions(
this DbContextOptionsBuilder optionsBuilder,
MessagingDbContextOptions options)
MessagingDbContextOptions options,
MessagingDbContextServices services)
{
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(
new MessagingDbContextOptionsExtension(options));
new MessagingDbContextOptionsExtension(options, services));

return optionsBuilder;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.EntityFrameworkCore;

namespace Mocha.EntityFrameworkCore;

internal static class DbContextServiceProviderExtensions
{
/// <summary>
/// Gets the <see cref="DbContext"/> of the specified type, and throws when it is not registered.
/// </summary>
public static DbContext GetRequiredDbContext(this IServiceProvider services, Type contextType)
=> (DbContext?)services.GetService(contextType)
?? throw ThrowHelper.DbContextNotRegistered(contextType);
}
Loading