diff --git a/src/Mocha/src/Mocha.Analyzers/Generators/MessagingDependencyInjectionGenerator.cs b/src/Mocha/src/Mocha.Analyzers/Generators/MessagingDependencyInjectionGenerator.cs index 3742c019af8..0763c433773 100644 --- a/src/Mocha/src/Mocha.Analyzers/Generators/MessagingDependencyInjectionGenerator.cs +++ b/src/Mocha/src/Mocha.Analyzers/Generators/MessagingDependencyInjectionGenerator.cs @@ -40,7 +40,10 @@ public void Generate( var contextOnlyTypes = syntaxInfos.OfType().OrderBy(c => c.OrderByKey).ToList(); - if (handlers.Count == 0 && sagas.Count == 0 && contextOnlyTypes.Count == 0) + if (handlers.Count == 0 + && sagas.Count == 0 + && contextOnlyTypes.Count == 0 + && !syntaxInfos.Any(static info => info is MessageDeclarationsInfo { Declarations.Count: > 0 })) { return; } diff --git a/src/Mocha/src/Mocha.Analyzers/Inspectors/AddMessageDeclarationInspector.cs b/src/Mocha/src/Mocha.Analyzers/Inspectors/AddMessageDeclarationInspector.cs index 83e2c32020d..5ee6179abad 100644 --- a/src/Mocha/src/Mocha.Analyzers/Inspectors/AddMessageDeclarationInspector.cs +++ b/src/Mocha/src/Mocha.Analyzers/Inspectors/AddMessageDeclarationInspector.cs @@ -64,7 +64,7 @@ public bool TryHandle( // Capture declaration metadata (doc + span) cross-file from the resolved symbol. Metadata-only types // (declared in another assembly) carry no source declaration, so there is nothing to contribute. This // is stale only in the IDE's incremental cache; every real compiler invocation runs fresh. - var declaredMessageType = messageType.ToDeclaredTypeInfo(cancellationToken); + var declaredMessageType = messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken); if (declaredMessageType is null) { return false; diff --git a/src/Mocha/src/Mocha.Analyzers/Inspectors/CallSiteMessageTypeInspector.cs b/src/Mocha/src/Mocha.Analyzers/Inspectors/CallSiteMessageTypeInspector.cs index 9175de7bf59..1ba45c4ba4c 100644 --- a/src/Mocha/src/Mocha.Analyzers/Inspectors/CallSiteMessageTypeInspector.cs +++ b/src/Mocha/src/Mocha.Analyzers/Inspectors/CallSiteMessageTypeInspector.cs @@ -8,23 +8,8 @@ namespace Mocha.Analyzers.Inspectors; /// -/// Inspects dispatch call sites (SendAsync, PublishAsync, RequestAsync, -/// QueryAsync, etc.) on IMessageBus, ISender, and IPublisher -/// to extract the compile-time message and response types being dispatched. +/// Extracts message and response types from message bus and mediator dispatch calls. /// -/// -/// -/// The extracted types feed downstream generators and analyzers that verify serializer -/// registrations (MO0018) and handler existence (MO0020). -/// -/// -/// Type extraction varies by method shape: for most generic methods the message type comes -/// from the type argument T, but for RequestAsync<TResponse> the type -/// argument is the response type - the message type is inferred from the first -/// argument's compile-time type instead. Non-generic overloads (e.g. -/// RequestAsync(object, …)) also fall back to argument-expression analysis. -/// -/// public sealed class CallSiteMessageTypeInspector : ISyntaxInspector { /// @@ -62,7 +47,6 @@ public bool TryHandle( return false; } - // Try IMessageBus if (knownSymbols.IMessageBus is not null && SymbolEqualityComparer.Default.Equals(receiverType, knownSymbols.IMessageBus)) { @@ -80,7 +64,7 @@ public bool TryHandle( if (knownSymbols.IPublisher is not null && SymbolEqualityComparer.Default.Equals(receiverType, knownSymbols.IPublisher)) { - return TryHandlePublisher(methodSymbol, invocation, cancellationToken, out syntaxInfo); + return TryHandlePublisher(methodSymbol, invocation, semanticModel, cancellationToken, out syntaxInfo); } return false; @@ -134,14 +118,13 @@ private static bool TryHandleMessageBus( argTypeName, kind, argLocation, - DeclaredMessageType: argType.ToDeclaredTypeInfo(cancellationToken)); + DeclaredMessageType: argType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken)); return true; } return false; } - // All other IMessageBus methods are generic - extract T from type arguments. if (methodSymbol.TypeArguments.Length == 0) { return false; @@ -172,7 +155,9 @@ private static bool TryHandleMessageBus( responseTypeName = methodSymbol .TypeArguments[0] .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - declaredResponseType = methodSymbol.TypeArguments[0].ToDeclaredTypeInfo(cancellationToken); + declaredResponseType = methodSymbol.TypeArguments[0].ToDeclaredTypeInfo( + semanticModel.Compilation, + cancellationToken); } syntaxInfo = new CallSiteMessageTypeInfo( @@ -180,7 +165,7 @@ private static bool TryHandleMessageBus( kind, location, responseTypeName, - firstArgType.ToDeclaredTypeInfo(cancellationToken), + firstArgType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken), declaredResponseType); return true; } @@ -199,7 +184,7 @@ private static bool TryHandleMessageBus( typeName, kind, locationInfo, - DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken)); + DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken)); return true; } @@ -254,13 +239,14 @@ private static bool TryHandleSender( typeName, kind, locationInfo, - DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken)); + DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken)); return true; } private static bool TryHandlePublisher( IMethodSymbol methodSymbol, InvocationExpressionSyntax invocation, + SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxInfo? syntaxInfo) { @@ -289,7 +275,7 @@ private static bool TryHandlePublisher( typeName, CallSiteKind.MediatorPublish, locationInfo, - DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken)); + DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken)); return true; } diff --git a/src/Mocha/src/Mocha.Analyzers/Inspectors/MessagingHandlerInspector.cs b/src/Mocha/src/Mocha.Analyzers/Inspectors/MessagingHandlerInspector.cs index 6df9992f840..c3385fa4532 100644 --- a/src/Mocha/src/Mocha.Analyzers/Inspectors/MessagingHandlerInspector.cs +++ b/src/Mocha/src/Mocha.Analyzers/Inspectors/MessagingHandlerInspector.cs @@ -115,8 +115,8 @@ public bool TryHandle( // their resolved symbols, so this handler is one of several discovery sources merged by type name. // Metadata-only types (declared in another assembly) yield null. This is stale only in the IDE's // incremental cache; every real compiler invocation runs fresh. - var declaredMessageType = messageSymbol.ToDeclaredTypeInfo(cancellationToken); - var declaredResponseType = responseType.ToDeclaredTypeInfo(cancellationToken); + var declaredMessageType = messageSymbol.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken); + var declaredResponseType = responseType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken); syntaxInfo = new MessagingHandlerInfo( handlerFullName, diff --git a/src/Mocha/src/Mocha.Analyzers/MessagingGenerator.cs b/src/Mocha/src/Mocha.Analyzers/MessagingGenerator.cs index 3c73a1e141f..ed0266d09bf 100644 --- a/src/Mocha/src/Mocha.Analyzers/MessagingGenerator.cs +++ b/src/Mocha/src/Mocha.Analyzers/MessagingGenerator.cs @@ -390,6 +390,7 @@ private static bool IsJsonSerializableAttributeCandidate(SyntaxNode node) CreateJsonSerializableTypeInfo( serializableType, attribute.GetLocation().ToDeclarationLocationInfo(), + semanticModel.Compilation, cancellationToken)); } @@ -458,9 +459,14 @@ private static MessageDeclarationsInfo BuildMessageDeclarations( // Sources B and C: dispatch call sites and explicit AddMessage registrations. foreach (var info in callSiteInfos) { - if (info is CallSiteMessageTypeInfo callSite) + if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind)) { - AddDeclaration(byTypeName, callSite.DeclaredMessageType); + // A message is dispatched as its runtime type, which is never an interface or an abstract class. + if (callSite.DeclaredMessageType is { IsAbstract: false }) + { + AddDeclaration(byTypeName, callSite.DeclaredMessageType); + } + AddDeclaration(byTypeName, callSite.DeclaredResponseType); } else if (info is AddMessageDeclarationInfo addMessage) @@ -516,12 +522,13 @@ private static DeclaredTypeInfo MergeDeclarations(DeclaredTypeInfo first, Declar // Prefer the entry with the ordinally smallest location; a null location always loses. var location = LocationInfo.Min(first.Location, second.Location); - return new DeclaredTypeInfo(first.TypeName, xmlDocumentation, location); + return new DeclaredTypeInfo(first.TypeName, xmlDocumentation, location, first.IsAbstract); } private static JsonSerializableTypeInfo CreateJsonSerializableTypeInfo( INamedTypeSymbol serializableType, LocationInfo? location, + Compilation compilation, CancellationToken cancellationToken) { var typeName = serializableType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); @@ -545,7 +552,7 @@ private static JsonSerializableTypeInfo CreateJsonSerializableTypeInfo( // Capture the declaration metadata (doc + location) cross-file from the resolved symbol so // context-only types (serializable types with no handler) still carry their own declaration. // This is stale only in the IDE's incremental cache; every real compiler invocation runs fresh. - var declaration = serializableType.ToDeclaredTypeInfo(cancellationToken); + var declaration = serializableType.ToDeclaredTypeInfo(compilation, cancellationToken); return new JsonSerializableTypeInfo( typeName, @@ -741,8 +748,7 @@ private static void AddRequiredCallSiteTypes( { foreach (var info in callSiteInfos) { - if (info is CallSiteMessageTypeInfo callSite - && callSite.Kind is not (CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish)) + if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind)) { requiredTypes.Add(callSite.MessageTypeName); @@ -800,8 +806,7 @@ private static void ValidateCallSiteJsonContext( // dispatch is in-process and does not require JSON serialization. foreach (var info in callSiteInfos) { - if (info is CallSiteMessageTypeInfo callSite - && callSite.Kind is not (CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish)) + if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind)) { if (!coveredTypes.Contains(callSite.MessageTypeName)) { @@ -831,6 +836,9 @@ private static void ValidateCallSiteJsonContext( } } + private static bool IsMediatorCallSite(CallSiteKind kind) + => kind is CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish; + private static ImmutableArray ExtractContextOnlyTypes( ImmutableArray syntaxInfos, JsonContextInfo jsonContextInfo) diff --git a/src/Mocha/src/Mocha.Analyzers/Models/DeclaredTypeInfo.cs b/src/Mocha/src/Mocha.Analyzers/Models/DeclaredTypeInfo.cs index a26be49c115..bc44fc2a279 100644 --- a/src/Mocha/src/Mocha.Analyzers/Models/DeclaredTypeInfo.cs +++ b/src/Mocha/src/Mocha.Analyzers/Models/DeclaredTypeInfo.cs @@ -16,7 +16,11 @@ namespace Mocha.Analyzers; /// /// The full source location of the type declaration, or if unavailable. /// +/// +/// when the declared type is an interface or an abstract class. +/// public sealed record DeclaredTypeInfo( string TypeName, string? XmlDocumentation, - LocationInfo? Location); + LocationInfo? Location, + bool IsAbstract); diff --git a/src/Mocha/src/Mocha.Analyzers/README.md b/src/Mocha/src/Mocha.Analyzers/README.md index c6e74c2e904..4ece2380a60 100644 --- a/src/Mocha/src/Mocha.Analyzers/README.md +++ b/src/Mocha/src/Mocha.Analyzers/README.md @@ -88,7 +88,7 @@ Classes (not records) that inherit from `Saga` are discovered. The inspe ## Call-Site Discovery -Invocations on `IMessageBus`, `ISender`, and `IPublisher` are inspected to discover message types used at call sites. These are used for validation only (no code generation). +Invocations on `IMessageBus`, `ISender`, and `IPublisher` are inspected to discover message types used at call sites. Message types found at `IMessageBus` call sites are validated and, when they are declared in the same assembly, registered with `AddMessage` in the generated module. A type that the generated code cannot reference, such as a private nested type, a file-local type, an anonymous type, or a type that contains a type parameter, is not registered. An interface or an abstract class at a call site is not registered either. Mediator call sites are used for validation only. ### IMessageBus Methods @@ -264,7 +264,7 @@ For each message type registration, the generator computes an "enclosed types" a **Fires when (AOT mode):** A message type used in a dispatch call (`PublishAsync`, `SendAsync`, etc.) is not found in the local `JsonSerializerContext` or imported module types. -**Scope:** Only messaging dispatch calls - mediator dispatch (`ISender.SendAsync`, `ISender.QueryAsync`, `IPublisher.PublishAsync`) is excluded because it's in-process. +**Scope:** Dispatch calls on `IMessageBus`. Mediator dispatch is excluded. > **Note:** MO0017 is reserved and not currently used. diff --git a/src/Mocha/src/Mocha.Analyzers/Utils/RoslynExtensions.cs b/src/Mocha/src/Mocha.Analyzers/Utils/RoslynExtensions.cs index 792b599546f..d4dd1ed9253 100644 --- a/src/Mocha/src/Mocha.Analyzers/Utils/RoslynExtensions.cs +++ b/src/Mocha/src/Mocha.Analyzers/Utils/RoslynExtensions.cs @@ -168,11 +168,13 @@ public static bool ImplementsInterface(this INamedTypeSymbol type, INamedTypeSym /// /// /// A for a source declaration; for a - /// metadata-only type that has no source declaration in the current compilation, or a non-named - /// type that cannot carry source declaration metadata. + /// metadata-only type that has no source declaration in the current compilation, a non-named + /// type that cannot carry source declaration metadata, or a type that code generated into + /// cannot reference. /// public static DeclaredTypeInfo? ToDeclaredTypeInfo( this ITypeSymbol? type, + Compilation compilation, CancellationToken cancellationToken) { if (type is not INamedTypeSymbol namedType) @@ -182,7 +184,7 @@ public static bool ImplementsInterface(this INamedTypeSymbol type, INamedTypeSym var location = namedType.GetDeclarationLocationInfo(cancellationToken); - if (location is null) + if (location is null || !IsReferenceableFromGeneratedCode(namedType, compilation)) { return null; } @@ -190,6 +192,48 @@ public static bool ImplementsInterface(this INamedTypeSymbol type, INamedTypeSym return new DeclaredTypeInfo( namedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), namedType.GetXmlDocumentation(cancellationToken), - location); + location, + namedType.IsAbstract); + } + + private static bool IsReferenceableFromGeneratedCode(ITypeSymbol type, Compilation compilation) + => compilation.IsSymbolAccessibleWithin(type, compilation.Assembly) && !ContainsUnnameableType(type); + + // A type is unnameable when, at any depth, it contains a type that a fully qualified name in a separate, + // safe-context file cannot denote: a file-local, anonymous, error, pointer or function pointer type, or a + // type parameter. + private static bool ContainsUnnameableType(ITypeSymbol type) + { + switch (type) + { + case IArrayTypeSymbol array: + return ContainsUnnameableType(array.ElementType); + + case INamedTypeSymbol { TypeKind: not TypeKind.Error } named: + for (var current = named; current is not null; current = current.ContainingType) + { + if (current.IsFileLocal || current.IsAnonymousType) + { + return true; + } + + foreach (var typeArgument in current.TypeArguments) + { + if (ContainsUnnameableType(typeArgument)) + { + return true; + } + } + } + + return false; + + default: + return type.TypeKind + is TypeKind.TypeParameter + or TypeKind.Error + or TypeKind.Pointer + or TypeKind.FunctionPointer; + } } } diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/MessagingTestHelper.cs b/src/Mocha/test/Mocha.Analyzers.Tests/MessagingTestHelper.cs index c0594e1ed3c..1ae4729c4a2 100644 --- a/src/Mocha/test/Mocha.Analyzers.Tests/MessagingTestHelper.cs +++ b/src/Mocha/test/Mocha.Analyzers.Tests/MessagingTestHelper.cs @@ -203,6 +203,9 @@ private static CSharpCompilation CreateCompilation( // Mocha (IConsumer, IBatchEventHandler, Saga, SagaStateBase) MetadataReference.CreateFromFile(typeof(IConsumer).Assembly.Location), + // Mocha.Mediator (IPublisher and ISender) + MetadataReference.CreateFromFile(typeof(Mediator.IPublisher).Assembly.Location), + // Mocha.Utilities (FeatureCollectionExtensions) MetadataReference.CreateFromFile(typeof(Features.FeatureCollectionExtensions).Assembly.Location), diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/OutboxCallSiteTests.cs b/src/Mocha/test/Mocha.Analyzers.Tests/OutboxCallSiteTests.cs new file mode 100644 index 00000000000..6ae4262ddbe --- /dev/null +++ b/src/Mocha/test/Mocha.Analyzers.Tests/OutboxCallSiteTests.cs @@ -0,0 +1,378 @@ +using Microsoft.CodeAnalysis; + +namespace Mocha.Analyzers.Tests; + +public class OutboxCallSiteTests +{ + [Theory] + [InlineData("await bus.PublishAsync(new Ping(), cancellationToken);")] + public void Generate_Should_SkipMessage_When_PublishedTypeIsPrivateNested(string dispatch) + { + // arrange + var source = CreatePublisherSource(dispatch, nestedTypes: "private sealed record Ping;"); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Theory] + [InlineData("protected sealed record Ping;", "new Ping()")] + [InlineData("private protected sealed record Ping;", "new Ping()")] + [InlineData("protected class Messages { public sealed record Ping; }", "new Messages.Ping()")] + public void Generate_Should_SkipMessage_When_PublishedTypeIsProtectedNested(string nestedTypes, string message) + { + // arrange + var source = CreatePublisherSource( + $"await bus.PublishAsync({message}, cancellationToken);", + nestedTypes: nestedTypes); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Fact] + public void Generate_Should_SkipMessage_When_PublishedTypeIsFileLocal() + { + // arrange + var source = CreatePublisherSource( + "await bus.PublishAsync(new Ping(), cancellationToken);", + topLevelTypes: "file sealed record Ping;"); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Theory] + [InlineData("new Envelope(new Ping())")] + [InlineData("new Envelope<(Ping, int)>((new Ping(), 1))")] + public void Generate_Should_SkipMessage_When_TypeArgumentIsPrivateNested(string message) + { + // arrange + var source = CreatePublisherSource( + $"await bus.PublishAsync({message}, cancellationToken);", + nestedTypes: "private sealed record Ping;", + topLevelTypes: "public sealed record Envelope(T Payload);"); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Theory] + [InlineData("bus.PublishAsync(new Envelope(payload), cancellationToken)")] + public void Generate_Should_SkipMessage_When_TypeArgumentIsTypeParameter(string dispatch) + { + // arrange + var source = CreateEnvelopeSource( + $$""" + public ValueTask PublishAsync( + IMessageBus bus, + T payload, + CancellationToken cancellationToken) + => {{dispatch}}; + """); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Fact] + public void Generate_Should_SkipMessage_When_ContainingTypeHasTypeParameter() + { + // arrange + var source = CreateEnvelopeSource( + """ + public sealed class Feature + { + public ValueTask PublishAsync(IMessageBus bus, CancellationToken cancellationToken) + => bus.PublishAsync(new Started(), cancellationToken); + + public sealed record Started; + } + """); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Fact] + public void Generate_Should_SkipMessage_When_TypeArgumentIsAnonymousType() + { + // arrange + var source = CreateEnvelopeSource( + """ + public ValueTask PublishAsync(IMessageBus bus, CancellationToken cancellationToken) + => bus.PublishAsync(Envelope.Create(new { OrderId = 1 }), cancellationToken); + """); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Theory] + [InlineData("IDomainEvent message = new Ping(); await bus.PublishAsync(message, cancellationToken);")] + [InlineData("EventBase message = new Pong(); await bus.SendAsync(message, cancellationToken);")] + public void Generate_Should_SkipMessage_When_PublishedTypeIsInterfaceOrAbstract(string dispatch) + { + // arrange + var source = CreatePublisherSource( + dispatch, + topLevelTypes: """ + public interface IDomainEvent; + + public sealed record Ping : IDomainEvent; + + public abstract record EventBase; + + public sealed record Pong : EventBase; + """); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + [Fact] + public async Task Generate_Should_RegisterMessage_When_TypeArgumentIsAccessible() + { + // arrange + var source = CreateEnvelopeSource( + """ + public async ValueTask PublishAsync(IMessageBus bus, CancellationToken cancellationToken) + { + await bus.PublishAsync(new Envelope(new OrderPlaced()), cancellationToken); + await bus.PublishAsync(new Envelope([]), cancellationToken); + } + """); + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var snapshot = MessagingTestHelper.GetGeneratedSourceSnapshot([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + await snapshot.MatchMarkdownAsync(TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Generate_Should_RegisterMessage_When_PublishedTypeIsInternalNested() + { + // arrange + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using Mocha; + + namespace TestApp; + + internal sealed class Messages + { + internal sealed record OrderPlaced; + } + + public class Dispatcher + { + public async ValueTask DispatchAsync(IMessageBus bus, CancellationToken cancellationToken) + { + await bus.PublishAsync(new Messages.OrderPlaced(), cancellationToken); + await bus.PublishAsync(new OrderShipped(), cancellationToken); + } + + protected internal sealed record OrderShipped; + } + """; + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var snapshot = MessagingTestHelper.GetGeneratedSourceSnapshot([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + await snapshot.MatchMarkdownAsync(TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Generate_Should_SkipPrivateNestedMessage_When_AssemblyHasHandler() + { + // arrange + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using Mocha; + + namespace TestApp; + + public sealed record IncomingMessage; + + public sealed class IncomingHandler : IEventHandler + { + public ValueTask HandleAsync(IncomingMessage message, CancellationToken cancellationToken) + => default; + } + + public sealed class Dispatcher + { + public ValueTask DispatchAsync(IMessageBus bus, CancellationToken cancellationToken) + => bus.PublishAsync(new Ping(), cancellationToken); + + private sealed record Ping; + } + """; + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var snapshot = MessagingTestHelper.GetGeneratedSourceSnapshot([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + await snapshot.MatchMarkdownAsync(TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Generate_Should_RegisterOnlyPublicMessage_When_PublicAndPrivateNestedTypesArePublished() + { + // arrange + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using Mocha; + + namespace TestApp; + + public sealed record OrderPlaced; + + public sealed class Dispatcher + { + public async ValueTask DispatchAsync(IMessageBus bus, CancellationToken cancellationToken) + { + await bus.PublishAsync(new OrderPlaced(), cancellationToken); + await bus.PublishAsync(new Ping(), cancellationToken); + } + + private sealed record Ping; + } + """; + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var snapshot = MessagingTestHelper.GetGeneratedSourceSnapshot([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + await snapshot.MatchMarkdownAsync(TestContext.Current.CancellationToken); + } + + [Fact] + public void Generate_Should_IgnoreMediatorMessage_When_ApplicationHasNoBusDispatch() + { + // arrange + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using Mocha.Mediator; + + namespace TestApp; + + public sealed record OutboundMessage : INotification; + + public sealed class Dispatcher + { + public ValueTask DispatchAsync(IPublisher publisher, CancellationToken cancellationToken) + => publisher.PublishAsync(new OutboundMessage(), cancellationToken); + } + """; + + // act + var diagnostics = MessagingTestHelper.GetCompilationDiagnostics([source]); + var sources = MessagingTestHelper.GetGeneratedSourceTexts([source]); + + // assert + Assert.Empty(diagnostics.Where(static d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(sources); + } + + private static string CreatePublisherSource( + string dispatch, + string nestedTypes = "", + string topLevelTypes = "") + => $$""" + using System.Threading; + using System.Threading.Tasks; + using Mocha; + + namespace TestApp; + + {{topLevelTypes}} + + public class Dispatcher + { + public async ValueTask DispatchAsync(IMessageBus bus, CancellationToken cancellationToken) + { + {{dispatch}} + } + + {{nestedTypes}} + } + """; + + private static string CreateEnvelopeSource(string dispatcherMembers) + => $$""" + using System.Threading; + using System.Threading.Tasks; + using Mocha; + + namespace TestApp; + + public sealed record OrderPlaced; + + public sealed record Envelope(T Payload); + + public static class Envelope + { + public static Envelope Create(T payload) => new(payload); + } + + public sealed class Dispatcher + { + {{dispatcherMembers}} + } + """; +} diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_PublishedTypeIsInternalNested.md b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_PublishedTypeIsInternalNested.md new file mode 100644 index 00000000000..e99244325d5 --- /dev/null +++ b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_PublishedTypeIsInternalNested.md @@ -0,0 +1,59 @@ +# Generate_Should_RegisterMessage_When_PublishedTypeIsInternalNested + +```csharp +// + +#nullable enable +#pragma warning disable + +namespace Microsoft.Extensions.DependencyInjection +{ + [global::System.CodeDom.Compiler.GeneratedCode("Mocha.Analyzers", "1.0.0")] + public static partial class TestsMessageBusBuilderExtensions + { + public static global::Mocha.IMessageBusHostBuilder AddTests( + this global::Mocha.IMessageBusHostBuilder builder) + { + + // --- Message Types --- + global::Mocha.MessageBusHostBuilderExtensions.AddMessage(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.Dispatcher.OrderShipped", + typeof(global::TestApp.Dispatcher.OrderShipped), + __Initialize_OrderShipped_MessageType_pDw7iHQsBFVbwf95ivKPCg)); + global::Mocha.MessageBusHostBuilderExtensions.AddMessage(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.Messages.OrderPlaced", + typeof(global::TestApp.Messages.OrderPlaced), + __Initialize_OrderPlaced_MessageType_qTTIqVq4mHUibXne3y99KA)); + + return builder; + } + + private static void __Initialize_OrderShipped_MessageType_pDw7iHQsBFVbwf95ivKPCg(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 20, 5, 20, 51) + }; + } + + private static void __Initialize_OrderPlaced_MessageType_qTTIqVq4mHUibXne3y99KA(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 9, 5, 9, 40) + }; + } + } +} + +``` diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_TypeArgumentIsAccessible.md b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_TypeArgumentIsAccessible.md new file mode 100644 index 00000000000..0a5ab5a4f1e --- /dev/null +++ b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterMessage_When_TypeArgumentIsAccessible.md @@ -0,0 +1,59 @@ +# Generate_Should_RegisterMessage_When_TypeArgumentIsAccessible + +```csharp +// + +#nullable enable +#pragma warning disable + +namespace Microsoft.Extensions.DependencyInjection +{ + [global::System.CodeDom.Compiler.GeneratedCode("Mocha.Analyzers", "1.0.0")] + public static partial class TestsMessageBusBuilderExtensions + { + public static global::Mocha.IMessageBusHostBuilder AddTests( + this global::Mocha.IMessageBusHostBuilder builder) + { + + // --- Message Types --- + global::Mocha.MessageBusHostBuilderExtensions.AddMessage>(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.Envelope", + typeof(global::TestApp.Envelope), + __Initialize_OrderPlaced__MessageType_GOt64v_sR2u47RskwCNU9g)); + global::Mocha.MessageBusHostBuilderExtensions.AddMessage>(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.Envelope", + typeof(global::TestApp.Envelope), + __Initialize_OrderPlaced____MessageType__31geCEop8qou_SBuLvB38w)); + + return builder; + } + + private static void __Initialize_OrderPlaced__MessageType_GOt64v_sR2u47RskwCNU9g(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 9, 1, 9, 45) + }; + } + + private static void __Initialize_OrderPlaced____MessageType__31geCEop8qou_SBuLvB38w(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 9, 1, 9, 45) + }; + } + } +} + +``` diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterOnlyPublicMessage_When_PublicAndPrivateNestedTypesArePublished.md b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterOnlyPublicMessage_When_PublicAndPrivateNestedTypesArePublished.md new file mode 100644 index 00000000000..fcb3b34c5ab --- /dev/null +++ b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_RegisterOnlyPublicMessage_When_PublicAndPrivateNestedTypesArePublished.md @@ -0,0 +1,42 @@ +# Generate_Should_RegisterOnlyPublicMessage_When_PublicAndPrivateNestedTypesArePublished + +```csharp +// + +#nullable enable +#pragma warning disable + +namespace Microsoft.Extensions.DependencyInjection +{ + [global::System.CodeDom.Compiler.GeneratedCode("Mocha.Analyzers", "1.0.0")] + public static partial class TestsMessageBusBuilderExtensions + { + public static global::Mocha.IMessageBusHostBuilder AddTests( + this global::Mocha.IMessageBusHostBuilder builder) + { + + // --- Message Types --- + global::Mocha.MessageBusHostBuilderExtensions.AddMessage(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.OrderPlaced", + typeof(global::TestApp.OrderPlaced), + __Initialize_OrderPlaced_MessageType_J0AkFRcpb2y_xl31xPEBhg)); + + return builder; + } + + private static void __Initialize_OrderPlaced_MessageType_J0AkFRcpb2y_xl31xPEBhg(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 7, 1, 7, 34) + }; + } + } +} + +``` diff --git a/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_SkipPrivateNestedMessage_When_AssemblyHasHandler.md b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_SkipPrivateNestedMessage_When_AssemblyHasHandler.md new file mode 100644 index 00000000000..a90f684e24b --- /dev/null +++ b/src/Mocha/test/Mocha.Analyzers.Tests/__snapshots__/OutboxCallSiteTests.Generate_Should_SkipPrivateNestedMessage_When_AssemblyHasHandler.md @@ -0,0 +1,71 @@ +# Generate_Should_SkipPrivateNestedMessage_When_AssemblyHasHandler + +```csharp +// + +#nullable enable +#pragma warning disable + +namespace Microsoft.Extensions.DependencyInjection +{ + [global::System.CodeDom.Compiler.GeneratedCode("Mocha.Analyzers", "1.0.0")] + public static partial class TestsMessageBusBuilderExtensions + { + [global::Mocha.MessagingModuleInfo( + HandlerTypes = new global::System.Type[] + { + typeof(global::TestApp.IncomingHandler), + } + )] + public static global::Mocha.IMessageBusHostBuilder AddTests( + this global::Mocha.IMessageBusHostBuilder builder) + { + + // --- Message Types --- + global::Mocha.MessageBusHostBuilderExtensions.AddMessage(builder); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.IncomingMessage", + typeof(global::TestApp.IncomingMessage), + __Initialize_IncomingMessage_MessageType_VoTTuNw1wU1Ci8sx668MlQ)); + + // --- Event Handlers --- + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped( + builder.Services); + global::Mocha.MessageBusHostBuilderExtensions.AddConsumer( + builder, + static () => global::Mocha.ConsumerFactory.Subscribe()); + global::Mocha.MessageBusHostBuilderExtensions.ConfigureDescriptorContext( + builder, + static ctx => global::Mocha.Features.FeatureCollectionExtensions.GetRequired(ctx.Features) + .Configurations.TryAdd( + "Tests::TestApp.IncomingHandler", + typeof(global::TestApp.IncomingHandler), + __Initialize_IncomingHandler_Consumer_guxr5wPWpfVIrke8uCQA7Q)); + + return builder; + } + + private static void __Initialize_IncomingMessage_MessageType_VoTTuNw1wU1Ci8sx668MlQ(global::Mocha.IMessageTypeDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 7, 1, 7, 38) + }; + } + + private static void __Initialize_IncomingHandler_Consumer_guxr5wPWpfVIrke8uCQA7Q(global::Mocha.IConsumerDescriptor descriptor) + { + descriptor.Extend().Configuration.Source = new global::Mocha.SourceMetadata + { + Assembly = "Tests", + DeclarationLocation = new global::Mocha.DeclarationLocation("", null, 9, 1, 13, 2) + }; + } + } +} + +``` diff --git a/website/content/docs/mocha/handler-registration.md b/website/content/docs/mocha/handler-registration.md index b56cefd4645..0d8b8c7b15a 100644 --- a/website/content/docs/mocha/handler-registration.md +++ b/website/content/docs/mocha/handler-registration.md @@ -26,6 +26,8 @@ The generator discovers these types: | `IConsumer` | Low-level consumer | | `Saga` | Saga orchestration | +The generated method also registers the message types that the assembly publishes or sends through `IMessageBus`, when they are declared in the same assembly. 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: register the concrete message types with `AddMessage()` when they must be known at startup, for example in a Native AOT application. + If you have used the [Mediator source generator](./mediator/index.md), this works the same way. The mediator generates `Add{ModuleName}()` on `IMediatorHostBuilder`; the message bus generates `Add{ModuleName}()` on `IMessageBusHostBuilder`. > **Recommendation:** Always use the source generator for handler registration. The generated code uses optimized, reflection-free registration paths. The source-generated output is designed for long-term stability across versions. Manual registration methods are available for edge cases but their internal behavior may change between releases. 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 3afec64c00d..f17c16ca008 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, 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, 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. @@ -274,6 +274,13 @@ 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. +## 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). +- When two referenced assemblies now generate a method with the same name, a call to it fails to compile with `CS0121`. Give one of them a distinct name with `[assembly: MessagingModule("Name")]`. +- The generated method no longer registers message types that the assembly dispatches only through the mediator (`ISender`, `IPublisher`). +- The generated method skips message types that generated code cannot reference: types that are not accessible from the whole assembly, such as private or protected nested types, file-local types, anonymous types, and types that contain a type parameter. The bus registers such a type when it is first published or sent. With `IsAotCompatible` set, that publish throws an `InvalidOperationException`. + # Health check, log, and trace changes ## The message bus health check is no longer tagged live