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/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 @@
-
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.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/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/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);
+ }
+}
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);
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.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