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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Mocha.Middlewares;
using Mocha.Outbox;
using Npgsql;
using NpgsqlTypes;

Expand Down Expand Up @@ -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
{
Expand Down
7 changes: 5 additions & 2 deletions src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public sealed class DispatchOutboxMiddleware
/// <param name="context">The current dispatch context containing the message envelope and metadata.</param>
/// <param name="next">The next middleware delegate in the dispatch pipeline.</param>
/// <returns>A value task that completes when the message has been persisted or forwarded.</returns>
/// <exception cref="InvalidOperationException">A message to persist has no envelope.</exception>
public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate next)
{
var feature = context.Features.GetOrSet<OutboxMiddlewareFeature>();
Expand All @@ -36,10 +37,12 @@ and not MessageKind.Reply
else
{
var outbox = context.Services.GetRequiredService<IMessageOutbox>();
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);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Mocha.Outbox;
Expand All @@ -19,9 +20,18 @@ public static class OutboxCoreServiceCollectionExtensions
/// <returns>The same <paramref name="builder"/> instance for chaining.</returns>
public static IMessageBusHostBuilder UseOutboxCore(this IMessageBusHostBuilder builder)
{
if (builder.Services.Any(d => d.ServiceType == typeof(OutboxCoreRegistration)))
{
return builder;
}

builder.Services.AddSingleton<OutboxCoreRegistration>();
builder.Services.TryAddSingleton<IOutboxSignal, MessageBusOutboxSignal>();
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;
}
12 changes: 12 additions & 0 deletions src/Mocha/src/Mocha.Outbox/OutboxDispatchMiddlewares.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Mocha.Outbox;

/// <summary>
/// Provides the outbox dispatch middleware configuration. Use its key to place middleware relative to it.
/// </summary>
public static class OutboxDispatchMiddlewares
{
/// <summary>
/// Persists outgoing messages in the outbox instead of sending them to the transport.
/// </summary>
public static readonly DispatchMiddlewareConfiguration Outbox = DispatchOutboxMiddleware.Create();
}
7 changes: 7 additions & 0 deletions src/Mocha/src/Mocha.Outbox/ThrowHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Mocha.Outbox;

internal static class ThrowHelper
{
public static InvalidOperationException EnvelopeNotSet()
=> new("Envelope is not set");
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
<ItemGroup>
<ProjectReference Include="..\Mocha.Abstractions\Mocha.Abstractions.csproj" />
<ProjectReference Include="..\Mocha\Mocha.csproj" />
<ProjectReference Include="..\Mocha.Outbox\Mocha.Outbox.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// 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.
/// </summary>
internal sealed class InMemoryScheduledMessageWorker(
IServiceProvider services,
Expand Down Expand Up @@ -135,19 +132,24 @@ 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)
{
// The worker is shutting down; the in-flight message is lost (in-memory is non-durable).
}
catch (Exception ex)
{
activity?.AddException(ex);
activity?.SetStatus(ActivityStatusCode.Error);
logger.ScheduledMessageDispatchFailed(entry.Id, ex);
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ namespace Mocha.Transport.RabbitMQ.Middlewares;
internal sealed class RabbitMQRoutingKeyMiddleware
{
/// <summary>
/// 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.
/// </summary>
/// <param name="context">The dispatch context.</param>
/// <param name="next">The next delegate in the dispatch pipeline.</param>
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<RabbitMQRoutingKeyExtractor>(out var extractor))
{
var routingKey = extractor.Extract(context.Message);
Expand Down
2 changes: 1 addition & 1 deletion src/Mocha/src/Mocha/Abstractions/IMessageBusBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ IMessageBusBuilder AddBatchHandler<THandler>(
/// <summary>
/// Adds a dispatch middleware configuration to the dispatch pipeline.
/// When neither <paramref name="before"/> nor <paramref name="after"/> is specified, the
/// middleware is appended to the end of the pipeline.
/// middleware runs before serialization.
/// When <paramref name="before"/> is specified, the middleware is inserted immediately before
/// the middleware with the given key.
/// When <paramref name="after"/> is specified, the middleware is inserted immediately after
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public IMessageBusBuilder UseReceive(
/// <summary>
/// Adds a dispatch middleware to the bus-level outbound pipeline, applied to all transports.
/// When neither <paramref name="before"/> nor <paramref name="after"/> is specified, the
/// middleware is appended to the end of the pipeline.
/// middleware runs before serialization.
/// When <paramref name="before"/> is specified, the middleware is inserted immediately before
/// the middleware with the given key.
/// When <paramref name="after"/> is specified, the middleware is inserted immediately after
Expand Down
4 changes: 0 additions & 4 deletions src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NotAcknowledgedEvent>(x =>
Expand Down
12 changes: 10 additions & 2 deletions src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics;
using Mocha.Middlewares;
using Mocha.Outbox;

namespace Mocha;

Expand Down Expand Up @@ -196,6 +197,7 @@ public void Complete(IMessagingConfigurationContext context)
{
OnComplete(context, Configuration);
_timeProvider = context.Services.GetTimeProvider();
var outboxStage = context.Features.Get<OutboxDispatchStageFeature>();

var pipeline = MiddlewareCompiler.CompileDispatch(
new DispatchMiddlewareFactoryContext
Expand All @@ -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);
Expand Down Expand Up @@ -254,7 +262,7 @@ public DispatchEndpointDescription Describe()
/// <returns>A <see cref="ValueTask"/> that completes when the transport-level send is finished.</returns>
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;
Expand Down
40 changes: 40 additions & 0 deletions src/Mocha/src/Mocha/Middlewares/DispatchContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -113,11 +112,6 @@ private async ValueTask<bool> DispatchRedeliveryAsync(
{
dispatchContext.ScheduledTime = scheduledTime;
}
else
{
// No scheduling store available for this transport, fall back to immediate redelivery.
dispatchContext.Features.Configure<SchedulingMiddlewareFeature>(f => f.SkipScheduler = true);
}

await dispatchEndpoint.ExecuteAsync(dispatchContext);
return isScheduled;
Expand Down
8 changes: 8 additions & 0 deletions src/Mocha/src/Mocha/Outbox/OutboxDispatchStageFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Mocha.Outbox;

/// <summary>
/// Adds the outbox middleware to the dispatch pipeline of every dispatch endpoint of the bus, directly after
/// <see cref="DispatchMiddlewares.Scheduling"/>.
/// </summary>
/// <param name="Middleware">The outbox middleware configuration.</param>
internal sealed record OutboxDispatchStageFeature(DispatchMiddlewareConfiguration Middleware);
15 changes: 3 additions & 12 deletions src/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ namespace Mocha.Scheduling;
/// to the scheduled message store instead of forwarding them to the next pipeline stage.
/// </summary>
/// <remarks>
/// Messages without a <see cref="IDispatchContext.ScheduledTime"/> and dispatches marked with
/// <see cref="SchedulingMiddlewareFeature.SkipScheduler"/> pass through to the next middleware.
/// Messages without a <see cref="IDispatchContext.ScheduledTime"/> pass through to the next middleware.
/// Scheduled messages are routed to the registered store for the current transport.
/// </remarks>
public sealed class DispatchSchedulingMiddleware
Expand All @@ -22,6 +21,7 @@ public sealed class DispatchSchedulingMiddleware
/// <param name="context">The current dispatch context containing the message envelope and metadata.</param>
/// <param name="next">The next middleware delegate in the dispatch pipeline.</param>
/// <returns>A value task that completes when the message has been persisted or forwarded.</returns>
/// <exception cref="InvalidOperationException">A scheduled message has no envelope.</exception>
public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate next)
{
if (context.ScheduledTime is not { } scheduledTime)
Expand All @@ -30,18 +30,9 @@ public async ValueTask InvokeAsync(IDispatchContext context, DispatchDelegate ne
return;
}

var feature = context.Features.GetOrSet<SchedulingMiddlewareFeature>();

if (feature.SkipScheduler)
{
await next(context);
return;
}

if (context.Envelope is null)
{
await next(context);
return;
throw ThrowHelper.EnvelopeNotSet();
}

if (context.Envelope.ScheduledTime != scheduledTime)
Expand Down
Loading
Loading