From c0fbc8b51dbe163da319adadbf88f887c551f538 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:55:25 +0000 Subject: [PATCH 1/7] [Mocha] Fix dispatch middleware running again when a stored message is delivered A message that the outbox or a scheduler stored was delivered by running the dispatch pipeline a second time with SkipOutbox() and SkipScheduler() set. Bus middleware registered before the outbox therefore ran twice, and transport and endpoint middleware, such as the RabbitMQ routing key extractor, ran only at delivery. The pipeline now runs once, in the order instrumentation, transport and application middleware, serialization, scheduling, outbox, so everything is applied before the message is stored. The outbox processor and the scheduler workers send the stored envelope straight to the transport and record a failed send on their own span. UseOutboxCore() adds the outbox middleware as a fixed stage after scheduling, so anchors to it no longer depend on registration order. SkipScheduler() and SchedulingMiddlewareFeature are removed, and the scheduling and outbox middleware throw when a dispatch reaches them without an envelope. --- .../Outbox/OutboxProcessor.cs | 15 +- .../Scheduling/ScheduledMessageDispatcher.cs | 22 +- .../Mocha.Outbox/DispatchOutboxMiddleware.cs | 7 +- .../OutboxCoreServiceCollectionExtensions.cs | 12 +- .../Mocha.Outbox/OutboxDispatchMiddlewares.cs | 12 + src/Mocha/src/Mocha.Outbox/ThrowHelper.cs | 7 + .../InMemoryScheduledMessageWorker.cs | 20 +- .../Mocha/Abstractions/IMessageBusBuilder.cs | 2 +- .../Builder/MessageBusBuilder.Middlewares.cs | 2 +- .../Builder/MessageBusBuilderExtensions.cs | 4 - .../src/Mocha/Endpoints/DispatchEndpoint.cs | 12 +- .../src/Mocha/Middlewares/DispatchContext.cs | 40 ++++ .../Redelivery/ReceiveRedeliveryMiddleware.cs | 6 - .../Outbox/OutboxDispatchStageFeature.cs | 8 + .../DispatchSchedulingMiddleware.cs | 15 +- .../SchedulingDispatchContextExtensions.cs | 20 -- .../Scheduling/SchedulingMiddlewareFeature.cs | 37 --- src/Mocha/src/Mocha/ThrowHelper.cs | 3 + .../Helpers/ScriptedDispatch.cs | 42 +++- .../PostgresOutboxExpirationTests.cs | 40 +++- .../PostgresOutboxRetryTests.cs | 36 ++- ...PostgresScheduledMessageDispatcherTests.cs | 5 +- .../PostgresSchedulingIntegrationTests.cs | 157 +++++++++++-- .../Outbox/OutboxMiddlewareAnchorTests.cs | 213 ++++++++++++++++++ .../DispatchSchedulingMiddlewareTests.cs | 109 ++++----- ...chedulingDispatchContextExtensionsTests.cs | 21 -- .../SchedulingMiddlewareIntegrationTests.cs | 39 ---- .../Scheduling/InMemorySchedulingTests.cs | 123 +++++++--- 28 files changed, 750 insertions(+), 279 deletions(-) create mode 100644 src/Mocha/src/Mocha.Outbox/OutboxDispatchMiddlewares.cs create mode 100644 src/Mocha/src/Mocha.Outbox/ThrowHelper.cs create mode 100644 src/Mocha/src/Mocha/Outbox/OutboxDispatchStageFeature.cs delete mode 100644 src/Mocha/src/Mocha/Scheduling/SchedulingDispatchContextExtensions.cs delete mode 100644 src/Mocha/src/Mocha/Scheduling/SchedulingMiddlewareFeature.cs create mode 100644 src/Mocha/test/Mocha.Tests/Outbox/OutboxMiddlewareAnchorTests.cs delete mode 100644 src/Mocha/test/Mocha.Tests/Scheduling/SchedulingDispatchContextExtensionsTests.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs index c5e80611836..ea93d571887 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs @@ -381,13 +381,16 @@ private async ValueTask SendAsync( { await using var scope = _services.CreateAsyncScope(); - context.Initialize(scope.ServiceProvider, endpoint, _runtime, messageType, cancellationToken); + context.InitializeFromEnvelope( + scope.ServiceProvider, endpoint, _runtime, messageType, envelope, cancellationToken); - context.SkipOutbox(); - - context.Envelope = envelope; - - await endpoint.ExecuteAsync(context); + await endpoint.DispatchInternalAsync(context); + } + catch (Exception ex) + { + activity?.AddException(ex); + activity?.SetStatus(ActivityStatusCode.Error); + throw; } finally { diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs index 19896afe690..a80f189e864 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Scheduling/ScheduledMessageDispatcher.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; -using Mocha.Outbox; using Npgsql; using NpgsqlTypes; @@ -388,14 +387,21 @@ private async ValueTask SendAsync( { await using var scope = _services.CreateAsyncScope(); - context.Initialize(scope.ServiceProvider, endpoint, _runtime, messageType, cancellationToken); + context.InitializeFromEnvelope( + scope.ServiceProvider, + endpoint, + _runtime, + messageType, + envelope, + cancellationToken); - context.SkipScheduler(); - context.SkipOutbox(); - - context.Envelope = envelope; - - await endpoint.ExecuteAsync(context); + await endpoint.DispatchInternalAsync(context); + } + catch (Exception ex) + { + activity?.AddException(ex); + activity?.SetStatus(ActivityStatusCode.Error); + throw; } finally { diff --git a/src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs b/src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs index eafb186c281..62b29185f14 100644 --- a/src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs +++ b/src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs @@ -20,6 +20,7 @@ public sealed class DispatchOutboxMiddleware /// The current dispatch context containing the message envelope and metadata. /// The next middleware delegate in the dispatch pipeline. /// A value task that completes when the message has been persisted or forwarded. + /// A message to persist has no envelope. public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate next) { var feature = context.Features.GetOrSet(); @@ -36,10 +37,12 @@ and not MessageKind.Reply else { var outbox = context.Services.GetRequiredService(); - if (context.Envelope is not null) + if (context.Envelope is null) { - await outbox.PersistAsync(context.Envelope, context.CancellationToken); + throw ThrowHelper.EnvelopeNotSet(); } + + await outbox.PersistAsync(context.Envelope, context.CancellationToken); } } diff --git a/src/Mocha/src/Mocha.Outbox/OutboxCoreServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.Outbox/OutboxCoreServiceCollectionExtensions.cs index 4ec2018c7ee..ab3ba7940eb 100644 --- a/src/Mocha/src/Mocha.Outbox/OutboxCoreServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.Outbox/OutboxCoreServiceCollectionExtensions.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Mocha.Outbox; @@ -19,9 +20,18 @@ public static class OutboxCoreServiceCollectionExtensions /// The same instance for chaining. public static IMessageBusHostBuilder UseOutboxCore(this IMessageBusHostBuilder builder) { + if (builder.Services.Any(d => d.ServiceType == typeof(OutboxCoreRegistration))) + { + return builder; + } + + builder.Services.AddSingleton(); builder.Services.TryAddSingleton(); - builder.ConfigureMessageBus(x => x.UseDispatch(DispatchOutboxMiddleware.Create())); + builder.ConfigureMessageBus(static b => b.ConfigureFeature( + static features => features.Set(new OutboxDispatchStageFeature(OutboxDispatchMiddlewares.Outbox)))); return builder; } + + private sealed class OutboxCoreRegistration; } diff --git a/src/Mocha/src/Mocha.Outbox/OutboxDispatchMiddlewares.cs b/src/Mocha/src/Mocha.Outbox/OutboxDispatchMiddlewares.cs new file mode 100644 index 00000000000..74b37dee4ae --- /dev/null +++ b/src/Mocha/src/Mocha.Outbox/OutboxDispatchMiddlewares.cs @@ -0,0 +1,12 @@ +namespace Mocha.Outbox; + +/// +/// Provides the outbox dispatch middleware configuration. Use its key to place middleware relative to it. +/// +public static class OutboxDispatchMiddlewares +{ + /// + /// Persists outgoing messages in the outbox instead of sending them to the transport. + /// + public static readonly DispatchMiddlewareConfiguration Outbox = DispatchOutboxMiddleware.Create(); +} diff --git a/src/Mocha/src/Mocha.Outbox/ThrowHelper.cs b/src/Mocha/src/Mocha.Outbox/ThrowHelper.cs new file mode 100644 index 00000000000..632a590169b --- /dev/null +++ b/src/Mocha/src/Mocha.Outbox/ThrowHelper.cs @@ -0,0 +1,7 @@ +namespace Mocha.Outbox; + +internal static class ThrowHelper +{ + public static InvalidOperationException EnvelopeNotSet() + => new("Envelope is not set"); +} diff --git a/src/Mocha/src/Mocha.Transport.InMemory/Scheduling/InMemoryScheduledMessageWorker.cs b/src/Mocha/src/Mocha.Transport.InMemory/Scheduling/InMemoryScheduledMessageWorker.cs index 853e74c0aa4..290309dc60c 100644 --- a/src/Mocha/src/Mocha.Transport.InMemory/Scheduling/InMemoryScheduledMessageWorker.cs +++ b/src/Mocha/src/Mocha.Transport.InMemory/Scheduling/InMemoryScheduledMessageWorker.cs @@ -4,16 +4,13 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; -using Mocha.Outbox; -using Mocha.Scheduling; using Mocha.Threading; namespace Mocha.Transport.InMemory.Scheduling; /// /// A hosted background worker that drains due entries from the in-memory scheduled message store and -/// dispatches them through the normal endpoint pipeline. It sleeps on the store's dedicated signal -/// until the next entry is due. +/// sends them to the transport. It sleeps on the store's dedicated signal until the next entry is due. /// internal sealed class InMemoryScheduledMessageWorker( IServiceProvider services, @@ -135,12 +132,15 @@ private async Task DispatchAsync(ScheduledEntry entry, CancellationToken cancell { await using var scope = services.CreateAsyncScope(); - context.Initialize(scope.ServiceProvider, endpoint, runtime, messageType, cancellationToken); - context.SkipScheduler(); - context.SkipOutbox(); - context.Envelope = envelope; + context.InitializeFromEnvelope( + scope.ServiceProvider, + endpoint, + runtime, + messageType, + envelope, + cancellationToken); - await endpoint.ExecuteAsync(context); + await endpoint.DispatchInternalAsync(context); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -148,6 +148,8 @@ private async Task DispatchAsync(ScheduledEntry entry, CancellationToken cancell } catch (Exception ex) { + activity?.AddException(ex); + activity?.SetStatus(ActivityStatusCode.Error); logger.ScheduledMessageDispatchFailed(entry.Id, ex); } finally diff --git a/src/Mocha/src/Mocha/Abstractions/IMessageBusBuilder.cs b/src/Mocha/src/Mocha/Abstractions/IMessageBusBuilder.cs index dd545b7501e..31701630be7 100644 --- a/src/Mocha/src/Mocha/Abstractions/IMessageBusBuilder.cs +++ b/src/Mocha/src/Mocha/Abstractions/IMessageBusBuilder.cs @@ -127,7 +127,7 @@ IMessageBusBuilder AddBatchHandler( /// /// Adds a dispatch middleware configuration to the dispatch pipeline. /// When neither nor is specified, the - /// middleware is appended to the end of the pipeline. + /// middleware runs before serialization. /// When is specified, the middleware is inserted immediately before /// the middleware with the given key. /// When is specified, the middleware is inserted immediately after diff --git a/src/Mocha/src/Mocha/Builder/MessageBusBuilder.Middlewares.cs b/src/Mocha/src/Mocha/Builder/MessageBusBuilder.Middlewares.cs index 8d2ebbaa1f9..456bd37dac9 100644 --- a/src/Mocha/src/Mocha/Builder/MessageBusBuilder.Middlewares.cs +++ b/src/Mocha/src/Mocha/Builder/MessageBusBuilder.Middlewares.cs @@ -113,7 +113,7 @@ public IMessageBusBuilder UseReceive( /// /// Adds a dispatch middleware to the bus-level outbound pipeline, applied to all transports. /// When neither nor is specified, the - /// middleware is appended to the end of the pipeline. + /// middleware runs before serialization. /// When is specified, the middleware is inserted immediately before /// the middleware with the given key. /// When is specified, the middleware is inserted immediately after diff --git a/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs b/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs index c73441557ad..a54731747f4 100644 --- a/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs +++ b/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs @@ -43,10 +43,6 @@ internal static void AddDefaults(this MessageBusBuilder builder) builder.UseReceive(ReceiveMiddlewares.MessageTypeSelection); builder.UseReceive(ReceiveMiddlewares.Routing); - builder.UseDispatch(DispatchMiddlewares.Instrumentation); - builder.UseDispatch(DispatchMiddlewares.Serialization); - builder.UseDispatch(DispatchMiddlewares.Scheduling, after: "Serialization"); - builder.AddConcurrencyLimiter(o => o.MaxConcurrency = Environment.ProcessorCount * 2); builder.AddMessage(x => diff --git a/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs b/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs index 4e6d66a4d15..85b20f829dc 100644 --- a/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs +++ b/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using Mocha.Middlewares; +using Mocha.Outbox; namespace Mocha; @@ -196,6 +197,7 @@ public void Complete(IMessagingConfigurationContext context) { OnComplete(context, Configuration); _timeProvider = context.Services.GetTimeProvider(); + var outboxStage = context.Features.Get(); var pipeline = MiddlewareCompiler.CompileDispatch( new DispatchMiddlewareFactoryContext @@ -205,7 +207,13 @@ public void Complete(IMessagingConfigurationContext context) Transport = Transport }, DispatchInternalAsync, - [Transport.GetDispatchMiddlewares(), Configuration.DispatchMiddlewares], + [ + [DispatchMiddlewares.Instrumentation], + Transport.GetDispatchMiddlewares(), + Configuration.DispatchMiddlewares, + [DispatchMiddlewares.Serialization, DispatchMiddlewares.Scheduling], + outboxStage is null ? [] : [outboxStage.Middleware] + ], [Transport.GetDispatchPipelineModifiers(), Configuration.DispatchPipelineModifiers]); Volatile.Write(ref _pipeline, pipeline); @@ -254,7 +262,7 @@ public DispatchEndpointDescription Describe() /// A that completes when the transport-level send is finished. protected abstract ValueTask DispatchAsync(IDispatchContext context); - private ValueTask DispatchInternalAsync(IDispatchContext context) + internal ValueTask DispatchInternalAsync(IDispatchContext context) { var sentAt = context.SentAt ?? context.Envelope?.SentAt ?? _timeProvider.GetUtcNow(); context.SentAt = sentAt; diff --git a/src/Mocha/src/Mocha/Middlewares/DispatchContext.cs b/src/Mocha/src/Mocha/Middlewares/DispatchContext.cs index d57c2bf0352..40b1ba4455c 100644 --- a/src/Mocha/src/Mocha/Middlewares/DispatchContext.cs +++ b/src/Mocha/src/Mocha/Middlewares/DispatchContext.cs @@ -240,4 +240,44 @@ public void Initialize( _features.Initialize(); } + + internal void InitializeFromEnvelope( + IServiceProvider services, + DispatchEndpoint endpoint, + IMessagingRuntime runtime, + MessageType? messageType, + MessageEnvelope envelope, + CancellationToken cancellationToken) + { + Services = services; + Endpoint = endpoint; + Transport = endpoint.Transport; + Runtime = runtime; + Host = envelope.Host ?? runtime.Host; + CancellationToken = cancellationToken; + MessageType = messageType; + ContentType = MessageContentType.Parse(envelope.ContentType); + MessageId = envelope.MessageId; + CorrelationId = envelope.CorrelationId; + ConversationId = envelope.ConversationId; + CausationId = envelope.CausationId; + SourceAddress = ParseAddress(envelope.SourceAddress); + DestinationAddress = ParseAddress(envelope.DestinationAddress); + ResponseAddress = ParseAddress(envelope.ResponseAddress); + FaultAddress = ParseAddress(envelope.FaultAddress); + SentAt = envelope.SentAt; + DeliverBy = envelope.DeliverBy; + ScheduledTime = envelope.ScheduledTime; + Envelope = envelope; + + if (envelope.Headers is { } headers) + { + _headers.AddRange(headers); + } + + _features.Initialize(); + } + + private static Uri? ParseAddress(string? address) + => Uri.TryCreate(address, UriKind.Absolute, out var parsed) ? parsed : null; } diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/Redelivery/ReceiveRedeliveryMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/Redelivery/ReceiveRedeliveryMiddleware.cs index 13c7dd7435f..13ae7593fbf 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/Redelivery/ReceiveRedeliveryMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/Redelivery/ReceiveRedeliveryMiddleware.cs @@ -1,7 +1,6 @@ using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Mocha.Features; using Mocha.Middlewares; using Mocha.Scheduling; @@ -113,11 +112,6 @@ private async ValueTask DispatchRedeliveryAsync( { dispatchContext.ScheduledTime = scheduledTime; } - else - { - // No scheduling store available for this transport, fall back to immediate redelivery. - dispatchContext.Features.Configure(f => f.SkipScheduler = true); - } await dispatchEndpoint.ExecuteAsync(dispatchContext); return isScheduled; diff --git a/src/Mocha/src/Mocha/Outbox/OutboxDispatchStageFeature.cs b/src/Mocha/src/Mocha/Outbox/OutboxDispatchStageFeature.cs new file mode 100644 index 00000000000..82769bf47c9 --- /dev/null +++ b/src/Mocha/src/Mocha/Outbox/OutboxDispatchStageFeature.cs @@ -0,0 +1,8 @@ +namespace Mocha.Outbox; + +/// +/// Adds the outbox middleware to the dispatch pipeline of every dispatch endpoint of the bus, directly after +/// . +/// +/// The outbox middleware configuration. +internal sealed record OutboxDispatchStageFeature(DispatchMiddlewareConfiguration Middleware); diff --git a/src/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs b/src/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs index 8ef6410b7c8..88099b3af4b 100644 --- a/src/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs +++ b/src/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs @@ -9,8 +9,7 @@ namespace Mocha.Scheduling; /// to the scheduled message store instead of forwarding them to the next pipeline stage. /// /// -/// Messages without a and dispatches marked with -/// pass through to the next middleware. +/// Messages without a pass through to the next middleware. /// Scheduled messages are routed to the registered store for the current transport. /// public sealed class DispatchSchedulingMiddleware @@ -22,6 +21,7 @@ public sealed class DispatchSchedulingMiddleware /// The current dispatch context containing the message envelope and metadata. /// The next middleware delegate in the dispatch pipeline. /// A value task that completes when the message has been persisted or forwarded. + /// A scheduled message has no envelope. public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate next) { if (context.ScheduledTime is not { } scheduledTime) @@ -30,18 +30,9 @@ public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate ne return; } - var feature = context.Features.GetOrSet(); - - if (feature.SkipScheduler) - { - await next(context); - return; - } - if (context.Envelope is null) { - await next(context); - return; + throw ThrowHelper.EnvelopeNotSet(); } if (context.Envelope.ScheduledTime != scheduledTime) diff --git a/src/Mocha/src/Mocha/Scheduling/SchedulingDispatchContextExtensions.cs b/src/Mocha/src/Mocha/Scheduling/SchedulingDispatchContextExtensions.cs deleted file mode 100644 index 91e10a8b0d1..00000000000 --- a/src/Mocha/src/Mocha/Scheduling/SchedulingDispatchContextExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Mocha.Features; -using Mocha.Middlewares; - -namespace Mocha.Scheduling; - -/// -/// Provides convenience methods on for scheduling control. -/// -public static class SchedulingDispatchContextExtensions -{ - /// - /// Marks the current dispatch context to bypass the scheduler, causing the message to be sent - /// directly to the transport. - /// - /// The dispatch context to modify. - public static void SkipScheduler(this IDispatchContext context) - { - context.Features.Configure(feature => feature.SkipScheduler = true); - } -} diff --git a/src/Mocha/src/Mocha/Scheduling/SchedulingMiddlewareFeature.cs b/src/Mocha/src/Mocha/Scheduling/SchedulingMiddlewareFeature.cs deleted file mode 100644 index e114f8ac94b..00000000000 --- a/src/Mocha/src/Mocha/Scheduling/SchedulingMiddlewareFeature.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Mocha.Features; - -namespace Mocha.Scheduling; - -/// -/// A pooled feature that controls whether the scheduling middleware should be bypassed for a given dispatch. -/// -/// -/// Attach this feature to the dispatch context's feature collection and set -/// to true to send the message directly without persisting it to the scheduled message store. -/// The feature is pooled and automatically reset between uses. -/// -public sealed class SchedulingMiddlewareFeature : IPooledFeature -{ - /// - /// Gets or sets a value indicating whether the scheduling persistence step should be skipped - /// for the current dispatch. - /// - public bool SkipScheduler { get; set; } - - /// - /// Initializes the feature from the pool, resetting to false. - /// - /// The initialization state provided by the feature pool (unused). - public void Initialize(object state) - { - SkipScheduler = false; - } - - /// - /// Resets the feature state before returning it to the pool, clearing to false. - /// - public void Reset() - { - SkipScheduler = false; - } -} diff --git a/src/Mocha/src/Mocha/ThrowHelper.cs b/src/Mocha/src/Mocha/ThrowHelper.cs index b7aae2780a0..ce1be1001bd 100644 --- a/src/Mocha/src/Mocha/ThrowHelper.cs +++ b/src/Mocha/src/Mocha/ThrowHelper.cs @@ -212,6 +212,9 @@ public static Exception DispatchSerializerNotFound(string contentType, string me => new InvalidOperationException( $"No serializer found for content type {contentType} and message type {messageType}"); + public static Exception EnvelopeNotSet() + => new InvalidOperationException("Envelope is not set"); + public static Exception ScheduledDispatchUnsupported(Type transportType) => new NotSupportedException( "Scheduled dispatch is not supported for transport " diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ScriptedDispatch.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ScriptedDispatch.cs index 9a373b892da..17c03f02284 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ScriptedDispatch.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ScriptedDispatch.cs @@ -4,7 +4,8 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; /// -/// A dispatch middleware in front of the transport that lets a test decide what each dispatch attempt does. +/// A dispatch endpoint in front of the transport that lets a test decide what each dispatch attempt does. +/// It sees the dispatches of the outbox relay and the scheduler, which do not run the dispatch middleware. /// internal sealed class ScriptedDispatch(Func onDispatch) { @@ -15,11 +16,21 @@ internal sealed class ScriptedDispatch(Func onDispat /// public ConcurrentQueue Accepted { get; } = new(); - public DispatchMiddlewareConfiguration Middleware - => new((_, next) => context => DispatchAsync(context, next), "ScriptedDispatch"); - public int AttemptsOf(string messageId) => _attempts.GetValueOrDefault(messageId); + /// + /// Replaces the endpoint of the started that publishes + /// with an endpoint that runs the script for each dispatch to its address. + /// + public void InterceptPublishEndpoint(MessagingRuntime runtime) + { + var endpoint = runtime.GetPublishEndpoint(runtime.GetMessageType(typeof(TMessage))); + var scripted = new ScriptedDispatchEndpoint(this, endpoint); + scripted.Initialize(runtime, new DispatchEndpointConfiguration { Name = endpoint.Name }); + scripted.Complete(runtime); + runtime.Endpoints.Remove(endpoint); + } + private ValueTask DispatchAsync(IDispatchContext context, DispatchDelegate next) { var messageId = context.Envelope!.MessageId!; @@ -27,6 +38,29 @@ private ValueTask DispatchAsync(IDispatchContext context, DispatchDelegate next) return onDispatch(new DispatchAttempt(this, context, next, messageId, number)); } + + // Takes over the address of the replaced endpoint and passes each dispatch to the script, which can hand it + // to the replaced endpoint's transport. + private sealed class ScriptedDispatchEndpoint(ScriptedDispatch dispatch, DispatchEndpoint endpoint) + : DispatchEndpoint(endpoint.Transport) + { + protected override void OnInitialize( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + Address = endpoint.Address; + Destination = endpoint.Destination; + } + + protected override void OnComplete( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + } + + protected override ValueTask DispatchAsync(IDispatchContext context) + => dispatch.DispatchAsync(context, endpoint.DispatchInternalAsync); + } } /// diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs index 343f94b7a66..b3abc21fe7c 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs @@ -88,6 +88,10 @@ public async Task ProcessAsync_Should_DiscardExpiredMessage_When_DeadlinePassesA // act await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + // the failed delivery is made due at once instead of after the retry delay + await MessageRows.WaitForOutboxTimesSentAsync(connectionString, id, 1, s_timeout, TestToken); + await MessageRows.MakeOutboxDueAsync(connectionString, TestToken); + provider.GetRequiredService().Set(); var remainingAttempts = await MessageRows.WaitForOutboxRetryAsync( connectionString, id, s_timeout, TestToken); @@ -123,7 +127,6 @@ private static async Task CreateProviderAsync( var services = new ServiceCollection(); services.AddSingleton(clock); services.AddSingleton(recorder); - services.AddSingleton(recorder); services.AddDbContext(options => options.UseTestNpgsql(connectionString)); var builder = services.AddMessageBus(); builder.AddEntityFramework(options => options.UsePostgresOutbox()); @@ -131,7 +134,13 @@ private static async Task CreateProviderAsync( builder.AddInMemory(); var provider = services.BuildServiceProvider(); - await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(TestToken); + var endpoint = runtime.GetPublishEndpoint(runtime.GetMessageType(typeof(PendingEvent))); + var recordingEndpoint = new RecordingDispatchEndpoint(endpoint, recorder); + recordingEndpoint.Initialize(runtime, new DispatchEndpointConfiguration { Name = endpoint.Name }); + recordingEndpoint.Complete(runtime); + runtime.Endpoints.Remove(endpoint); await using var scope = provider.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); return provider; @@ -151,7 +160,7 @@ public ValueTask HandleAsync(PendingEvent message, CancellationToken cancellatio } } - public sealed class DeliveryRecorder : MessagingDiagnosticEventListener + public sealed class DeliveryRecorder { private int _attempts; @@ -162,14 +171,35 @@ public sealed class DeliveryRecorder : MessagingDiagnosticEventListener public TaskCompletionSource Delivered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public override IDisposable Dispatch(IDispatchContext context) + public void RecordAttempt() { if (Interlocked.Increment(ref _attempts) == 1) { OnFirstAttempt?.Invoke(); } + } + } + + private sealed class RecordingDispatchEndpoint(DispatchEndpoint endpoint, DeliveryRecorder recorder) + : DispatchEndpoint(endpoint.Transport) + { + protected override void OnInitialize( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + Address = endpoint.Address; + Destination = endpoint.Destination; + } - return EmptyScope; + protected override void OnComplete( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { } + + protected override ValueTask DispatchAsync(IDispatchContext context) + { + recorder.RecordAttempt(); + return endpoint.DispatchInternalAsync(context); } } } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs index 2ee9f9aebd1..0734846c2d0 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs @@ -63,6 +63,37 @@ public async Task ProcessAsync_Should_DispatchMessageAgain_When_RetryDelayElapse Assert.Equal(["A"], dispatch.Accepted); } + [Fact] + public async Task ProcessAsync_Should_DispatchSameMessageAgain_When_SendFailsAfterTransportAccepted() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var dispatch = new ScriptedDispatch(static async attempt => + { + await attempt.SendAsync(); + + if (attempt.Number == 1) + { + throw new InvalidOperationException("The acknowledgement was lost."); + } + }); + await using var provider = await CreateProviderAsync(connectionString, dispatch); + var id = await MessageRows.InsertOutboxAsync(connectionString, CreateEnvelope(provider, "A"), TestToken); + long remaining; + + // act + await using (StartProcessor(provider)) + { + await MessageRows.WaitForOutboxTimesSentAsync(connectionString, id, 1, s_timeout, TestToken); + await MessageRows.MakeOutboxDueAsync(connectionString, TestToken); + remaining = await MessageRows.WaitForOutboxCountAsync(connectionString, 0, s_timeout, TestToken); + } + + // assert + Assert.Equal(0, remaining); + Assert.Equal(["A", "A"], dispatch.Accepted); + } + [Fact] public async Task ProcessAsync_Should_ScheduleRetryTenSecondsAhead_When_DispatchFails() { @@ -261,10 +292,11 @@ private static async Task CreateProviderAsync( t.DeclareQueue("retry"); t.DispatchEndpoint("retry").ToQueue("retry").Publish(); }); - builder.ConfigureMessageBus(b => b.UseDispatch(dispatch.Middleware, after: "Serialization")); var provider = services.BuildServiceProvider(); - await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(TestToken); + dispatch.InterceptPublishEndpoint(runtime); await using var scope = provider.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); return provider; diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs index 25144aa6a70..1f2277d8024 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresScheduledMessageDispatcherTests.cs @@ -221,10 +221,11 @@ private static async Task CreateProviderAsync(string connection t.DeclareQueue("scheduled"); t.DispatchEndpoint("scheduled").ToQueue("scheduled").Publish(); }); - builder.ConfigureMessageBus(b => b.UseDispatch(dispatch.Middleware, after: "Serialization")); var provider = services.BuildServiceProvider(); - await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(TestToken); + dispatch.InterceptPublishEndpoint(runtime); await using var scope = provider.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); return provider; diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSchedulingIntegrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSchedulingIntegrationTests.cs index 5d2e3c79978..6df68330f43 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSchedulingIntegrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSchedulingIntegrationTests.cs @@ -1,8 +1,10 @@ using System.Collections.Concurrent; +using System.Text; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Time.Testing; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Middlewares; using Mocha.Scheduling; @@ -36,6 +38,62 @@ await bus.PublishAsync( Assert.Equal("hello", received.Payload); } + [Fact] + public async Task SchedulePublishAsync_Should_StorePreparedEnvelope_When_DispatchMiddlewareRuns() + { + // arrange + var probe = new PreparationProbe(); + var time = new FakeTimeProvider(new DateTimeOffset(2050, 1, 1, 12, 0, 0, TimeSpan.Zero)); + await using var provider = await CreatePreparingProviderAsync(probe, time); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.SchedulePublishAsync( + new TestEvent { Payload = "original" }, + DateTimeOffset.UtcNow.AddSeconds(-1), + TestContext.Current.CancellationToken); + var json = await db.Set() + .Select(message => message.Envelope) + .SingleAsync(TestContext.Current.CancellationToken); + var stored = MessageEnvelopeReader.Parse(Encoding.UTF8.GetBytes(json.RootElement.GetRawText())); + + // assert + Assert.Equal(1, probe.PreparationCalls); + Assert.Equal(1, probe.ObservationCalls); + Assert.Null(stored.SentAt); + Assert.Equal("prepared", JsonSerializer.Deserialize(stored.Body.Span)!.Payload); + Assert.Equal("stored", (string?)stored.Headers?.GetValue("prepared-header")); + } + + [Fact] + public async Task Scheduler_Should_DeliverPreparedEnvelope_When_DispatchMiddlewareAlreadyRan() + { + // arrange + var probe = new PreparationProbe(); + var time = new FakeTimeProvider(new DateTimeOffset(2050, 1, 1, 12, 0, 0, TimeSpan.Zero)); + await using var provider = await CreatePreparingProviderAsync(probe, time); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + await bus.SchedulePublishAsync( + new TestEvent { Payload = "original" }, + DateTimeOffset.UtcNow.AddSeconds(-1), + TestContext.Current.CancellationToken); + + // act + time.Advance(TimeSpan.FromMinutes(11)); + await using var host = await MessagingTestHost.StartAsync(provider, TestContext.Current.CancellationToken); + var delivered = await probe.Received.Task.WaitAsync(s_timeout, TestContext.Current.CancellationToken); + + // assert + Assert.Equal(1, probe.PreparationCalls); + Assert.Equal(1, probe.ObservationCalls); + Assert.Equal("prepared", JsonSerializer.Deserialize(delivered.Body.Span)!.Payload); + Assert.Equal("stored", (string?)delivered.Headers?.GetValue("prepared-header")); + Assert.Equal(time.GetUtcNow(), delivered.SentAt); + } + [Fact] public async Task Scheduler_Should_DispatchAllMessages_When_MultipleMessagesScheduled() { @@ -181,12 +239,9 @@ await bus.PublishAsync( [Fact] public async Task Scheduler_Should_RecordLastError_When_DispatchFails() { - // Arrange - use a dispatch middleware that always throws AFTER the scheduling middleware. - // During initial publish the scheduling middleware intercepts (never calling next), - // so the throwing middleware is inactive. During re-dispatch from the worker the - // scheduling middleware is skipped, causing the throwing middleware to fire. + // arrange var recorder = new MessageRecorder(); - await using var env = await CreateBusWithSchedulingAsync(recorder, AddFailingDispatchMiddleware); + await using var env = await CreateBusWithSchedulingAsync(recorder, AddInvalidReplyDestination); using (var scope = env.Provider.CreateScope()) { @@ -213,14 +268,14 @@ await bus.PublishAsync( if (rows.Count > 0 && rows[0] is not null) { - // Assert - parse the JSON error + // assert using var doc = JsonDocument.Parse(rows[0]!); - Assert.True( - doc.RootElement.TryGetProperty("message", out _), - "last_error should contain 'message'"); - Assert.True( - doc.RootElement.TryGetProperty("exceptionType", out _), - "last_error should contain 'exceptionType'"); + Assert.Equal( + "Cannot determine topic or queue name from destination address memory://localhost/q/missing", + doc.RootElement.GetProperty("message").GetString()); + Assert.Equal( + "System.InvalidOperationException", + doc.RootElement.GetProperty("exceptionType").GetString()); return; } } @@ -231,9 +286,9 @@ await bus.PublishAsync( [Fact] public async Task Scheduler_Should_IncrementTimesSent_When_DispatchFails() { - // Arrange - same failing middleware approach as RecordLastError test + // arrange var recorder = new MessageRecorder(); - await using var env = await CreateBusWithSchedulingAsync(recorder, AddFailingDispatchMiddleware); + await using var env = await CreateBusWithSchedulingAsync(recorder, AddInvalidReplyDestination); using (var scope = env.Provider.CreateScope()) { @@ -449,13 +504,17 @@ public async Task CancelScheduledMessageAsync_Should_ReturnFalse_When_InvalidTok Assert.False(cancelled); } - private static void AddFailingDispatchMiddleware(IMessageBusHostBuilder builder) + private static void AddInvalidReplyDestination(IMessageBusHostBuilder builder) { - builder.ConfigureMessageBus(h => - h.UseDispatch(new DispatchMiddlewareConfiguration( - static (_, _) => static _ => - throw new InvalidOperationException("Simulated dispatch failure"), - "FailingTransport"))); + builder.ConfigureMessageBus(bus => + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + context.Headers.Set("message-kind", "reply"); + context.DestinationAddress = new Uri("memory://localhost/q/missing"); + return next(context); + }, + "InvalidReplyDestination"))); } [Fact] @@ -571,6 +630,64 @@ private async Task CreateBusWithSchedulingAsync( return new TestEnvironment(provider, hostedServices, connectionString); } + private async Task CreatePreparingProviderAsync(PreparationProbe probe, FakeTimeProvider time) + { + var connectionString = await fixture.CreateDatabaseAsync(); + var services = new ServiceCollection(); + services.AddSingleton(new MessageRecorder()); + services.AddSingleton(time); + services.AddSingleton(new ResilientSchedulerSignal()); + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework(options => options.UsePostgresScheduling()); + builder.AddEventHandler(); + builder.ConfigureMessageBus(bus => + { + bus.AddTransport(new InMemoryMessagingTransport(static _ => { })); + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + probe.PreparationCalls++; + context.Message = new TestEvent { Payload = "prepared" }; + context.Headers.Set("prepared-header", "stored"); + return next(context); + }, + "PrepareScheduledMessage")); + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + probe.ObservationCalls++; + return next(context); + }, + "ObserveScheduledMessage"), after: "PrepareScheduledMessage"); + bus.UseReceive(new ReceiveMiddlewareConfiguration( + (_, next) => async context => + { + var envelope = MessageEnvelope.CopyWithOwnedBody(context.Envelope!); + await next(context); + probe.Received.TrySetResult(envelope); + }, + "CaptureScheduledMessage")); + }); + var provider = services.BuildServiceProvider(); + await ((MessagingRuntime)provider.GetRequiredService()) + .StartAsync(TestContext.Current.CancellationToken); + using var scope = provider.CreateScope(); + await scope.ServiceProvider.GetRequiredService() + .Database.EnsureCreatedAsync(TestContext.Current.CancellationToken); + return provider; + } + + private sealed class PreparationProbe + { + public int PreparationCalls { get; set; } + + public int ObservationCalls { get; set; } + + public TaskCompletionSource Received { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + } + public sealed class TestEvent { public required string Payload { get; init; } diff --git a/src/Mocha/test/Mocha.Tests/Outbox/OutboxMiddlewareAnchorTests.cs b/src/Mocha/test/Mocha.Tests/Outbox/OutboxMiddlewareAnchorTests.cs new file mode 100644 index 00000000000..037f2757c47 --- /dev/null +++ b/src/Mocha/test/Mocha.Tests/Outbox/OutboxMiddlewareAnchorTests.cs @@ -0,0 +1,213 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.Tests.Outbox; + +public class OutboxMiddlewareAnchorTests +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PublishAsync_Should_RunMiddlewareAnchoredAfterScheduling_When_MessageIsStored( + bool anchorRegisteredFirst) + { + // arrange + var outbox = new CapturingOutbox(); + await using var provider = await CreateProviderAsync( + outbox, + anchorRegisteredFirst, + bus => bus.UseDispatch(SetHeader("after-scheduling"), after: DispatchMiddlewares.Scheduling.Key), + static _ => { }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new AnchorEvent { Payload = "stored" }, CancellationToken.None); + + // assert + var envelope = Assert.Single(outbox.Envelopes); + Assert.Equal("after-scheduling", envelope.Headers!.GetValue("x-anchor")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PublishAsync_Should_RunMiddlewareAnchoredBeforeOutbox_When_MessageIsStored( + bool anchorRegisteredFirst) + { + // arrange + var outbox = new CapturingOutbox(); + await using var provider = await CreateProviderAsync( + outbox, + anchorRegisteredFirst, + bus => bus.UseDispatch(SetHeader("before-outbox"), before: OutboxDispatchMiddlewares.Outbox.Key), + static _ => { }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new AnchorEvent { Payload = "stored" }, CancellationToken.None); + + // assert + var envelope = Assert.Single(outbox.Envelopes); + Assert.Equal("before-outbox", envelope.Headers!.GetValue("x-anchor")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PublishAsync_Should_SendDirectly_When_DocumentedSkipOutboxSampleIsRegistered( + bool anchorRegisteredFirst) + { + // arrange + var outbox = new CapturingOutbox(); + var recorder = new MessageRecorder(); + await using var provider = await CreateProviderAsync( + outbox, + anchorRegisteredFirst, + bus => bus.UseDispatch( + new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + if (context.Message is CacheInvalidatedEvent) + { + context.SkipOutbox(); + } + + return next(context); + }, + "SkipOutboxForCacheEvents"), + before: OutboxDispatchMiddlewares.Outbox.Key), + builder => + { + builder.Services.AddSingleton(recorder); + builder.AddEventHandler(); + }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new CacheInvalidatedEvent { Key = "products" }, CancellationToken.None); + await bus.PublishAsync(new AnchorEvent { Payload = "stored" }, CancellationToken.None); + + // assert + Assert.True(await recorder.WaitAsync(s_timeout)); + Assert.Equal("products", ((CacheInvalidatedEvent)Assert.Single(recorder.Messages)).Key); + Assert.Equal( + "stored", + JsonSerializer.Deserialize(Assert.Single(outbox.Envelopes).Body.Span)!.Payload); + } + + [Fact] + public async Task PublishAsync_Should_RejectMessage_When_MiddlewareClearsEnvelopeAfterSerialization() + { + // arrange + var outbox = new CapturingOutbox(); + await using var provider = await CreateProviderAsync( + outbox, + anchorRegisteredFirst: false, + bus => bus.UseDispatch( + new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Envelope = null; + return next(context); + }, + "ClearEnvelope"), + after: DispatchMiddlewares.Serialization.Key), + static _ => { }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + var exception = await Assert.ThrowsAsync(async () => + await bus.PublishAsync(new AnchorEvent { Payload = "cleared" }, CancellationToken.None)); + + // assert + Assert.Equal("Envelope is not set", exception.Message); + Assert.Empty(outbox.Envelopes); + } + + private static DispatchMiddlewareConfiguration SetHeader(string value) + => new( + (_, next) => context => + { + context.Headers.Set("x-anchor", value); + return next(context); + }, + "SetAnchorHeader"); + + private static async Task CreateProviderAsync( + CapturingOutbox outbox, + bool anchorRegisteredFirst, + Action configureAnchor, + Action configure) + { + var services = new ServiceCollection(); + services.AddSingleton(outbox); + var builder = services.AddMessageBus(); + configure(builder); + + if (anchorRegisteredFirst) + { + builder.ConfigureMessageBus(configureAnchor); + builder.UseOutboxCore(); + } + else + { + builder.UseOutboxCore(); + builder.ConfigureMessageBus(configureAnchor); + } + + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(); + try + { + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(CancellationToken.None); + return provider; + } + catch + { + await provider.DisposeAsync(); + throw; + } + } + + public sealed class AnchorEvent + { + public required string Payload { get; init; } + } + + public sealed class CacheInvalidatedEvent + { + public required string Key { get; init; } + } + + public sealed class CacheInvalidatedEventHandler(MessageRecorder recorder) : IEventHandler + { + public ValueTask HandleAsync(CacheInvalidatedEvent message, CancellationToken cancellationToken) + { + recorder.Record(message); + return default; + } + } + + private sealed class CapturingOutbox : IMessageOutbox + { + public ConcurrentBag Envelopes { get; } = []; + + public ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken cancellationToken) + { + Envelopes.Add(MessageEnvelope.CopyWithOwnedBody(envelope)); + return ValueTask.CompletedTask; + } + } +} diff --git a/src/Mocha/test/Mocha.Tests/Scheduling/DispatchSchedulingMiddlewareTests.cs b/src/Mocha/test/Mocha.Tests/Scheduling/DispatchSchedulingMiddlewareTests.cs index c7b8e1e23ff..c5b8f40792d 100644 --- a/src/Mocha/test/Mocha.Tests/Scheduling/DispatchSchedulingMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Tests/Scheduling/DispatchSchedulingMiddlewareTests.cs @@ -1,21 +1,27 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Time.Testing; -using Mocha.Features; using Mocha.Middlewares; using Mocha.Scheduling; +using Mocha.Transport.InMemory; namespace Mocha.Tests.Scheduling; public class DispatchSchedulingMiddlewareTests { [Fact] - public void Create_Should_ReturnMiddleware() + public async Task Create_Should_CallNext_When_MessageIsNotScheduled() { // arrange - DispatchDelegate next = _ => ValueTask.CompletedTask; - var config = DispatchSchedulingMiddleware.Create(); + var nextCalled = false; + DispatchDelegate next = _ => + { + nextCalled = true; + return ValueTask.CompletedTask; + }; + var factoryContext = new DispatchMiddlewareFactoryContext { Services = new ServiceCollection().BuildServiceProvider(), @@ -24,10 +30,11 @@ public void Create_Should_ReturnMiddleware() }; // act - var result = config.Middleware(factoryContext, next); + var pipeline = DispatchSchedulingMiddleware.Create().Middleware(factoryContext, next); + await pipeline(new DispatchContext()); // assert - Assert.NotSame(next, result); + Assert.True(nextCalled); } [Fact] @@ -52,42 +59,32 @@ public async Task InvokeAsync_Should_CallNext_When_ScheduledTimeIsNull() } [Fact] - public async Task InvokeAsync_Should_CallNext_When_SkipSchedulerIsTrue() + public async Task InvokeAsync_Should_CallNext_When_OnlyHistoricalEnvelopeHasScheduledTime() { // arrange - var timeProvider = new FakeTimeProvider(); var middleware = new DispatchSchedulingMiddleware(); - var store = new InMemoryScheduledMessageStore(); - await using var provider = BuildProvider(store); - using var scope = provider.CreateScope(); - - var context = new DispatchContext - { - ScheduledTime = timeProvider.GetUtcNow().AddMinutes(10), - Services = scope.ServiceProvider, - Envelope = new MessageEnvelope { MessageId = "msg-skip" }, - Transport = new StubTransport() - }; - - context.Features.Configure(f => f.SkipScheduler = true); - - var nextCalled = false; - DispatchDelegate next = _ => + var envelope = new MessageEnvelope { - nextCalled = true; - return ValueTask.CompletedTask; + MessageId = "previously-scheduled", + ScheduledTime = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero) }; + var context = new DispatchContext { Envelope = envelope }; + MessageEnvelope? forwarded = null; // act - await middleware.InvokeAsync(context, next); + await middleware.InvokeAsync(context, dispatch => + { + forwarded = dispatch.Envelope; + return default; + }); // assert - Assert.True(nextCalled); - Assert.Empty(store.Entries); + Assert.Same(envelope, forwarded); + Assert.Null(context.ScheduledTime); } [Fact] - public async Task InvokeAsync_Should_PersistToStore_When_ScheduledTimeSetAndNotSkipped() + public async Task InvokeAsync_Should_PersistToStore_When_ScheduledTimeSet() { // arrange var timeProvider = new FakeTimeProvider(); @@ -210,38 +207,48 @@ await Assert.ThrowsAsync(async () => } [Fact] - public async Task InvokeAsync_Should_ForwardToNext_When_EnvelopeIsNull() + public async Task SchedulePublishAsync_Should_RejectMessage_When_MiddlewareClearsEnvelopeAfterSerialization() { // arrange - var timeProvider = new FakeTimeProvider(); - var middleware = new DispatchSchedulingMiddleware(); var store = new InMemoryScheduledMessageStore(); - await using var provider = BuildProvider(store); + var services = new ServiceCollection(); + services.AddScoped(_ => store); + var builder = services.AddMessageBus(); + builder.ConfigureMessageBus(bus => bus.UseDispatch( + new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Envelope = null; + return next(context); + }, + "ClearEnvelope"), + after: DispatchMiddlewares.Serialization.Key)); + builder.AddInMemory(); + services.RemoveAll(); + services.AddSingleton( + new ScheduledMessageStoreRegistration( + typeof(InMemoryMessagingTransport), + InMemoryScheduledMessageStore.TokenPrefix, + typeof(InMemoryScheduledMessageStore))); + await using var provider = services.BuildServiceProvider(); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(CancellationToken.None); using var scope = provider.CreateScope(); - - var context = new DispatchContext - { - ScheduledTime = timeProvider.GetUtcNow().AddMinutes(10), - Services = scope.ServiceProvider, - Envelope = null, - Transport = new StubTransport() - }; - - var nextCalled = false; - DispatchDelegate next = _ => - { - nextCalled = true; - return ValueTask.CompletedTask; - }; + var bus = scope.ServiceProvider.GetRequiredService(); // act - await middleware.InvokeAsync(context, next); + var exception = await Assert.ThrowsAsync(async () => + await bus.SchedulePublishAsync( + new ScheduledEvent("cleared"), + DateTimeOffset.UtcNow.AddMinutes(10), + CancellationToken.None)); // assert - Assert.True(nextCalled); + Assert.Equal("Envelope is not set", exception.Message); Assert.Empty(store.Entries); } + public sealed record ScheduledEvent(string Value); + private static ServiceProvider BuildProvider(InMemoryScheduledMessageStore store) { var services = new ServiceCollection(); diff --git a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingDispatchContextExtensionsTests.cs b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingDispatchContextExtensionsTests.cs deleted file mode 100644 index ad7d96785ee..00000000000 --- a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingDispatchContextExtensionsTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Mocha.Middlewares; -using Mocha.Scheduling; - -namespace Mocha.Tests; - -public class SchedulingDispatchContextExtensionsTests -{ - [Fact] - public void SkipScheduler_Should_SetFeatureFlag_When_Called() - { - // arrange - var context = new DispatchContext(); - - // act - context.SkipScheduler(); - - // assert - var feature = context.Features.GetOrSet(); - Assert.True(feature.SkipScheduler); - } -} diff --git a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingMiddlewareIntegrationTests.cs b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingMiddlewareIntegrationTests.cs index c3f561f86a2..f577a02829f 100644 --- a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingMiddlewareIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingMiddlewareIntegrationTests.cs @@ -81,45 +81,6 @@ await bus.PublishAsync( Assert.Empty(store.Entries); } - [Fact] - public async Task Scheduling_Should_PassThrough_When_SkipSchedulerSet() - { - var timeProvider = new FakeTimeProvider(); - var store = new InMemoryScheduledMessageStore(); - var recorder = new MessageRecorder(); - await using var provider = await CreateBusWithSchedulingAsync( - store, - b => - { - b.Services.AddSingleton(recorder); - b.AddEventHandler(); - - b.ConfigureMessageBus(h => - h.UseDispatch( - new DispatchMiddlewareConfiguration( - static (_, next) => - ctx => - { - ctx.SkipScheduler(); - return next(ctx); - }, - "SkipSchedulerCheck"), - before: "Scheduling")); - }, - timeProvider); - - using var scope = provider.CreateScope(); - var bus = scope.ServiceProvider.GetRequiredService(); - - await bus.PublishAsync( - new SchedulingTestEvent { Payload = "skip-scheduler" }, - new PublishOptions { ScheduledTime = timeProvider.GetUtcNow().AddSeconds(-1) }, - CancellationToken.None); - - Assert.True(await recorder.WaitAsync(s_timeout), "Message should be delivered to handler"); - Assert.Empty(store.Entries); - } - [Fact] public async Task SchedulePublishAsync_Should_ReturnCancellableResult_When_StoreRegistered() { diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Scheduling/InMemorySchedulingTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Scheduling/InMemorySchedulingTests.cs index e6e101295ad..46afe67d942 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Scheduling/InMemorySchedulingTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Scheduling/InMemorySchedulingTests.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Time.Testing; +using Mocha.Middlewares; namespace Mocha.Transport.InMemory.Tests.Scheduling; @@ -47,6 +48,79 @@ await recorder.WaitAsync(s_deliveryTimeout), Assert.Equal("ping", received.Text); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ScheduledMessage_Should_RunDispatchMiddlewareOnce_When_PublishedOrSent(bool send) + { + // arrange + var recorder = new MessageRecorder(); + var time = new FakeTimeProvider(s_start); + var preparationCalls = 0; + var observationCalls = 0; + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var env = await CreateBusAsync(recorder, time, builder => + { + builder.AddRequestHandler(); + builder.ConfigureMessageBus(bus => + { + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + preparationCalls++; + context.Message = new ScheduledPing { Text = "prepared" }; + context.Headers.Set("prepared-header", "stored"); + return next(context); + }, + "PrepareScheduledMessage")); + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + observationCalls++; + return next(context); + }, + "ObserveScheduledMessage"), after: "PrepareScheduledMessage"); + bus.UseReceive(new ReceiveMiddlewareConfiguration( + (_, next) => async context => + { + var envelope = MessageEnvelope.CopyWithOwnedBody(context.Envelope!); + await next(context); + received.TrySetResult(envelope); + }, + "CaptureScheduledMessage")); + }); + }); + using var scope = env.Provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + if (send) + { + await bus.ScheduleSendAsync( + new ScheduledPing { Text = "original" }, + s_start.AddMinutes(10), + TestContext.Current.CancellationToken); + } + else + { + await bus.SchedulePublishAsync( + new ScheduledPing { Text = "original" }, + s_start.AddMinutes(10), + TestContext.Current.CancellationToken); + } + + var callsAtInvocation = (preparationCalls, observationCalls); + time.Advance(TimeSpan.FromMinutes(11)); + var delivered = await received.Task.WaitAsync(s_deliveryTimeout, TestContext.Current.CancellationToken); + + // assert + Assert.Equal((1, 1), callsAtInvocation); + Assert.Equal((1, 1), (preparationCalls, observationCalls)); + Assert.Equal("{\"Text\":\"prepared\"}", System.Text.Encoding.UTF8.GetString(delivered.Body.Span)); + Assert.Equal("stored", delivered.Headers?.GetValue("prepared-header")); + Assert.Equal((s_start.AddMinutes(11), s_start.AddMinutes(10)), (delivered.SentAt, delivered.ScheduledTime)); + } + [Fact] public async Task CancelScheduledMessage_Should_PreventDelivery_When_BeforeDueTime() { @@ -119,15 +193,12 @@ await recorder.WaitAsync(s_deliveryTimeout), public async Task ScheduledMessage_Should_BeDroppedAndWorkerContinue_When_DispatchThrows() { // arrange - // a dispatch middleware throws on the first re-dispatch; the worker must log-and-drop that - // message and keep delivering later scheduled messages. var recorder = new MessageRecorder(); var time = new FakeTimeProvider(s_start); - var toggle = new DispatchFailureToggle(); await using var env = await CreateBusAsync( recorder, time, - b => AddThrowOnceDispatchMiddleware(b, toggle)); + AddInvalidReplyDestination); await PublishScheduledAsync(env.Provider, s_start.AddMinutes(5), "dropped"); time.Advance(TimeSpan.FromMinutes(6)); @@ -137,7 +208,7 @@ public async Task ScheduledMessage_Should_BeDroppedAndWorkerContinue_When_Dispat // act time.Advance(TimeSpan.FromMinutes(6)); - // assert - only the second message is delivered; the worker survived the failure + // assert Assert.True( await recorder.WaitAsync(s_deliveryTimeout), "The worker should survive a dispatch failure and deliver later messages"); @@ -198,25 +269,21 @@ private static async Task CreateBusAsync( return new TestEnvironment(provider, hostedServices); } - private static void AddThrowOnceDispatchMiddleware( - IMessageBusHostBuilder builder, - DispatchFailureToggle toggle) + private static void AddInvalidReplyDestination(IMessageBusHostBuilder builder) { - builder.ConfigureMessageBus(h => - h.UseDispatch( - new DispatchMiddlewareConfiguration( - (_, next) => ctx => + builder.ConfigureMessageBus(bus => + bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => context => + { + if (context.Message is ScheduledPing { Text: "dropped" }) { - if (!toggle.Thrown) - { - toggle.Thrown = true; - - throw new InvalidOperationException("Simulated dispatch failure"); - } + context.Headers.Set("message-kind", "reply"); + context.DestinationAddress = new Uri("memory://localhost/q/missing"); + } - return next(ctx); - }, - "ThrowOnceDispatch"))); + return next(context); + }, + "InvalidReplyDestination"))); } public sealed class ScheduledPing @@ -234,6 +301,15 @@ public ValueTask HandleAsync(ScheduledPing message, CancellationToken cancellati } } + public sealed class ScheduledPingRequestHandler(MessageRecorder recorder) : IEventRequestHandler + { + public ValueTask HandleAsync(ScheduledPing message, CancellationToken cancellationToken) + { + recorder.Record(message); + return default; + } + } + private sealed class TestEnvironment(ServiceProvider provider, List hostedServices) : IAsyncDisposable { @@ -251,9 +327,4 @@ public async ValueTask DisposeAsync() await provider.DisposeAsync(); } } - - private sealed class DispatchFailureToggle - { - public bool Thrown; - } } From e576064d3ca18f80da1abccd4de7911a70eb35b6 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:52:05 +0000 Subject: [PATCH 2/7] [Mocha] Cover the delivery of a stored message in the outbox integration tests A test stores a published message in the outbox, delivers the stored envelope through DispatchInternalAsync and checks that the handler receives it while the outbox keeps the one stored message. --- .../Outbox/OutboxIntegrationTests.cs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs b/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs index 6c505885bcc..8a84c8a3457 100644 --- a/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs @@ -166,10 +166,55 @@ public async Task Outbox_Should_UseBatchIdAsCausation_When_PublishedFromBatchHan Assert.Equal(recorder.BatchId, envelope.CausationId); } + [Fact] + public async Task DispatchInternalAsync_Should_DeliverStoredMessage_When_OutboxIsEnabled() + { + // arrange + var outbox = new InMemoryMessageOutbox(); + var recorder = new MessageRecorder(); + await using var provider = await CreateBusWithOutboxAsync( + outbox, + builder => + { + builder.Services.AddSingleton(recorder); + builder.AddEventHandler(); + }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + await bus.PublishAsync(new OutboxTestEvent { Payload = "stored" }, CancellationToken.None); + var envelope = Assert.Single(outbox.Envelopes); + + // act + await DeliverAsync(scope.ServiceProvider, envelope); + + // assert + Assert.True(await recorder.WaitAsync(s_timeout)); + Assert.Equal(["stored"], recorder.Messages.Cast().Select(message => message.Payload)); + Assert.Single(outbox.Envelopes); + } + // ══════════════════════════════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════════════════════════════ + private static async ValueTask DeliverAsync(IServiceProvider services, MessageEnvelope envelope) + { + var runtime = services.GetRequiredService(); + var messageType = runtime.GetMessageType(envelope.MessageType); + var endpoint = runtime.GetDispatchEndpoint(new Uri(envelope.DestinationAddress!)); + var pool = services.GetRequiredService().DispatchContext; + var context = pool.Get(); + try + { + context.InitializeFromEnvelope(services, endpoint, runtime, messageType, envelope, CancellationToken.None); + await endpoint.DispatchInternalAsync(context); + } + finally + { + pool.Return(context); + } + } + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) { using var cts = new CancellationTokenSource(timeout); From c5f0095ae0fa33bda567661c78d7a465dd1ba534 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:52:05 +0000 Subject: [PATCH 3/7] [Mocha] Cover the dispatch pipeline of published, sent and scheduled messages The tests check that changes dispatch middleware makes before next end up in the stored message, that the message is serialized before middleware unwinds, that middleware can anchor to every built-in stage, that middleware anchored after serialization runs for a stored message, that a cancellation after the dispatch completes it, and that scheduling returns the requested time when middleware changes it after next. --- .../Infrastructure/MessagePreparationTests.cs | 380 ++++++++++++++++++ 1 file changed, 380 insertions(+) create mode 100644 src/Mocha/test/Mocha.Tests/Infrastructure/MessagePreparationTests.cs diff --git a/src/Mocha/test/Mocha.Tests/Infrastructure/MessagePreparationTests.cs b/src/Mocha/test/Mocha.Tests/Infrastructure/MessagePreparationTests.cs new file mode 100644 index 00000000000..ef100878173 --- /dev/null +++ b/src/Mocha/test/Mocha.Tests/Infrastructure/MessagePreparationTests.cs @@ -0,0 +1,380 @@ +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Scheduling; +using Mocha.Transport.InMemory; + +namespace Mocha.Tests.Infrastructure; + +public class MessagePreparationTests +{ + private static readonly JsonSerializerOptions s_webOptions = new(JsonSerializerDefaults.Web); + + [Fact] + public async Task PublishAsync_Should_PersistMiddlewareChanges_When_ApplicationMiddlewareRuns() + { + // arrange + var middlewareCalls = 0; + await using var provider = await CreateProviderAsync(outbox: true, builder => + builder.ConfigureMessageBus(b => b.UseDispatch( + new DispatchMiddlewareConfiguration( + (_, next) => context => + { + middlewareCalls++; + context.Message = new TargetMessage("from-middleware"); + context.Headers.Set("durable-header", "prepared-once"); + return next(context); + }, + "ChangeMessage")))); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new TargetMessage("persisted"), CancellationToken.None); + + // assert + var envelope = Assert.Single(provider.GetRequiredService().Envelopes); + Assert.Equal(1, middlewareCalls); + Assert.Equal("prepared-once", envelope.Headers!.GetValue("durable-header")); + Assert.Equal("from-middleware", Deserialize(envelope).Value); + Assert.Equal(0, provider.GetRequiredService().Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PublishAsync_Should_FinalizeBeforeMiddlewareUnwinds_When_MessageIsDispatched(bool outbox) + { + // arrange + string? observed = null; + await using var provider = await CreateProviderAsync(outbox, builder => + builder.ConfigureMessageBus(bus => bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => async context => + { + await next(context); + var envelopes = outbox + ? context.Services.GetRequiredService().Envelopes + : context.Services.GetRequiredService().Envelopes; + observed = Deserialize(envelopes.Single()).Value; + context.Message = new TargetMessage("after-next"); + }, + "ObserveFinalization")))); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new TargetMessage("before-next"), CancellationToken.None); + + // assert + var envelopes = outbox + ? provider.GetRequiredService().Envelopes + : provider.GetRequiredService().Envelopes; + Assert.Equal("before-next", observed); + Assert.Equal(["before-next"], envelopes.Select(envelope => Deserialize(envelope).Value)); + } + + [Theory] + [InlineData("Instrumentation")] + [InlineData("Serialization")] + [InlineData("Scheduling")] + [InlineData("Outbox")] + public async Task Configure_Should_AcceptAnchor_When_MiddlewareReferencesBuiltInStage(string key) + { + // arrange + var middleware = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Headers.Set("x-anchor", "set"); + return next(context); + }, + "ApplicationMiddleware"); + + // act + await using var provider = await CreateProviderAsync(outbox: true, builder => + builder.ConfigureMessageBus(bus => bus.UseDispatch(middleware, before: key))); + using var scope = provider.CreateScope(); + await scope.ServiceProvider.GetRequiredService() + .PublishAsync(new TargetMessage("anchored"), CancellationToken.None); + + // assert + var envelope = Assert.Single(provider.GetRequiredService().Envelopes); + Assert.Equal("anchored", Deserialize(envelope).Value); + Assert.Equal("set", envelope.Headers!.GetValue("x-anchor")); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public async Task PublishAsync_Should_RunSerializationAnchoredMiddleware_When_MessageIsStored( + bool after, + bool scheduled) + { + // arrange + var calls = 0; + var store = new CapturingScheduledMessageStore(); + var middleware = new DispatchMiddlewareConfiguration( + (_, next) => context => + { + calls++; + context.Headers.Set("x-anchor", "set"); + return next(context); + }, + "SerializationAnchored"); + await using var provider = await CreateProviderAsync(outbox: true, builder => + { + builder.Services.RemoveAll(); + builder.Services.AddSingleton(store); + builder.Services.AddSingleton(new ScheduledMessageStoreRegistration( + typeof(InMemoryMessagingTransport), "test:", typeof(CapturingScheduledMessageStore))); + builder.ConfigureMessageBus(bus => + { + if (after) + { + bus.UseDispatch(middleware, after: "Serialization"); + } + else + { + bus.UseDispatch(middleware, before: "Serialization"); + } + }); + }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + if (scheduled) + { + await bus.SchedulePublishAsync( + new TargetMessage("anchored"), + new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero), + CancellationToken.None); + } + else + { + await bus.PublishAsync(new TargetMessage("anchored"), CancellationToken.None); + } + + // assert + var envelope = scheduled + ? Assert.Single(store.Envelopes) + : Assert.Single(provider.GetRequiredService().Envelopes); + Assert.Equal(1, calls); + Assert.Equal("set", envelope.Headers!.GetValue("x-anchor")); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PublishAsync_Should_Complete_When_MiddlewareCancelsAfterDispatch(bool outbox) + { + // arrange + using var cancellation = new CancellationTokenSource(); + await using var provider = await CreateProviderAsync(outbox, builder => + builder.ConfigureMessageBus(bus => bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => async context => + { + await next(context); + cancellation.Cancel(); + }, + "CancelAfterDispatch")))); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + await bus.PublishAsync(new TargetMessage("dispatched"), cancellation.Token); + + // assert + var envelopes = outbox + ? provider.GetRequiredService().Envelopes + : provider.GetRequiredService().Envelopes; + Assert.Equal("dispatched", Deserialize(Assert.Single(envelopes)).Value); + Assert.True(cancellation.IsCancellationRequested); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ScheduleAsync_Should_ReturnRequestedTime_When_MiddlewareChangesTimeAfterNext(bool send) + { + // arrange + var time = new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero); + var store = new CapturingScheduledMessageStore(); + await using var provider = await CreateProviderAsync(outbox: true, builder => + { + builder.Services.RemoveAll(); + builder.Services.AddSingleton(store); + builder.Services.AddSingleton(new ScheduledMessageStoreRegistration( + typeof(InMemoryMessagingTransport), "test:", typeof(CapturingScheduledMessageStore))); + builder.ConfigureMessageBus(bus => bus.UseDispatch(new DispatchMiddlewareConfiguration( + (_, next) => async context => + { + await next(context); + context.ScheduledTime = time.AddDays(1); + }, + "ChangeScheduleAfterNext"))); + }); + using var scope = provider.CreateScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + var result = await (send + ? bus.ScheduleSendAsync(new TargetMessage("scheduled"), time, CancellationToken.None) + : bus.SchedulePublishAsync(new TargetMessage("scheduled"), time, CancellationToken.None)); + + // assert + Assert.Equal( + new SchedulingResult { Token = "test:scheduled", ScheduledTime = time, IsCancellable = true }, + result); + Assert.Equal( + [(time, "scheduled")], + store.Envelopes.Select(envelope => (envelope.ScheduledTime, Deserialize(envelope).Value))); + Assert.Empty(provider.GetRequiredService().Envelopes); + Assert.Equal(0, provider.GetRequiredService().Calls); + } + + private static TargetMessage Deserialize(MessageEnvelope envelope) + => JsonSerializer.Deserialize(envelope.Body.Span, s_webOptions)!; + + private static async Task CreateProviderAsync( + bool outbox, + Action configure) + { + var services = new ServiceCollection(); + var counter = new TransportCounter(); + services.AddSingleton(); + services.AddSingleton(counter); + services.AddSingleton(sp => sp.GetRequiredService()); + var builder = services.AddMessageBus(); + if (outbox) + { + builder.UseOutboxCore(); + } + + builder.AddInMemory(transport => transport.DeclareQueue("target")); + configure(builder); + var provider = services.BuildServiceProvider(); + try + { + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(CancellationToken.None); + var transport = runtime.Transports.Single(); + var endpoint = new CapturingDispatchEndpoint(transport, counter); + endpoint.Initialize(runtime, new DispatchEndpointConfiguration { Name = "target" }); + endpoint.Complete(runtime); + foreach (var kind in new[] { OutboundRouteKind.Publish, OutboundRouteKind.Send }) + { + var route = new OutboundRoute(); + route.Initialize(runtime, new OutboundRouteConfiguration + { + RuntimeType = typeof(TargetMessage), + Kind = kind + }); + route.ConnectEndpoint(runtime, endpoint); + route.Complete(runtime); + } + + return provider; + } + catch + { + await provider.DisposeAsync(); + throw; + } + } + + public sealed record TargetMessage(string Value) : IEventRequest; + + private sealed class CapturingDispatchEndpoint(MessagingTransport transport, TransportCounter counter) + : DispatchEndpoint(transport) + { + protected override void OnInitialize( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { } + + protected override void OnComplete( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + Destination = ((InMemoryMessagingTopology)Transport.Topology).GetQueue("target")!; + Address = Destination.Address; + } + + protected override ValueTask DispatchAsync(IDispatchContext context) + { + counter.Calls++; + counter.Envelopes.Add(MessageEnvelope.CopyWithOwnedBody(context.Envelope!)); + return default; + } + } + + private sealed class ScopedState + { + public string Value { get; set; } = "unassigned"; + } + + private sealed class RecordingDiagnostics : MessagingDiagnosticEventListener + { + public List Events { get; } = []; + + public override IDisposable Dispatch(IDispatchContext context) + { + Events.Add("begin"); + return new RecordingScope(Events); + } + + public override void DispatchError(IDispatchContext context, Exception exception) + => Events.Add("error"); + + private sealed class RecordingScope(List events) : IDisposable + { + public void Dispose() => events.Add("end"); + } + } + + private sealed class TransportCounter + { + public int Calls { get; set; } + + public List Envelopes { get; } = []; + } + + private sealed class CapturingOutbox : IMessageOutbox + { + public List Envelopes { get; } = []; + + public Exception? Failure { get; set; } + + public Action? OnPersist { get; set; } + + public ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken cancellationToken) + { + if (Failure is { } failure) + { + throw failure; + } + + Envelopes.Add(MessageEnvelope.CopyWithOwnedBody(envelope)); + OnPersist?.Invoke(); + return default; + } + } + + private sealed class CapturingScheduledMessageStore : IScheduledMessageStore + { + public List Envelopes { get; } = []; + + public ValueTask PersistAsync(IDispatchContext context, CancellationToken cancellationToken) + { + Envelopes.Add(MessageEnvelope.CopyWithOwnedBody(context.Envelope!)); + return ValueTask.FromResult("test:scheduled"); + } + + public ValueTask CancelAsync(string token, CancellationToken cancellationToken) + => ValueTask.FromResult(false); + } +} From 48d4316aecebd553890c08d8023f69d4cfe3faf6 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:56:36 +0000 Subject: [PATCH 4/7] [Mocha] Fix the RabbitMQ routing key middleware replacing a routing key set by dispatch middleware Application middleware now runs before the RabbitMQ routing key extractor, so it can set the routing key header itself, but the extractor overwrote the header with the key extracted from the message. It now keeps a header that is already set, as the Azure Service Bus property middleware does. Tests cover that both extractors see a message that middleware replaced or changed, that middleware anchored after serialization reads the extracted values, and that Service Bus properties survive an envelope that was stored and read back. --- .../Dispatch/RabbitMQRoutingKeyMiddleware.cs | 4 +- ...erviceBusMessagePropertiesPipelineTests.cs | 128 ++++++++++++++ .../AzureServiceBusSchedulingUnitTests.cs | 34 ++++ .../Behaviors/RoutingKeyMiddlewareTests.cs | 99 +++++++++++ .../RabbitMQRoutingKeyPipelineTests.cs | 160 ++++++++++++++++++ .../RabbitMQRoutingKeyTests.cs | 97 +++++++++++ 6 files changed, 521 insertions(+), 1 deletion(-) create mode 100644 src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusMessagePropertiesPipelineTests.cs create mode 100644 src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RoutingKeyMiddlewareTests.cs create mode 100644 src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyPipelineTests.cs diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Dispatch/RabbitMQRoutingKeyMiddleware.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Dispatch/RabbitMQRoutingKeyMiddleware.cs index 2e21f25703d..3fa0ea53f9b 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Dispatch/RabbitMQRoutingKeyMiddleware.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Dispatch/RabbitMQRoutingKeyMiddleware.cs @@ -10,7 +10,8 @@ namespace Mocha.Transport.RabbitMQ.Middlewares; internal sealed class RabbitMQRoutingKeyMiddleware { /// - /// Invokes the middleware, extracting the routing key if an extractor is configured on the message type. + /// Invokes the middleware, extracting the routing key if an extractor is configured on the message type + /// and the routing key header has not already been set. /// /// The dispatch context. /// The next delegate in the dispatch pipeline. @@ -18,6 +19,7 @@ public ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate next) { if (context.MessageType is not null && context.Message is not null + && !context.Headers.ContainsKey(RabbitMQMessageHeaders.RoutingKey.Key) && context.MessageType.Features.TryGet(out var extractor)) { var routingKey = extractor.Extract(context.Message); diff --git a/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusMessagePropertiesPipelineTests.cs b/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusMessagePropertiesPipelineTests.cs new file mode 100644 index 00000000000..d08221120dc --- /dev/null +++ b/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusMessagePropertiesPipelineTests.cs @@ -0,0 +1,128 @@ +using Microsoft.Extensions.DependencyInjection; +using Mocha.Middlewares; +using Mocha.Transport.AzureServiceBus.Tests.Helpers; + +namespace Mocha.Transport.AzureServiceBus.Tests; + +public class AzureServiceBusMessagePropertiesPipelineTests +{ + private const string FakeConnectionString = + "Endpoint=sb://fake.servicebus.windows.net/;SharedAccessKeyName=k;SharedAccessKey=a2V5"; + + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_ExtractSessionIdFromNewMessage_When_BusMiddlewareReplacesMessage( + string? before) + { + // arrange + var replace = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Message = new SessionEvent { SessionKey = "session-new" }; + return next(context); + }, + "ReplaceMessage"); + + // act + var sessionId = await DispatchAsync( + new SessionEvent { SessionKey = "session-original" }, + bus => bus.UseDispatch(replace, before: before)); + + // assert + Assert.Equal("session-new", sessionId); + } + + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_ExtractSessionIdFromChangedMessage_When_BusMiddlewareMutatesMessage( + string? before) + { + // arrange + var mutate = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + ((SessionEvent)context.Message!).SessionKey = "session-new"; + return next(context); + }, + "MutateMessage"); + + // act + var sessionId = await DispatchAsync( + new SessionEvent { SessionKey = "session-original" }, + bus => bus.UseDispatch(mutate, before: before)); + + // assert + Assert.Equal("session-new", sessionId); + } + + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_KeepSessionId_When_BusMiddlewareSetsSessionIdHeader(string? before) + { + // arrange + var setHeader = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Headers.Set(AzureServiceBusMessageHeaders.SessionId, "from-middleware"); + return next(context); + }, + "SetSessionId"); + + // act + var sessionId = await DispatchAsync( + new SessionEvent { SessionKey = "session-original" }, + bus => bus.UseDispatch(setHeader, before: before)); + + // assert + Assert.Equal("from-middleware", sessionId); + } + + private static async Task DispatchAsync(SessionEvent message, Action configureBus) + { + object? sessionId = null; + var services = new ServiceCollection(); + var builder = services.AddMessageBus(); + builder.AddMessage(m => + { + m.UseAzureServiceBusSessionId(e => e.SessionKey); + m.Publish(route => route.ToAzureServiceBusTopic("sessions")); + }); + builder.ConfigureMessageBus(bus => + { + bus.UseDispatch( + new DispatchMiddlewareConfiguration( + (_, _) => context => + { + sessionId = context.Envelope!.Headers!.GetValue(AzureServiceBusMessageHeaders.SessionId); + return default; + }, + "CaptureSessionId"), + after: DispatchMiddlewares.Serialization.Key); + configureBus(bus); + }); + await using var runtime = builder.AddAzureServiceBus(FakeConnectionString).BuildRuntime(); + var messageType = runtime.GetMessageType(typeof(SessionEvent)); + var endpoint = runtime.GetPublishEndpoint(messageType); + var context = new DispatchContext { Message = message }; + context.Initialize(runtime.Services, endpoint, runtime, messageType, CancellationToken.None); + + try + { + await endpoint.ExecuteAsync(context); + } + finally + { + context.Reset(); + } + + return sessionId; + } + + public sealed class SessionEvent + { + public required string SessionKey { get; set; } + } +} diff --git a/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusSchedulingUnitTests.cs b/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusSchedulingUnitTests.cs index cefd0a087d0..e553d7bfdb4 100644 --- a/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusSchedulingUnitTests.cs +++ b/src/Mocha/test/Mocha.Transport.AzureServiceBus.Tests/AzureServiceBusSchedulingUnitTests.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; +using System.Text.Json; using Azure.Messaging.ServiceBus; using Azure.Messaging.ServiceBus.Administration; using Microsoft.Extensions.DependencyInjection; @@ -6,6 +7,7 @@ using Mocha.Scheduling; using Mocha.Transport.AzureServiceBus.Scheduling; using Mocha.Transport.AzureServiceBus.Tests.Helpers; +using Mocha.Utils; namespace Mocha.Transport.AzureServiceBus.Tests; @@ -232,6 +234,38 @@ public void CreateMessage_Should_DefaultPartitionKeyToSessionId_When_PartitionKe Assert.Equal("session-1", message.PartitionKey); } + [Fact] + public void CreateMessage_Should_SetNativeProperties_When_EnvelopeWasStoredAndReadBack() + { + // arrange + var headers = new Headers(); + headers.Set(AzureServiceBusMessageHeaders.SessionId, "session-1"); + headers.Set(AzureServiceBusMessageHeaders.PartitionKey, "session-1"); + headers.Set(AzureServiceBusMessageHeaders.ReplyToSessionId, "reply-session"); + headers.Set(AzureServiceBusMessageHeaders.To, "forward-target"); + var envelope = new MessageEnvelope + { + MessageId = "message-1", + Headers = headers, + Body = "{}"u8.ToArray() + }; + using var buffer = new PooledArrayWriter(); + using var json = new Utf8JsonWriter(buffer); + var writer = new MessageEnvelopeWriter(json); + writer.WriteMessage(envelope); + json.Flush(); + var stored = MessageEnvelopeReader.Parse(buffer.WrittenMemory.ToArray()); + + // act + var message = AzureServiceBusMessageFactory.Create(stored, DateTimeOffset.UtcNow); + + // assert + Assert.Equal("session-1", message.SessionId); + Assert.Equal("session-1", message.PartitionKey); + Assert.Equal("reply-session", message.ReplyToSessionId); + Assert.Equal("forward-target", message.To); + } + [Fact] public void CreateMessage_Should_Throw_When_PartitionKeyDoesNotMatchSessionId() { diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RoutingKeyMiddlewareTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RoutingKeyMiddlewareTests.cs new file mode 100644 index 00000000000..c34d2255063 --- /dev/null +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RoutingKeyMiddlewareTests.cs @@ -0,0 +1,99 @@ +using Microsoft.Extensions.DependencyInjection; +using Mocha.Transport.RabbitMQ.Tests.Helpers; + +namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; + +[Collection(RabbitMQCollections.Topology)] +public class RoutingKeyMiddlewareTests +{ + private static readonly TimeSpan s_negativeTimeout = TimeSpan.FromSeconds(2); + private readonly RabbitMQFixture _fixture; + + public RoutingKeyMiddlewareTests(RabbitMQFixture fixture) + { + _fixture = fixture; + } + + [Fact] + public async Task PublishAsync_Should_RouteByNewMessage_When_BusMiddlewareReplacesMessageBeforeSerialization() + { + // arrange + var usRecorder = new MessageRecorder(); + var euRecorder = new MessageRecorder(); + var retag = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + var original = (RegionEvent)context.Message!; + context.Message = new RegionEvent { Region = "eu.west", Payload = original.Payload + "-retagged" }; + return next(context); + }, + "Retag"); + await using var vhost = await _fixture.CreateVhostAsync(); + var services = new ServiceCollection() + .AddSingleton(vhost.ConnectionFactory) + .AddKeyedSingleton("us", usRecorder) + .AddKeyedSingleton("eu", euRecorder); + var builder = services.AddMessageBus(); + builder.ConfigureMessageBus(bus => bus.UseDispatch(retag, before: DispatchMiddlewares.Serialization.Key)); + await using var bus = await builder + .AddConsumer() + .AddConsumer() + .AddMessage(m => m.UseRabbitMQRoutingKey(msg => msg.Region)) + .AddRabbitMQ(t => + { + t.BindExplicitly(); + + t.DeclareExchange("region-topic").Type(RabbitMQExchangeType.Topic); + t.DeclareQueue("us-queue"); + t.DeclareQueue("eu-queue"); + t.DeclareBinding("region-topic", "us-queue").RoutingKey("us.*"); + t.DeclareBinding("region-topic", "eu-queue").RoutingKey("eu.*"); + + t.Queue("us-queue").BindExplicitly().Consumer(); + t.Queue("eu-queue").BindExplicitly().Consumer(); + t.DispatchEndpoint("region-dispatch").ToExchange("region-topic").Publish(); + }) + .BuildTestBusAsync(); + + using var scope = bus.Provider.CreateScope(); + var messageBus = scope.ServiceProvider.GetRequiredService(); + + // act + await messageBus.PublishAsync( + new RegionEvent { Region = "us.east", Payload = "p" }, + CancellationToken.None); + + // assert + Assert.True(await euRecorder.WaitAsync(TestTimeouts.Signal), "EU handler did not receive the retagged event"); + var euEvent = Assert.IsType(Assert.Single(euRecorder.Messages)); + Assert.Equal("eu.west/p-retagged", $"{euEvent.Region}/{euEvent.Payload}"); + Assert.False( + await usRecorder.WaitAsync(s_negativeTimeout), + "US handler should not have received an event retagged to eu.west"); + } + + public sealed class RegionEvent + { + public required string Region { get; init; } + + public required string Payload { get; init; } + } + + public sealed class UsRegionConsumer([FromKeyedServices("us")] MessageRecorder recorder) : IConsumer + { + public ValueTask ConsumeAsync(IConsumeContext context) + { + recorder.Record(context.Message); + return default; + } + } + + public sealed class EuRegionConsumer([FromKeyedServices("eu")] MessageRecorder recorder) : IConsumer + { + public ValueTask ConsumeAsync(IConsumeContext context) + { + recorder.Record(context.Message); + return default; + } + } +} diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyPipelineTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyPipelineTests.cs new file mode 100644 index 00000000000..28247f952f8 --- /dev/null +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyPipelineTests.cs @@ -0,0 +1,160 @@ +using Microsoft.Extensions.DependencyInjection; +using Mocha.Middlewares; +using Mocha.Transport.RabbitMQ.Middlewares; +using Mocha.Transport.RabbitMQ.Tests.Helpers; + +namespace Mocha.Transport.RabbitMQ.Tests; + +public class RabbitMQRoutingKeyPipelineTests +{ + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_ExtractRoutingKeyFromNewMessage_When_BusMiddlewareReplacesMessage( + string? before) + { + // arrange + var replace = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + context.Message = new RegionEvent { Region = "eu.west" }; + return next(context); + }, + "ReplaceMessage"); + + // act + var routingKey = await DispatchAsync( + new RegionEvent { Region = "us.east" }, + bus => bus.UseDispatch(replace, before: before), + static _ => { }); + + // assert + Assert.Equal("eu.west", routingKey); + } + + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_ExtractRoutingKeyFromChangedMessage_When_BusMiddlewareMutatesMessage( + string? before) + { + // arrange + var mutate = new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + ((RegionEvent)context.Message!).Region = "eu.west"; + return next(context); + }, + "MutateMessage"); + + // act + var routingKey = await DispatchAsync( + new RegionEvent { Region = "us.east" }, + bus => bus.UseDispatch(mutate, before: before), + static _ => { }); + + // assert + Assert.Equal("eu.west", routingKey); + } + + [Fact] + public async Task ExecuteAsync_Should_ExposeExtractedRoutingKey_When_BusMiddlewareRunsAfterSerialization() + { + // arrange + string? observed = null; + var observe = new DispatchMiddlewareConfiguration( + (_, next) => context => + { + observed = context.Headers.Get(RabbitMQMessageHeaders.RoutingKey); + return next(context); + }, + "ObserveRoutingKey"); + + // act + await DispatchAsync( + new RegionEvent { Region = "us.east" }, + bus => bus.UseDispatch(observe, after: DispatchMiddlewares.Serialization.Key), + static _ => { }); + + // assert + Assert.Equal("us.east", observed); + } + + [Fact] + public async Task ExecuteAsync_Should_ExposeExtractedRoutingKey_When_TransportMiddlewareRunsAfterExtractor() + { + // arrange + string? observed = null; + var observe = new DispatchMiddlewareConfiguration( + (_, next) => context => + { + observed = context.Headers.Get(RabbitMQMessageHeaders.RoutingKey); + return next(context); + }, + "ObserveRoutingKey"); + + // act + await DispatchAsync( + new RegionEvent { Region = "us.east" }, + static _ => { }, + transport => transport.UseDispatch(observe, after: RabbitMQDispatchMiddlewares.RoutingKey.Key)); + + // assert + Assert.Equal("us.east", observed); + } + + private static async Task DispatchAsync( + RegionEvent message, + Action configureBus, + Action configureTransport) + { + string? routingKey = null; + var services = new ServiceCollection(); + var builder = services.AddMessageBus(); + builder.AddMessage(m => + { + m.UseRabbitMQRoutingKey(e => e.Region); + m.Publish(route => route.ToRabbitMQExchange("regions")); + }); + builder.ConfigureMessageBus(bus => + { + bus.UseDispatch( + new DispatchMiddlewareConfiguration( + (_, _) => context => + { + routingKey = context.Envelope!.Headers!.Get(RabbitMQMessageHeaders.RoutingKey); + return default; + }, + "CaptureRoutingKey"), + after: DispatchMiddlewares.Serialization.Key); + configureBus(bus); + }); + await using var runtime = builder + .AddRabbitMQ(t => + { + t.ConnectionProvider(_ => new StubConnectionProvider()); + configureTransport(t); + }) + .BuildRuntime(); + var messageType = runtime.GetMessageType(typeof(RegionEvent)); + var endpoint = runtime.GetPublishEndpoint(messageType); + var context = new DispatchContext { Message = message }; + context.Initialize(runtime.Services, endpoint, runtime, messageType, CancellationToken.None); + + try + { + await endpoint.ExecuteAsync(context); + } + finally + { + context.Reset(); + } + + return routingKey; + } + + public sealed class RegionEvent + { + public required string Region { get; set; } + } +} diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyTests.cs index 39dd7e50770..57394800cf7 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQRoutingKeyTests.cs @@ -104,6 +104,96 @@ public async Task Middleware_Should_SetRoutingKeyHeader_When_ExtractorConfigured Assert.Equal("ORD-999", capturedRoutingKey); } + [Theory] + [InlineData(null)] + [InlineData("Serialization")] + public async Task ExecuteAsync_Should_PreserveBusMiddlewareRoutingKey_When_ExtractorIsConfigured(string? before) + { + // arrange + object? preparedRoutingKey = null; + await using var runtime = CreateRuntime(builder => + { + builder.AddMessage(message => + { + message.UseRabbitMQRoutingKey(order => order.OrderId); + message.Publish(route => route.ToRabbitMQExchange("orders")); + }); + builder.ConfigureMessageBus(bus => + { + bus.UseDispatch( + new DispatchMiddlewareConfiguration( + (_, next) => context => + { + context.Headers.Set(RabbitMQMessageHeaders.RoutingKey, "from-middleware"); + return next(context); + }, + "OverrideRoutingKey"), + before: before); + bus.UseDispatch( + new DispatchMiddlewareConfiguration( + (_, _) => context => + { + preparedRoutingKey = context.Envelope!.Headers!.GetValue( + RabbitMQMessageHeaders.RoutingKey.Key); + return default; + }, + "CaptureEnvelope"), + after: DispatchMiddlewares.Serialization.Key); + }); + }); + var messageType = runtime.GetMessageType(typeof(OrderCreated)); + var endpoint = runtime.GetPublishEndpoint(messageType); + var context = new DispatchContext { Message = new OrderCreated { OrderId = "ORD-123" } }; + context.Initialize(runtime.Services, endpoint, runtime, messageType, CancellationToken.None); + + // act + try + { + await endpoint.ExecuteAsync(context); + } + finally + { + context.Reset(); + } + + // assert + Assert.Equal("from-middleware", preparedRoutingKey); + } + + [Fact] + public async Task ExecuteAsync_Should_ReportDispatchError_When_RoutingKeyExtractorThrows() + { + // arrange + var diagnostics = new RecordingDiagnostics(); + await using var runtime = CreateRuntime(builder => + { + builder.Services.AddSingleton(diagnostics); + builder.AddMessage(message => + { + message.UseRabbitMQRoutingKey( + _ => throw new InvalidOperationException("The routing key could not be extracted.")); + message.Publish(route => route.ToRabbitMQExchange("orders")); + }); + }); + var messageType = runtime.GetMessageType(typeof(OrderCreated)); + var endpoint = runtime.GetPublishEndpoint(messageType); + var context = new DispatchContext { Message = new OrderCreated { OrderId = "ORD-123" } }; + context.Initialize(runtime.Services, endpoint, runtime, messageType, CancellationToken.None); + + // act + try + { + await Assert.ThrowsAsync(async () => await endpoint.ExecuteAsync(context)); + } + finally + { + context.Reset(); + } + + // assert + Assert.Equal("The routing key could not be extracted.", Assert.Single(diagnostics.Errors).Message); + } + [Fact] public async Task Middleware_Should_NotSetRoutingKeyHeader_When_ExtractorNotConfigured() { @@ -168,6 +258,13 @@ public async Task Middleware_Should_NotSetRoutingKeyHeader_When_ExtractorReturns Assert.False(context.Headers.TryGetValue("x-routing-key", out _)); } + private sealed class RecordingDiagnostics : MessagingDiagnosticEventListener + { + public List Errors { get; } = []; + + public override void DispatchError(IDispatchContext context, Exception exception) => Errors.Add(exception); + } + private static MessagingRuntime CreateRuntime(Action configure) { var services = new ServiceCollection(); From 5df73948778d8d5df41a600d8c3038b93f0c3849 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:56:56 +0000 Subject: [PATCH 5/7] [Mocha] Remove the unused Mocha.Outbox reference from the in-memory transport The scheduler worker was the only code in the in-memory transport that used Mocha.Outbox, for SkipOutbox(). It sends stored envelopes directly now, so the project reference is removed. An application that got Mocha.Outbox only through the in-memory transport has to reference it itself. --- .../src/Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Mocha/src/Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj b/src/Mocha/src/Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj index 77acfb86aea..ba20a2a0f7c 100644 --- a/src/Mocha/src/Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj +++ b/src/Mocha/src/Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj @@ -6,7 +6,6 @@ - From 404bff98f81af6a4d09e7552435714dd2c35cad3 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:57:18 +0000 Subject: [PATCH 6/7] [Mocha] Document the dispatch pipeline order and the delivery of stored messages The middleware page shows the new dispatch order, says that middleware without an anchor runs before serialization, lists the keys of the built-in middleware and explains how anchors are resolved. The reliability, scheduling, observability and transport pages say that dispatch middleware runs when a message is stored and that the outbox processor and the scheduler send the stored envelope directly. The skip-the-outbox section shows a middleware anchored before OutboxDispatchMiddlewares.Outbox. The dispatch registration sample no longer calls an AddMessageBus overload that does not exist. --- .../docs/mocha/middleware-and-pipelines.md | 53 +++++++++++-------- website/content/docs/mocha/observability.md | 8 +-- website/content/docs/mocha/reliability.md | 34 ++++++++++-- website/content/docs/mocha/scheduling.md | 4 +- .../content/docs/mocha/transports/index.md | 11 ++-- 5 files changed, 76 insertions(+), 34 deletions(-) diff --git a/website/content/docs/mocha/middleware-and-pipelines.md b/website/content/docs/mocha/middleware-and-pipelines.md index 5012e74905b..424f50564bc 100644 --- a/website/content/docs/mocha/middleware-and-pipelines.md +++ b/website/content/docs/mocha/middleware-and-pipelines.md @@ -41,8 +41,11 @@ PublishAsync / SendAsync / RequestAsync ┌─────────────────────────┐ │ Dispatch Pipeline │ │ Instrumentation │ +│ Application middleware │ │ Serialization │ -│ → Transport sends │ +│ Scheduling │ +│ Outbox (optional) │ +│ → Transport │ └─────────────────────────┘ │ ▼ (wire / InMemory) @@ -72,9 +75,9 @@ PublishAsync / SendAsync / RequestAsync Each pipeline operates on a different context: -- **Dispatch** (`IDispatchContext`) - operates on the unserialized message object. Has the CLR message, headers, and destination address. Serialization happens at the end. -- **Receive** (`IReceiveContext`) - operates on the raw envelope from the transport. Has the serialized body, headers, and transport metadata. Message type resolution and routing happen here. -- **Consumer** (`IConsumeContext`) - operates on the deserialized message inside a specific consumer. Has the typed message, envelope metadata, and scoped services. +- **Dispatch** (`IDispatchContext`): operates on the outgoing message object, headers, and destination address. The message is serialized before persistence or transport dispatch. +- **Receive** (`IReceiveContext`): operates on the raw envelope from the transport. Has the serialized body, headers, and transport metadata. Message type resolution and routing happen here. +- **Consumer** (`IConsumeContext`): operates on the deserialized message inside a specific consumer. Has the typed message, envelope metadata, and scoped services. In a distributed system, the dispatch and receive pipelines run in different processes. With the InMemory transport, they run in the same process. @@ -208,6 +211,12 @@ builder.Services Dispatch middleware wraps the outbound path. Use it for concerns on every outgoing message: adding headers, enforcing message schemas, or enriching with correlation context. +The default dispatch order is instrumentation, application middleware, serialization, scheduling, outbox persistence when enabled, and transport dispatch. Scheduling and outbox middleware persist the serialized message and return without calling the next middleware. Other messages continue to the transport. + +Middleware registered without an anchor runs before serialization. Change message data and headers before calling `next(context)`; later changes do not affect the serialized message. Middleware that works on the serialized envelope, such as signing or encryption, is registered with `after: DispatchMiddlewares.Serialization.Key` and runs for every message, including scheduled and outboxed ones. + +Outbox and scheduler workers deliver stored envelopes without running dispatch middleware again. For a stored message, `await next(context)` returns once the message is stored or staged, and middleware after the step that stores it does not run. + ```csharp internal sealed class TenantDispatchMiddleware { @@ -239,14 +248,12 @@ internal sealed class TenantDispatchMiddleware } ``` -Register before all other dispatch middleware so every outgoing message carries the header: +Register the middleware on the bus to add the header to outgoing messages: ```csharp builder.Services .AddMessageBus() - .UseDispatch( - TenantDispatchMiddleware.Create("acme"), - before: DispatchMiddlewares.Instrumentation.Key) + .UseDispatch(TenantDispatchMiddleware.Create("acme")) .AddEventHandler() .AddInMemory(); ``` @@ -281,19 +288,23 @@ The factory lambda in `ReceiveMiddlewareConfiguration`, `ConsumerMiddlewareConfi Each pipeline type has a single registration method with optional `before` and `after` parameters: -| Method | Pipeline | Behavior | -| ------------------------------------ | -------- | ----------------------------------------------- | -| `UseReceive(config)` | Receive | Append to the pipeline | -| `UseReceive(config, before: "key")` | Receive | Insert before the middleware with the given key | -| `UseReceive(config, after: "key")` | Receive | Insert after the middleware with the given key | -| `UseDispatch(config)` | Dispatch | Append to the pipeline | -| `UseDispatch(config, before: "key")` | Dispatch | Insert before the middleware with the given key | -| `UseDispatch(config, after: "key")` | Dispatch | Insert after the middleware with the given key | -| `UseConsume(config)` | Consumer | Append to the pipeline | -| `UseConsume(config, before: "key")` | Consumer | Insert before the middleware with the given key | -| `UseConsume(config, after: "key")` | Consumer | Insert after the middleware with the given key | - -Only one of `before` or `after` can be specified at the same time. If neither is specified, the middleware is appended after the built-in defaults. +| Method | Pipeline | Behavior | +| ---------------------------------- | -------- | ----------------------------------------------- | +| `UseReceive(config)` | Receive | Append to the pipeline | +| `UseReceive(config, before: key)` | Receive | Insert before the middleware with the given key | +| `UseReceive(config, after: key)` | Receive | Insert after the middleware with the given key | +| `UseDispatch(config)` | Dispatch | Insert before serialization | +| `UseDispatch(config, before: key)` | Dispatch | Insert before the middleware with the given key | +| `UseDispatch(config, after: key)` | Dispatch | Insert after the middleware with the given key | +| `UseConsume(config)` | Consumer | Append to the pipeline | +| `UseConsume(config, before: key)` | Consumer | Insert before the middleware with the given key | +| `UseConsume(config, after: key)` | Consumer | Insert after the middleware with the given key | + +Only one of `before` or `after` can be specified at the same time. If neither is specified, the middleware is appended to the configured middleware list. + +The built-in middleware are exposed as configurations whose `Key` is the anchor: `ReceiveMiddlewares`, `DispatchMiddlewares`, and `ConsumerMiddlewares` in Mocha, `OutboxDispatchMiddlewares` and `InboxConsumerMiddlewares` in the outbox and inbox packages, and classes such as `RabbitMQDispatchMiddlewares` in the transports. The dispatch pipeline contains `DispatchMiddlewares.Instrumentation`, `DispatchMiddlewares.Serialization`, `DispatchMiddlewares.Scheduling`, and `OutboxDispatchMiddlewares.Outbox` when the outbox is enabled. For example, `UseDispatch(config, after: DispatchMiddlewares.Serialization.Key)` places middleware after serialization and before scheduling and outbox persistence. Middleware after a step that short-circuits does not run for that message. + +In the dispatch and receive pipelines, anchors are applied scope by scope, bus anchors first, then transport anchors, then endpoint anchors, and in registration order within a scope. Referencing a key that is not in the pipeline at that point throws an `InvalidOperationException` when the pipeline is built. A transport adds its own middleware, such as `RabbitMQDispatchMiddlewares.RoutingKey`, with a transport anchor, so anchor to its keys with the `UseDispatch` or `UseReceive` of that transport or of one of its endpoints. A bus anchor to a transport key throws. Middleware is compiled once at startup into a single delegate chain. Register all middleware during bus configuration, before the service provider is built. Middleware added after the bus starts has no effect. diff --git a/website/content/docs/mocha/observability.md b/website/content/docs/mocha/observability.md index 8f4eabe4aed..64cad4a8212 100644 --- a/website/content/docs/mocha/observability.md +++ b/website/content/docs/mocha/observability.md @@ -62,9 +62,11 @@ builder.Services After publishing a message, open your tracing backend (Aspire Dashboard, Jaeger, or an OTLP collector). For each message flow you should see three linked spans: -1. **`publish {destination}`** - Created by the dispatch pipeline when the message is sent. This span belongs to the publishing service. -2. **`receive {endpoint}`** - Created by the receive pipeline when the message arrives at an endpoint. This span belongs to the consuming service and links back to the publish span. -3. **`consume {handler}`** - Created as a child of the receive span when your handler processes the message. +1. **`publish {destination}`**: created by the dispatch pipeline when you publish the message. This span belongs to the publishing service. +2. **`receive {endpoint}`**: created by the receive pipeline when the message arrives at an endpoint. This span belongs to the consuming service and links back to the publish span. +3. **`consume {handler}`**: created as a child of the receive span when your handler processes the message. + +For a message that the outbox or a scheduler stores for later delivery, the `publish` span is created when the message is stored. The outbox processor records the delivery as an `outbox send` span, and the scheduler workers of the InMemory transport and of `UsePostgresScheduling()` record it as a `scheduler send` span. In the Aspire Dashboard, you will see the `publish` span from the publishing service linked to the `receive` span in the consumer service, with a child `consume` span for the handler execution. The three spans appear as a single distributed trace that crosses service boundaries. diff --git a/website/content/docs/mocha/reliability.md b/website/content/docs/mocha/reliability.md index d24c840bf32..579822366e8 100644 --- a/website/content/docs/mocha/reliability.md +++ b/website/content/docs/mocha/reliability.md @@ -733,7 +733,9 @@ builder.Services **4. Publish inside a transaction.** -With the outbox enabled, calls to `PublishAsync`, `SendAsync`, and `ReplyAsync` inside a handler persist the message envelope to the outbox table within the same database transaction. The outbox dispatch middleware intercepts these calls and writes to `IMessageOutbox` instead of the transport. +With the outbox enabled, calls to `PublishAsync`, `SendAsync`, and `ReplyAsync` inside a handler persist the message envelope to the outbox table within the same database transaction. The outbox middleware writes the serialized message to `IMessageOutbox` and returns without dispatching it to the transport. + +Dispatch middleware runs when the message is written to the outbox, not when the outbox processor delivers it. See [Dispatch middleware](./middleware-and-pipelines.md#dispatch-middleware) for where to register middleware that changes the message. ```csharp public class OrderPlacedHandler(AppDbContext dbContext, IMessageBus bus) @@ -825,15 +827,37 @@ builder.Services ## How the outbox processor works -The outbox processor is a background hosted service (`IHostedService`). When the EF Core interceptors detect a `SaveChanges` or transaction commit, they signal the processor through `IOutboxSignal`. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and dispatches each message through the bus's dispatch pipeline. +The outbox processor is a background hosted service (`IHostedService`). EF Core interceptors signal it through `IOutboxSignal` after saves and transaction commits. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. + +The processor sends stored envelopes directly through the transport. Dispatch middleware does not run during delivery or retries. If `SentAt` is unset, it is assigned immediately before transport dispatch. + +The `TimesSent` column counts dispatch attempts. If an attempt fails, the processor tries the message again after 10 seconds, until it succeeds or its expiration time passes, and logs every failed attempt. An expired message is deleted without being sent. At every 10th failed attempt of a message it also writes a `Critical` entry that names the outbox row, the message ID, the message type, and the destination. Messages are deleted from the outbox table after successful transport dispatch. -The `TimesSent` column counts dispatch attempts. If a dispatch fails, the processor dispatches the message again after 10 seconds, until it succeeds, and logs every failed attempt. At every 10th failed attempt of a message it also writes a `Critical` entry that names the outbox row, the message ID, the message type, and the destination. Messages are deleted from the outbox table after successful dispatch. +Outbox persistence applies to messages of kind `Publish`, `Send`, `Reply`, or `Fault`. Other message kinds pass through without outbox persistence. ## Skip the outbox for specific dispatches -Some messages - like internal system events or replies that do not need durability - can bypass the outbox. The outbox middleware checks for an `OutboxMiddlewareFeature` on the dispatch context. Messages with `SkipOutbox = true` pass straight through to the transport. +Some messages, such as internal events that do not need durability, can bypass the outbox. Call `context.SkipOutbox()` in dispatch middleware that runs before `OutboxDispatchMiddlewares.Outbox`, and the message goes straight to the transport: + +```csharp +using Mocha.Outbox; + +bus.UseDispatch( + new DispatchMiddlewareConfiguration( + static (_, next) => context => + { + if (context.Message is CacheInvalidatedEvent) + { + context.SkipOutbox(); + } + + return next(context); + }, + "SkipOutboxForCacheEvents"), + before: OutboxDispatchMiddlewares.Outbox.Key); +``` -The outbox middleware also only intercepts messages of kind `Publish`, `Send`, `Reply`, or `Fault`. Other message kinds pass through without outbox persistence. +This applies to `IMessageBus` publishes and sends. Scheduled messages are stored by the scheduler before the outbox runs and ignore the flag. # Deduplicate messages with the transactional inbox diff --git a/website/content/docs/mocha/scheduling.md b/website/content/docs/mocha/scheduling.md index a2778f6d693..73b2e466a13 100644 --- a/website/content/docs/mocha/scheduling.md +++ b/website/content/docs/mocha/scheduling.md @@ -16,6 +16,8 @@ var result = await bus.SchedulePublishAsync( The call returns immediately with a `SchedulingResult`. The message is persisted and delivered when the scheduled time arrives. If you need to revoke the message before delivery, pass the token to `CancelScheduledMessageAsync`. +Dispatch middleware runs when you schedule a message, not when it is delivered. See [Dispatch middleware](./middleware-and-pipelines.md#dispatch-middleware) for the order of the dispatch pipeline. + # Schedule a message Mocha provides scheduling methods on `IMessageBus` for scheduling with an absolute `DateTimeOffset`. @@ -211,7 +213,7 @@ builder.Services | `UsePostgresScheduling()` | Registers everything needed for durable scheduling with Postgres, including the background worker and EF Core interceptors. | | `AddPostgresScheduledMessages()` | Adds the `ScheduledMessage` entity configuration to the EF Core model. | -`UsePostgresScheduling()` sets up everything needed to persist scheduled messages in Postgres and dispatch them at the right time. Outgoing messages with a `ScheduledTime` are intercepted and written to the `scheduled_messages` table instead of being sent to the transport. A background worker continuously polls for due messages and dispatches them through the bus. EF Core interceptors signal the worker when `SaveChanges` or a transaction commit occurs, enabling low-latency wake-up. +`UsePostgresScheduling()` sets up everything needed to persist scheduled messages in Postgres and dispatch them at the right time. Outgoing messages with a `ScheduledTime` are intercepted and written to the `scheduled_messages` table instead of being sent to the transport. A background worker continuously polls for due messages and sends their stored envelopes directly through the transport. EF Core interceptors signal the worker when `SaveChanges` or a transaction commit occurs, enabling low-latency wake-up. When `UsePostgresScheduling()` is configured, `SchedulePublishAsync` and `ScheduleSendAsync` return cancellable results with tokens you can pass to `CancelScheduledMessageAsync`. diff --git a/website/content/docs/mocha/transports/index.md b/website/content/docs/mocha/transports/index.md index 2db8164ab42..9c46ab09e62 100644 --- a/website/content/docs/mocha/transports/index.md +++ b/website/content/docs/mocha/transports/index.md @@ -94,18 +94,21 @@ builder.Services .AddRabbitMQ(transport => { // Add dispatch middleware scoped to this transport - transport.UseDispatch(myDispatchMiddleware); + var tenantMiddleware = TenantDispatchMiddleware.Create("acme"); + transport.UseDispatch(tenantMiddleware); // Add receive middleware scoped to this transport transport.UseReceive(myReceiveMiddleware); // Insert middleware relative to existing ones - transport.UseReceive(myMiddleware, after: "ConcurrencyLimiter"); - transport.UseDispatch(myMiddleware, before: "Serialization"); + transport.UseReceive(myMiddleware, after: ReceiveMiddlewares.ConcurrencyLimiter.Key); + transport.UseDispatch(myDispatchMiddleware, after: tenantMiddleware.Key); }); ``` -This scoping model lets you run different middleware configurations per transport without affecting other transports in a multi-transport setup. +`TenantDispatchMiddleware` and dispatch ordering are covered in [Middleware and Pipelines](../middleware-and-pipelines.md#dispatch-middleware). + +Transport middleware applies only to endpoints on that transport. # Customize queues and binding From 09ca87a10fdc8e04fffc9ec94c84d4d916b8f41e Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:57:18 +0000 Subject: [PATCH 7/7] [Mocha] Add 16.8 upgrade notes for the dispatch pipeline The migration guide covers the removal of SkipScheduler(), the in-memory transport no longer referencing Mocha.Outbox, stored messages bypassing middleware during delivery, including rows written by 16.7, and the new position of middleware registered without an anchor. --- .../migration/migrate-from-16-7-to-16-8.md | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index f17c16ca008..b0376d4496a 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -1,6 +1,6 @@ --- title: Migrate Mocha from 16.7 to 16.8 -description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, source generator changes, and the health check, log, and trace changes that monitoring depends on." +description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, dispatch middleware ordering, delivery of stored messages, source generator changes, and the health check, log, and trace changes that monitoring depends on." --- Update every `Mocha.*` package in the application to version 16.8 before applying these changes. @@ -24,6 +24,18 @@ Assemblies that call or implement these methods must be recompiled against 16.8. `Mocha.Transport.RabbitMQ` references `RabbitMQ.Client` 7.2.2. Version 16.7 referenced 7.2.0. An application that pins `RabbitMQ.Client` to a lower version gets a package downgrade error (`NU1605`) at restore. Raise the pinned version to 7.2.2 or later. +## `SkipScheduler()` is removed + +`SkipScheduler()` and `SchedulingMiddlewareFeature` are removed. To dispatch a message that has a scheduled time right away, set `context.ScheduledTime = null` in dispatch middleware registered without an anchor. The message is then serialized without a scheduled time and dispatched like a message that was not scheduled. + +## The in-memory transport no longer depends on `Mocha.Outbox` + +The `Mocha.Transport.InMemory` package no longer references the `Mocha.Outbox` package. An application that uses types from `Mocha.Outbox`, such as `SkipOutbox()`, `IOutboxSignal`, or `UseOutboxCore()`, and gets the package only through the in-memory transport, adds the reference itself: + +```shell +dotnet add package Mocha.Outbox +``` + # Behavioral breaking changes ## RabbitMQ sends and publishes wait for the broker's confirmation @@ -274,6 +286,27 @@ What you will observe: - For a temporary endpoint, the forwarding subscriptions and the queue are removed after the processor is disposed. When this takes longer than 30 seconds, the log shows the Warning `Deleting the temporary resources of Azure Service Bus queue '' did not complete within 00:00:30` and the stop continues. - Disposing the processor waits for running handlers. A handler that ignores its `CancellationToken` delays the stop until it returns. +## Stored messages bypass middleware during delivery + +Dispatch middleware runs when a message is published or sent, including scheduled messages. After commit, the outbox processor sends stored messages directly through the transport. Scheduler delivery also uses the stored envelope. Dispatch middleware does not run again during delivery or retries. + +- Middleware anchored after `DispatchMiddlewares.Scheduling.Key` does not run for scheduled messages, and middleware anchored after `OutboxDispatchMiddlewares.Outbox.Key` does not run for messages that the outbox stores. In 16.7 such middleware ran when the outbox processor or a scheduler worker delivered the message. Move it before `DispatchMiddlewares.Scheduling` to run it when the message is stored. +- For a stored message, `await next(context)` returns once the message is staged or stored. Code after it, and a `catch` around it, do not observe the transport send or a failed delivery. + +Rows that 16.7 wrote to the outbox table or the scheduled message table are also sent as stored. Middleware that 16.7 would have run when delivering them never runs for those rows: for an outbox row, bus middleware registered after the outbox and all transport and endpoint middleware, and for a scheduled row, every middleware registered without an anchor. If the application depends on such middleware, let both tables drain on 16.7 before deploying 16.8. While both versions run against the same tables, a 16.7 instance runs its dispatch middleware again for a row that 16.8 stored. + +Dispatch spans and metrics, and the `Dispatch` and `DispatchError` calls of an `IMessagingDiagnosticEventListener`, happen when a stored (outboxed or scheduled) message is staged or stored, not when it is delivered. The delivery itself is traced by the `outbox send` and `scheduler send` spans, which record failures. + +## Dispatch middleware ordering + +The dispatch pipeline runs `DispatchMiddlewares.Instrumentation`, transport and application middleware, `DispatchMiddlewares.Serialization`, `DispatchMiddlewares.Scheduling`, and `OutboxDispatchMiddlewares.Outbox` when the outbox is enabled. The scheduling and outbox middleware persist the serialized message and do not call the next middleware. + +- Middleware registered without an anchor now runs before serialization, so `context.Envelope` is not set yet. Change the message and headers before calling `next(context)`. Changes made after `await next(context)` do not affect the sent or stored message. +- Middleware registered without an anchor that reads `context.Envelope` throws a `NullReferenceException` where it dereferences the envelope, and silently skips work that it applies only when the envelope is set, such as signing or encryption. Anchor such middleware with `after: DispatchMiddlewares.Serialization.Key`. +- Middleware anchored before or after `DispatchMiddlewares.Serialization.Key` runs for every message, including scheduled and outboxed messages. Use `after: DispatchMiddlewares.Serialization.Key` for middleware that works on the serialized envelope. +- `OutboxDispatchMiddlewares.Outbox`, `DispatchOutboxMiddleware.Create()`, or `DispatchMiddlewares.Scheduling` registered by hand without an anchor runs before serialization, and a message that it stores throws an `InvalidOperationException` with the message `Envelope is not set`. Register the outbox middleware with `UseOutboxCore()` or `UsePostgresOutbox()`, which add it after `DispatchMiddlewares.Scheduling`. The dispatch pipeline always contains the scheduling middleware. +- The RabbitMQ routing key and Azure Service Bus message property middleware run before `DispatchMiddlewares.Serialization`, after application middleware registered without an anchor or on the bus, and keep a value whose header is already set, except that an Azure Service Bus reply with a `ReplyToSessionId` header always takes its `SessionId` and `PartitionKey` from it. Middleware overrides a value by setting its header (`x-routing-key`, or a key from `AzureServiceBusMessageHeaders`) and reads the extracted values when it is anchored `after: DispatchMiddlewares.Serialization.Key`. + ## The source generator registers message types differently - An assembly that publishes or sends messages through `IMessageBus` but has no handlers or sagas now gets a generated `Add{Module}()` method, which registers the message types it publishes or sends that are declared in the same assembly. Message types from a referenced assembly, such as a contracts project, are not registered by call sites. The compile-time type of the message argument decides what is registered: a call that passes the message as an interface, an abstract class, or `object` registers nothing. See [Module naming](../handler-registration.md#module-naming).