diff --git a/.editorconfig b/.editorconfig index fc93403b5ed..855a0523b93 100644 --- a/.editorconfig +++ b/.editorconfig @@ -309,6 +309,11 @@ dotnet_diagnostic.RCS1266.severity = warning # Unnecessary conditional access. dotnet_diagnostic.RCS9003.severity = warning +[**/Migrations/**.cs] +dotnet_analyzer_diagnostic.severity = none +dotnet_diagnostic.IDE0005.severity = none +dotnet_diagnostic.IDE0300.severity = none + # netstandard2.0 [src/HotChocolate/{Core/src/Types.Analyzers,Language}/**/*.cs] dotnet_diagnostic.CA1510.severity = none diff --git a/src/HotChocolate/Core/test/Types.Analyzers.Tests/ObjectTypeTests.XmlDocInference.cs b/src/HotChocolate/Core/test/Types.Analyzers.Tests/ObjectTypeTests.XmlDocInference.cs index 9bc14457090..629dca03bf7 100644 --- a/src/HotChocolate/Core/test/Types.Analyzers.Tests/ObjectTypeTests.XmlDocInference.cs +++ b/src/HotChocolate/Core/test/Types.Analyzers.Tests/ObjectTypeTests.XmlDocInference.cs @@ -268,7 +268,7 @@ internal static partial class Query "Parameter doc."); } - [Fact] + [Fact] public void XmlDocumentation_ForMethod_WithInheritdoc_Inside_Summary() { var snapshot = @@ -316,7 +316,7 @@ internal static partial class Query "My Parameter doc."); } - [Fact] + [Fact] public void XmlDocumentation_ForMethod_WithInheritdoc_Inside_Param() { var snapshot = @@ -364,7 +364,7 @@ internal static partial class Query "My Parameter doc. Inherited: Parameter doc."); } - [Fact] + [Fact] public void XmlDocumentation_ForMethod_WithInheritdoc_Inside_Returns() { var snapshot = @@ -412,7 +412,7 @@ internal static partial class Query "My Parameter doc."); } - [Fact] + [Fact] public void XmlDocumentation_ForMethod_WithInheritdoc_Inside_Exception() { var snapshot = diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/Issue7399Tests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/Issue7399Tests.cs index 716f3dfee1a..e99ef76c481 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/Issue7399Tests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/Issue7399Tests.cs @@ -1,5 +1,4 @@ using HotChocolate.Execution; -using HotChocolate.Execution.Configuration; using Microsoft.Extensions.DependencyInjection; namespace HotChocolate.Resolvers; diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs index 28d9259cb48..50174213574 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs @@ -1,7 +1,6 @@ using HotChocolate.Configuration; using HotChocolate.Features; using HotChocolate.Utilities; -using Microsoft.Extensions.DependencyInjection; namespace HotChocolate.Types.Descriptors; diff --git a/src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Planning/OperationPlanner.BuildExecutionTree.cs b/src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Planning/OperationPlanner.BuildExecutionTree.cs index 30d87dfde05..79d3898300c 100644 --- a/src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Planning/OperationPlanner.BuildExecutionTree.cs +++ b/src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Planning/OperationPlanner.BuildExecutionTree.cs @@ -195,11 +195,13 @@ bool IsEmptyOperation(OperationPlanStep step) return step.Definition.SelectionSet.Selections is [ FieldNode +#pragma warning disable format { Alias: null, Name.Value: IntrospectionFieldNames.TypeName, Directives: [{ Name.Value: "fusion__empty" }] } +#pragma warning restore format ]; } diff --git a/src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/FusionTestBase.cs b/src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/FusionTestBase.cs index 63f19c67fd9..ee278008e7f 100644 --- a/src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/FusionTestBase.cs +++ b/src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/FusionTestBase.cs @@ -2,7 +2,6 @@ using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using System.Net.Http; using System.Net; using System.Net.Http.Headers; using System.Text; diff --git a/src/Mocha/src/Demo/Demo.Billing/Program.cs b/src/Mocha/src/Demo/Demo.Billing/Program.cs index a1343dae9c0..c86b2da7d1a 100644 --- a/src/Mocha/src/Demo/Demo.Billing/Program.cs +++ b/src/Mocha/src/Demo/Demo.Billing/Program.cs @@ -75,10 +75,14 @@ await db.Invoices.Include(i => i.Payments).FirstOrDefaultAsync(i => i.OrderId == { var invoice = await db.Invoices.FirstOrDefaultAsync(i => i.Id == invoiceId); if (invoice is null) + { return Results.NotFound("Invoice not found"); + } if (invoice.Status == InvoiceStatus.Paid) + { return Results.BadRequest("Invoice already paid"); + } var payment = new Payment { diff --git a/src/Mocha/src/Demo/Demo.Catalog/Data/CatalogDbContext.cs b/src/Mocha/src/Demo/Demo.Catalog/Data/CatalogDbContext.cs index bf967ee38d4..f2eaa229f21 100644 --- a/src/Mocha/src/Demo/Demo.Catalog/Data/CatalogDbContext.cs +++ b/src/Mocha/src/Demo/Demo.Catalog/Data/CatalogDbContext.cs @@ -1,8 +1,6 @@ using Demo.Catalog.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Infrastructure; using Mocha.Outbox; using Mocha.Sagas.EfCore; diff --git a/src/Mocha/src/Demo/Demo.Catalog/JsonTopologyPrinter.cs b/src/Mocha/src/Demo/Demo.Catalog/JsonTopologyPrinter.cs index 8b7c2030eaf..ebb408719f1 100644 --- a/src/Mocha/src/Demo/Demo.Catalog/JsonTopologyPrinter.cs +++ b/src/Mocha/src/Demo/Demo.Catalog/JsonTopologyPrinter.cs @@ -20,7 +20,7 @@ namespace Explorer; /// public class JsonTopologyPrinter { - private static readonly JsonSerializerOptions JsonOptions = new() + private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, @@ -50,7 +50,7 @@ public string PrintTopology(MessagingRuntime runtime) ArgumentNullException.ThrowIfNull(runtime); var model = BuildTopologyModel(runtime); - return JsonSerializer.Serialize(model, JsonOptions); + return JsonSerializer.Serialize(model, s_jsonOptions); } public JsonBusModel BuildTopologyModel(MessagingRuntime runtime) @@ -287,14 +287,18 @@ private static JsonTopologyModel ExportGenericTopology(MessagingTransport transp foreach (var endpoint in transport.ReceiveEndpoints) { if (endpoint.Source is not null) + { outboundResources.Add(endpoint.Source); + } } // Dispatch endpoints connect to inbound resources (messages flow INTO transport) foreach (var endpoint in transport.DispatchEndpoints) { if (endpoint.Destination is not null) + { inboundResources.Add(endpoint.Destination); + } } foreach (var resource in outboundResources) @@ -312,7 +316,9 @@ private static JsonTopologyModel ExportGenericTopology(MessagingTransport transp { // Skip if already added as outbound (resource used for both directions) if (outboundResources.Contains(resource)) + { continue; + } entities.Add( new JsonTopologyEntity @@ -338,12 +344,16 @@ private static JsonTopologyModel ExportGenericTopology(MessagingTransport transp foreach (var consumer in runtime.Consumers) { if (consumer is not SagaConsumer sagaConsumer) + { continue; + } // Access the saga through reflection since SagaConsumer uses a primary constructor var saga = GetSagaFromConsumer(sagaConsumer); if (saga is null) + { continue; + } var sagaModel = new JsonSagaModel { @@ -473,7 +483,9 @@ private static List ExportSagaTransitions(SagaState sta private static string GetTypeName(Type type) { if (!type.IsGenericType) + { return type.Name; + } var genericTypeName = type.Name.Split('`')[0]; var genericArgs = string.Join(", ", type.GetGenericArguments().Select(GetTypeName)); diff --git a/src/Mocha/src/Demo/Demo.Catalog/Program.cs b/src/Mocha/src/Demo/Demo.Catalog/Program.cs index 6b2d87be222..6bd6602e9df 100644 --- a/src/Mocha/src/Demo/Demo.Catalog/Program.cs +++ b/src/Mocha/src/Demo/Demo.Catalog/Program.cs @@ -85,10 +85,14 @@ await db.Products.Include(p => p.Category).FirstOrDefaultAsync(p => p.Id == id) var product = await db.Products.FindAsync(request.ProductId); if (product is null) + { return Results.NotFound("Product not found"); + } if (product.StockQuantity < request.Quantity) + { return Results.BadRequest("Insufficient stock"); + } var order = new OrderRecord { @@ -191,7 +195,9 @@ await db.Orders.Include(o => o.Product).FirstOrDefaultAsync(o => o.Id == id) is // Verify order exists var order = await db.Orders.FindAsync(request.OrderId); if (order is null) + { return Results.NotFound("Order not found"); + } logger.LogInformation("Initiating quick refund saga for order {OrderId}", request.OrderId); @@ -232,10 +238,14 @@ await db.Orders.Include(o => o.Product).FirstOrDefaultAsync(o => o.Id == id) is // Verify order exists var order = await db.Orders.Include(o => o.Product).FirstOrDefaultAsync(o => o.Id == request.OrderId); if (order is null) + { return Results.NotFound("Order not found"); + } if (order.Status != OrderStatus.Delivered && order.Status != OrderStatus.Shipping) + { return Results.BadRequest($"Order cannot be returned in status: {order.Status}"); + } logger.LogInformation("Creating return label for order {OrderId}", request.OrderId); diff --git a/src/Mocha/src/Demo/Demo.Catalog/Sagas/QuickRefundSaga.cs b/src/Mocha/src/Demo/Demo.Catalog/Sagas/QuickRefundSaga.cs index fac6fc4e1c6..61bc534c165 100644 --- a/src/Mocha/src/Demo/Demo.Catalog/Sagas/QuickRefundSaga.cs +++ b/src/Mocha/src/Demo/Demo.Catalog/Sagas/QuickRefundSaga.cs @@ -28,7 +28,9 @@ protected override void Configure(ISagaDescriptor descriptor) descriptor .During(AwaitingRefund) .OnReply() - .Then((state, response) => { if (response.Success) + .Then((state, response) => + { + if (response.Success) { state.RefundId = response.RefundId; state.RefundedAmount = response.Amount; @@ -36,7 +38,8 @@ protected override void Configure(ISagaDescriptor descriptor) else { state.FailureReason = response.FailureReason ?? "Refund processing failed"; - } }) + } + }) .TransitionTo(Completed); // Note: We handle both success and failure in the same transition, diff --git a/src/Mocha/src/Demo/Demo.Catalog/Sagas/ReturnProcessingSaga.cs b/src/Mocha/src/Demo/Demo.Catalog/Sagas/ReturnProcessingSaga.cs index 6d00daaef33..3b72469e125 100644 --- a/src/Mocha/src/Demo/Demo.Catalog/Sagas/ReturnProcessingSaga.cs +++ b/src/Mocha/src/Demo/Demo.Catalog/Sagas/ReturnProcessingSaga.cs @@ -53,7 +53,9 @@ protected override void Configure(ISagaDescriptor descriptor) descriptor .During(AwaitingBothReplies) .OnReply() - .Then((state, response) => { if (response.Success) + .Then((state, response) => + { + if (response.Success) { state.RefundId = response.RefundId; state.RefundedAmount = response.Amount; @@ -62,14 +64,17 @@ protected override void Configure(ISagaDescriptor descriptor) else { state.FailureReason = response.FailureReason; - } }) + } + }) .TransitionTo(RefundDoneAwaitingRestock); // Waiting for refund after restock done descriptor .During(RestockDoneAwaitingRefund) .OnReply() - .Then((state, response) => { if (response.Success) + .Then((state, response) => + { + if (response.Success) { state.RefundId = response.RefundId; state.RefundedAmount = response.Amount; @@ -78,7 +83,8 @@ protected override void Configure(ISagaDescriptor descriptor) else { state.FailureReason = response.FailureReason; - } }) + } + }) .TransitionTo(Completed); // Waiting for restock after refund done diff --git a/src/Mocha/src/Demo/Demo.ServiceDefaults/Extensions.cs b/src/Mocha/src/Demo/Demo.ServiceDefaults/Extensions.cs index c0281fad6de..141ae9df586 100644 --- a/src/Mocha/src/Demo/Demo.ServiceDefaults/Extensions.cs +++ b/src/Mocha/src/Demo/Demo.ServiceDefaults/Extensions.cs @@ -1,134 +1,133 @@ -using System.Text.Json.Serialization; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.AspNetCore.Http.Json; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.ServiceDiscovery; -using OpenTelemetry; -using OpenTelemetry.Metrics; -using OpenTelemetry.Trace; - -namespace Microsoft.Extensions.Hosting; - -// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. -// This project should be referenced by each service project in your solution. -// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults -public static class Extensions -{ - private const string HealthEndpointPath = "/health"; - private const string AlivenessEndpointPath = "/alive"; - - public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder - { - builder.ConfigureOpenTelemetry(); - - builder.AddDefaultHealthChecks(); - - builder.Services.AddServiceDiscovery(); - - builder.Services.ConfigureHttpClientDefaults(http => - { - // Turn on resilience by default - http.AddStandardResilienceHandler(); - - // Turn on service discovery by default - http.AddServiceDiscovery(); - }); - - // Uncomment the following to restrict the allowed schemes for service discovery. - // builder.Services.Configure(options => - // { - // options.AllowedSchemes = ["https"]; - // }); - - builder.Services.Configure(options => - options.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve); - - return builder; - } - - public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) - where TBuilder : IHostApplicationBuilder - { - builder.Logging.AddOpenTelemetry(logging => - { - logging.IncludeFormattedMessage = true; - logging.IncludeScopes = true; - }); - - builder - .Services.AddOpenTelemetry() - .WithMetrics(metrics => - metrics.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddRuntimeInstrumentation()) - .WithTracing(tracing => - { - tracing - .AddSource(builder.Environment.ApplicationName) - .AddSource("Mocha") - .AddAspNetCoreInstrumentation(tracing => - // Exclude health check requests from tracing - tracing.Filter = context => - !context.Request.Path.StartsWithSegments(HealthEndpointPath) - && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) - ) - // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) - //.AddGrpcClientInstrumentation() - .AddHttpClientInstrumentation(); - }); - - builder.AddOpenTelemetryExporters(); - - return builder; - } - - private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) - where TBuilder : IHostApplicationBuilder - { - var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); - - if (useOtlpExporter) - { - builder.Services.AddOpenTelemetry().UseOtlpExporter(); - } - - // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) - //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) - //{ - // builder.Services.AddOpenTelemetry() - // .UseAzureMonitor(); - //} - - return builder; - } - - public static TBuilder AddDefaultHealthChecks(this TBuilder builder) - where TBuilder : IHostApplicationBuilder - { - builder - .Services.AddHealthChecks() - // Add a default liveness check to ensure app is responsive - .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); - - return builder; - } - - public static WebApplication MapDefaultEndpoints(this WebApplication app) - { - // Adding health checks endpoints to applications in non-development environments has security implications. - // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. - if (app.Environment.IsDevelopment()) - { - // All health checks must pass for app to be considered ready to accept traffic after starting - app.MapHealthChecks(HealthEndpointPath); - - // Only health checks tagged with the "live" tag must pass for app to be considered alive - app.MapHealthChecks( - AlivenessEndpointPath, - new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }); - } - - return app; - } -} +using System.Text.Json.Serialization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.AspNetCore.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + builder.Services.Configure(options => + options.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder + .Services.AddOpenTelemetry() + .WithMetrics(metrics => + metrics.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddRuntimeInstrumentation()) + .WithTracing(tracing => + { + tracing + .AddSource(builder.Environment.ApplicationName) + .AddSource("Mocha") + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder + .Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks( + AlivenessEndpointPath, + new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }); + } + + return app; + } +} diff --git a/src/Mocha/src/Demo/Demo.Shipping/Program.cs b/src/Mocha/src/Demo/Demo.Shipping/Program.cs index b88d8827250..5e996b11b06 100644 --- a/src/Mocha/src/Demo/Demo.Shipping/Program.cs +++ b/src/Mocha/src/Demo/Demo.Shipping/Program.cs @@ -67,10 +67,14 @@ await db.Shipments.Include(s => s.Items).FirstOrDefaultAsync(s => s.OrderId == o { var shipment = await db.Shipments.FirstOrDefaultAsync(s => s.Id == id); if (shipment is null) + { return Results.NotFound("Shipment not found"); + } if (shipment.Status == ShipmentStatus.Shipped) + { return Results.BadRequest("Shipment already shipped"); + } shipment.Status = ShipmentStatus.Shipped; shipment.Carrier = request.Carrier; @@ -118,10 +122,14 @@ await db.ReturnShipments.FirstOrDefaultAsync(r => r.OrderId == orderId) is { } r { var returnShipment = await db.ReturnShipments.FirstOrDefaultAsync(r => r.Id == id); if (returnShipment is null) + { return Results.NotFound("Return shipment not found"); + } if (returnShipment.Status == ReturnShipmentStatus.Received) + { return Results.BadRequest("Return package already received"); + } returnShipment.Status = ReturnShipmentStatus.Received; returnShipment.ReceivedAt = DateTimeOffset.UtcNow; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/MessageBusOutboxWorker.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/MessageBusOutboxWorker.cs index 15297731a73..3dc2189a4c7 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/MessageBusOutboxWorker.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/MessageBusOutboxWorker.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Options; using Mocha.Threading; using Npgsql; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxMessage.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxMessage.cs index f9bafe5078d..b2adf2cfabf 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxMessage.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxMessage.cs @@ -1,5 +1,4 @@ using System.Text.Json; -using Mocha.Middlewares; namespace Mocha.Outbox; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs index f676e0d23ec..a405b4d2dd2 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs @@ -2,8 +2,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; -using Mocha; -using Mocha.Features; using Mocha.Middlewares; using Npgsql; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index ace1695619d..fa98a90c624 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -57,7 +57,7 @@ public static IEntityFrameworkCoreBuilder AddPostgresOutbox(this IEntityFramewor options.Queries = PostgresMessageOutboxQueries.From(tableInfo.Outbox); }); - builder.Services.AddSingleton(sp => + builder.Services.AddSingleton(sp => { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); @@ -70,7 +70,7 @@ public static IEntityFrameworkCoreBuilder AddPostgresOutbox(this IEntityFramewor options.Queries); }); - builder.Services.AddSingleton(sp => + builder.Services.AddSingleton(sp => { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index 996d7aaa36b..b272581c927 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -25,7 +25,7 @@ internal sealed class PostgresMessageOutbox : IMessageOutbox, IDisposable private readonly IOutboxSignal _signal; private readonly SemaphoreSlim _semaphore = new(1, 1); private PooledArrayWriter? _arrayWriter; - private string? _insertSql; + private readonly string? _insertSql; /// /// Creates a new using the provided DbContext connection, diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxMessageEntityConfiguration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxMessageEntityConfiguration.cs index 727fb157cc8..7f98a0a340b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxMessageEntityConfiguration.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxMessageEntityConfiguration.cs @@ -11,7 +11,7 @@ namespace Mocha.Outbox; internal sealed class PostgresOutboxMessageEntityConfiguration : IEntityTypeConfiguration { // Use default values from OutboxTableInfo as the source of truth - private static readonly OutboxTableInfo Defaults = new(); + private static readonly OutboxTableInfo s_defaults = new(); /// /// Gets the shared singleton instance of the outbox message entity configuration. @@ -24,17 +24,17 @@ internal sealed class PostgresOutboxMessageEntityConfiguration : IEntityTypeConf /// The entity type builder for . public void Configure(EntityTypeBuilder builder) { - builder.ToTable(Defaults.Table); + builder.ToTable(s_defaults.Table); - builder.HasKey(e => e.Id).HasName(Defaults.IxPrimaryKey); + builder.HasKey(e => e.Id).HasName(s_defaults.IxPrimaryKey); - builder.HasIndex(x => x.CreatedAt).HasDatabaseName(Defaults.IxCreatedAt).IsDescending(); + builder.HasIndex(x => x.CreatedAt).HasDatabaseName(s_defaults.IxCreatedAt).IsDescending(); - builder.HasIndex(x => x.TimesSent).HasDatabaseName(Defaults.IxTimesSent); + builder.HasIndex(x => x.TimesSent).HasDatabaseName(s_defaults.IxTimesSent); - builder.Property(x => x.Id).HasColumnName(Defaults.Id); - builder.Property(x => x.Envelope).HasColumnName(Defaults.Envelope).HasColumnType("json"); - builder.Property(x => x.TimesSent).HasColumnName(Defaults.TimesSent); - builder.Property(x => x.CreatedAt).HasColumnName(Defaults.CreatedAt); + builder.Property(x => x.Id).HasColumnName(s_defaults.Id); + builder.Property(x => x.Envelope).HasColumnName(s_defaults.Envelope).HasColumnType("json"); + builder.Property(x => x.TimesSent).HasColumnName(s_defaults.TimesSent); + builder.Property(x => x.CreatedAt).HasColumnName(s_defaults.CreatedAt); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/PostgresSagaStore.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/PostgresSagaStore.cs index d1d56a4d1da..efc01857074 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/PostgresSagaStore.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/PostgresSagaStore.cs @@ -2,7 +2,6 @@ using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Mocha.Sagas; using Mocha.Utils; using Npgsql; using NpgsqlTypes; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaServiceCollectionExtensions.cs index fd9e40c39df..93e6d571908 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Options; using Mocha.EntityFrameworkCore; using Mocha.EntityFrameworkCore.Postgres; -using Mocha.Sagas; using Mocha.Sagas.EfCore; using EfCoreSagaState = Mocha.Sagas.EfCore.SagaState; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaStateEntityConfiguration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaStateEntityConfiguration.cs index a6828f44e84..faf5ec4619a 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaStateEntityConfiguration.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Sagas/SagaStateEntityConfiguration.cs @@ -11,7 +11,7 @@ namespace Mocha.Sagas.EfCore; internal sealed class SagaStateEntityConfiguration : IEntityTypeConfiguration { // Use default values from SagaStateTableInfo as the source of truth - private static readonly SagaStateTableInfo Defaults = new(); + private static readonly SagaStateTableInfo s_defaults = new(); /// /// Gets the shared singleton instance of the saga state entity configuration. @@ -24,17 +24,17 @@ internal sealed class SagaStateEntityConfiguration : IEntityTypeConfigurationThe entity type builder for . public void Configure(EntityTypeBuilder builder) { - builder.ToTable(Defaults.Table); + builder.ToTable(s_defaults.Table); - builder.HasKey(e => new { e.Id, e.SagaName }).HasName(Defaults.IxPrimaryKey); + builder.HasKey(e => new { e.Id, e.SagaName }).HasName(s_defaults.IxPrimaryKey); - builder.HasIndex(x => x.CreatedAt).HasDatabaseName(Defaults.IxCreatedAt); + builder.HasIndex(x => x.CreatedAt).HasDatabaseName(s_defaults.IxCreatedAt); - builder.Property(x => x.Version).IsConcurrencyToken().HasColumnName(Defaults.Version); - builder.Property(x => x.Id).HasColumnName(Defaults.Id); - builder.Property(x => x.SagaName).HasColumnName(Defaults.SagaName); - builder.Property(x => x.State).HasColumnName(Defaults.State).HasColumnType("json"); - builder.Property(x => x.CreatedAt).HasColumnName(Defaults.CreatedAt); - builder.Property(x => x.UpdatedAt).HasColumnName(Defaults.UpdatedAt); + builder.Property(x => x.Version).IsConcurrencyToken().HasColumnName(s_defaults.Version); + builder.Property(x => x.Id).HasColumnName(s_defaults.Id); + builder.Property(x => x.SagaName).HasColumnName(s_defaults.SagaName); + builder.Property(x => x.State).HasColumnName(s_defaults.State).HasColumnType("json"); + builder.Property(x => x.CreatedAt).HasColumnName(s_defaults.CreatedAt); + builder.Property(x => x.UpdatedAt).HasColumnName(s_defaults.UpdatedAt); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index 24bfee24b86..967adc15884 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -1,7 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Mocha.Middlewares; namespace Mocha.EntityFrameworkCore; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/DbContextSagaStore.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/DbContextSagaStore.cs index df1969e008c..2617570d7c6 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/DbContextSagaStore.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/DbContextSagaStore.cs @@ -1,6 +1,5 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Mocha.Utils; @@ -154,7 +153,7 @@ private JsonDocument ToJsonDocument(Saga saga, SagaStateBase state) lock (_lock) { _arrayWriter ??= new PooledArrayWriter(); - _buffers ??= new List(); + _buffers ??= []; _arrayWriter.Reset(); saga.StateSerializer.Serialize(state, _arrayWriter); @@ -185,7 +184,7 @@ private JsonDocument ToJsonDocument(Saga saga, SagaStateBase state) var writtenMemory = _arrayWriter.WrittenMemory; - return saga.StateSerializer.Deserialize(writtenMemory) ?? default(T); + return saga.StateSerializer.Deserialize(writtenMemory) ?? default; } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/EfCoreSagaTransaction.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/EfCoreSagaTransaction.cs index 1a54c9481c6..ece2c5fa763 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/EfCoreSagaTransaction.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/EfCoreSagaTransaction.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore.Storage; -using Mocha.Outbox; namespace Mocha.Sagas.EfCore; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/SagaEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/SagaEntityFrameworkCorePersistenceBuilderExtensions.cs index 77108ea5790..981d9147944 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/SagaEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Sagas/SagaEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -1,5 +1,3 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Mocha.Sagas; using Mocha.Sagas.EfCore; diff --git a/src/Mocha/src/Mocha.Hosting/Topology/MessageBusEndpointRouteBuilderExtensions.cs b/src/Mocha/src/Mocha.Hosting/Topology/MessageBusEndpointRouteBuilderExtensions.cs index 5f0b5f42c75..3af32ec7a1c 100644 --- a/src/Mocha/src/Mocha.Hosting/Topology/MessageBusEndpointRouteBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.Hosting/Topology/MessageBusEndpointRouteBuilderExtensions.cs @@ -47,7 +47,7 @@ public static IEndpointConventionBuilder MapMessageBus( var description = MessageBusDescriptionVisitor.Visit(runtime); return Results.Content( - JsonSerializer.Serialize(description, s_jsonOptions), + JsonSerializer.Serialize(description, s_jsonOptions), "application/json"); }); } diff --git a/src/Mocha/src/Mocha.Threading/AsyncAutoResetEvent.cs b/src/Mocha/src/Mocha.Threading/AsyncAutoResetEvent.cs index 5cdec236e2b..5f4727d13f5 100644 --- a/src/Mocha/src/Mocha.Threading/AsyncAutoResetEvent.cs +++ b/src/Mocha/src/Mocha.Threading/AsyncAutoResetEvent.cs @@ -8,7 +8,7 @@ namespace Mocha.Threading; /// public sealed class AsyncAutoResetEvent(bool releaseAllOnSet = false) : IDisposable { - private static readonly Task _completedTask = Task.FromResult(true); + private static readonly Task s_completedTask = Task.FromResult(true); private readonly Queue> _waitingTasks = new(); private bool _signaled; @@ -35,7 +35,7 @@ public Task WaitAsync(CancellationToken cancellationToken) if (_signaled) { _signaled = false; - return _completedTask; + return s_completedTask; } var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); diff --git a/src/Mocha/src/Mocha.Threading/ContinuousTask.cs b/src/Mocha/src/Mocha.Threading/ContinuousTask.cs index 6b874596d20..9a005f4523a 100644 --- a/src/Mocha/src/Mocha.Threading/ContinuousTask.cs +++ b/src/Mocha/src/Mocha.Threading/ContinuousTask.cs @@ -23,7 +23,7 @@ public sealed class ContinuousTask : IAsyncDisposable private readonly CancellationTokenSource _completion = new(); private readonly Func _handler; private readonly Task _task; - private bool disposed; + private bool _disposed; /// /// Creates a new continuous task that immediately begins executing the specified handler. @@ -77,7 +77,7 @@ private async Task RunContinuously() /// public async ValueTask DisposeAsync() { - if (disposed) + if (_disposed) { return; } @@ -93,7 +93,7 @@ public async ValueTask DisposeAsync() _completion.Dispose(); - disposed = true; + _disposed = true; } } diff --git a/src/Mocha/src/Mocha.Transport.InMemory/InMemoryMessagingTransport.cs b/src/Mocha/src/Mocha.Transport.InMemory/InMemoryMessagingTransport.cs index 9b0a5cf4011..a426614c42a 100644 --- a/src/Mocha/src/Mocha.Transport.InMemory/InMemoryMessagingTransport.cs +++ b/src/Mocha/src/Mocha.Transport.InMemory/InMemoryMessagingTransport.cs @@ -325,7 +325,7 @@ protected override DispatchEndpoint CreateDispatchEndpoint() if (configuration is null && address is { Scheme: "queue" }) { - string? name = + var name = !string.IsNullOrEmpty(address.Host) ? address.Host : segmentCount == 1 ? new string(path[ranges[0]]) : null; @@ -337,7 +337,7 @@ protected override DispatchEndpoint CreateDispatchEndpoint() if (configuration is null && address is { Scheme: "topic" }) { - string? name = + var name = !string.IsNullOrEmpty(address.Host) ? address.Host : segmentCount == 1 ? new string(path[ranges[0]]) : null; diff --git a/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryBinding.cs b/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryBinding.cs index b9187681874..bd1dc24e660 100644 --- a/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryBinding.cs +++ b/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryBinding.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Mocha.Middlewares; namespace Mocha.Transport.InMemory; diff --git a/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryQueue.cs b/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryQueue.cs index 4315019b9e2..1ab96115972 100644 --- a/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryQueue.cs +++ b/src/Mocha/src/Mocha.Transport.InMemory/Topology/InMemoryQueue.cs @@ -1,5 +1,4 @@ using System.Buffers; -using System.Collections.Concurrent; using System.Collections.Immutable; using System.Threading.Channels; using Mocha.Middlewares; @@ -69,13 +68,13 @@ public IAsyncEnumerable ConsumeAsync(CancellationToken cancel /// Wraps a message envelope together with its pooled buffer for zero-copy in-memory transfer. /// /// -/// The underlying byte buffer is rented from and +/// The underlying byte buffer is rented from and /// must be returned by calling . Failing to dispose will cause pool exhaustion. /// public class InMemoryQueueItem : IDisposable { private readonly byte[] _buffer; - private MessageEnvelope _envelope; + private readonly MessageEnvelope _envelope; /// /// Creates a new queue item backed by the given envelope and pooled buffer. diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConnectionManagerBase.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConnectionManagerBase.cs index 4584e6ad127..6c460a0d7eb 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConnectionManagerBase.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConnectionManagerBase.cs @@ -13,7 +13,7 @@ public abstract class RabbitMQConnectionManagerBase : IAsyncDisposable { private const int InitialConnectionRetryDelaySeconds = 1; private const int MaxConnectionAttempts = 5; - private static readonly TimeSpan MaxBackoffDelay = TimeSpan.FromSeconds(60); + private static readonly TimeSpan s_maxBackoffDelay = TimeSpan.FromSeconds(60); private readonly Func> _connectionFactory; private readonly SemaphoreSlim _connectionLock = new(1, 1); @@ -276,7 +276,7 @@ private Task OnConnectionUnblockedAsync(object? sender, AsyncEventArgs e) private static TimeSpan CalculateBackoffDelay(TimeSpan baseDelay, int attempt) { var delay = baseDelay * Math.Pow(2, attempt - 1); - return delay > MaxBackoffDelay ? MaxBackoffDelay : delay; + return delay > s_maxBackoffDelay ? s_maxBackoffDelay : delay; } private async Task DisposeConnectionInternalAsync() diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConsumerManager.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConsumerManager.cs index 93eb2e53ff4..8754d58d010 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConsumerManager.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Connection/RabbitMQConsumerManager.cs @@ -1,7 +1,5 @@ using System.Collections.Immutable; -using System.Text; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -257,7 +255,8 @@ public required Func< BasicDeliverEventArgs, CancellationToken, ValueTask - > MessageHandler { get; init; } + > MessageHandler + { get; init; } /// /// Gets the maximum number of unacknowledged messages the broker delivers to this consumer. diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/IRabbitMQMessagingTransportDescriptor.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/IRabbitMQMessagingTransportDescriptor.cs index afd20145a32..576d770c119 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/IRabbitMQMessagingTransportDescriptor.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/IRabbitMQMessagingTransportDescriptor.cs @@ -1,5 +1,3 @@ -using RabbitMQ.Client; - namespace Mocha.Transport.RabbitMQ; /// diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/RabbitMQMessagingTransportDescriptor.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/RabbitMQMessagingTransportDescriptor.cs index e0de46d632c..7bffc3ff899 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/RabbitMQMessagingTransportDescriptor.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Descriptors/RabbitMQMessagingTransportDescriptor.cs @@ -1,5 +1,3 @@ -using RabbitMQ.Client; - namespace Mocha.Transport.RabbitMQ; /// diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQAcknowledgementMiddleware.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQAcknowledgementMiddleware.cs index ff5bae6a34f..73c1d948bc9 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQAcknowledgementMiddleware.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQAcknowledgementMiddleware.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Logging; using Mocha.Features; using Mocha.Middlewares; using Mocha.Transport.RabbitMQ.Features; @@ -43,7 +42,7 @@ public async ValueTask InvokeAsync(IReceiveContext context, ReceiveDelegate next } } - private static readonly RabbitMQAcknowledgementMiddleware _instance = new(); + private static readonly RabbitMQAcknowledgementMiddleware s_instance = new(); /// /// Creates a that wraps the acknowledgement middleware singleton. @@ -51,6 +50,6 @@ public async ValueTask InvokeAsync(IReceiveContext context, ReceiveDelegate next /// A middleware configuration keyed as "RabbitMQAcknowledgement". public static ReceiveMiddlewareConfiguration Create() => new( - static (context, next) => ctx => _instance.InvokeAsync(ctx, next), + static (context, next) => ctx => s_instance.InvokeAsync(ctx, next), "RabbitMQAcknowledgement"); } diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQParsingMiddleware.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQParsingMiddleware.cs index af95c414150..26d78a8fd62 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQParsingMiddleware.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Middlewares/Receive/RabbitMQParsingMiddleware.cs @@ -27,12 +27,12 @@ public async ValueTask InvokeAsync(IReceiveContext context, ReceiveDelegate next await next(context); } - private static readonly RabbitMQParsingMiddleware _instance = new(); + private static readonly RabbitMQParsingMiddleware s_instance = new(); /// /// Creates a that wraps the parsing middleware singleton. /// /// A middleware configuration keyed as "RabbitMQParsing". public static ReceiveMiddlewareConfiguration Create() - => new(static (_, next) => ctx => _instance.InvokeAsync(ctx, next), "RabbitMQParsing"); + => new(static (_, next) => ctx => s_instance.InvokeAsync(ctx, next), "RabbitMQParsing"); } diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQDispatchEndpoint.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQDispatchEndpoint.cs index 5de0b55493b..bb9edbee7c4 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQDispatchEndpoint.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQDispatchEndpoint.cs @@ -1,6 +1,3 @@ -using System.Collections.Specialized; -using System.Web; -using Microsoft.AspNetCore.WebUtilities; using Mocha.Middlewares; using RabbitMQ.Client; using static System.StringSplitOptions; diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageEnvelopeParser.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageEnvelopeParser.cs index 7a2ebb7ee37..76c1a7c55cf 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageEnvelopeParser.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageEnvelopeParser.cs @@ -71,7 +71,7 @@ private static Headers BuildHeaders(IDictionary? headers) var result = new Headers(headers.Count); foreach (var (key, value) in headers) { - object? strValue = value switch + var strValue = value switch { byte[] bytes => Encoding.UTF8.GetString(bytes), AmqpTimestamp timestamp => DateTimeOffset.FromUnixTimeSeconds(timestamp.UnixTime), diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageHeaders.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageHeaders.cs index df3e3e0848a..f56d3230df7 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageHeaders.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessageHeaders.cs @@ -81,7 +81,7 @@ public static ImmutableArray GetStringArray( this IDictionary headers, ContextDataKey> key) { - if (headers.TryGetValue(key.Key, out object? value) && value is List listOfObjects) + if (headers.TryGetValue(key.Key, out var value) && value is List listOfObjects) { var builder = ImmutableArray.CreateBuilder(listOfObjects.Count); foreach (var obj in listOfObjects) diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessagingTransport.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessagingTransport.cs index 25fea5e4c99..cbedb1703c6 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessagingTransport.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/RabbitMQMessagingTransport.cs @@ -1,7 +1,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Mocha.Sagas; using RabbitMQ.Client; using static System.StringSplitOptions; @@ -98,14 +97,14 @@ private RabbitMQConsumerManager CreateConsumerManager(IMessagingSetupContext con { var logger = context.Services.GetRequiredService>(); - return new RabbitMQConsumerManager(logger, ct => Connection.CreateAsync(ct)); + return new RabbitMQConsumerManager(logger, Connection.CreateAsync); } private RabbitMQDispatcher CreateDispatcher(IMessagingSetupContext context) { var logger = context.Services.GetRequiredService>(); - return new RabbitMQDispatcher(logger, ct => Connection.CreateAsync(ct), ProvisionTopologyAsync); + return new RabbitMQDispatcher(logger, Connection.CreateAsync, ProvisionTopologyAsync); async Task ProvisionTopologyAsync(IConnection connection, CancellationToken ct) { diff --git a/src/Mocha/src/Mocha.Transport.RabbitMQ/Topology/RabbitMQQueue.cs b/src/Mocha/src/Mocha.Transport.RabbitMQ/Topology/RabbitMQQueue.cs index 5a9cd1d850d..f4ebc3f7e9e 100644 --- a/src/Mocha/src/Mocha.Transport.RabbitMQ/Topology/RabbitMQQueue.cs +++ b/src/Mocha/src/Mocha.Transport.RabbitMQ/Topology/RabbitMQQueue.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.Collections.Immutable; using RabbitMQ.Client; diff --git a/src/Mocha/src/Mocha/Abstractions/Context/IConsumeContext.cs b/src/Mocha/src/Mocha/Abstractions/Context/IConsumeContext.cs index e4148107045..e5bb1049356 100644 --- a/src/Mocha/src/Mocha/Abstractions/Context/IConsumeContext.cs +++ b/src/Mocha/src/Mocha/Abstractions/Context/IConsumeContext.cs @@ -1,5 +1,3 @@ -using System.Buffers; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Abstractions/Context/IDispatchContext.cs b/src/Mocha/src/Mocha/Abstractions/Context/IDispatchContext.cs index 7afe6399116..5d90db11674 100644 --- a/src/Mocha/src/Mocha/Abstractions/Context/IDispatchContext.cs +++ b/src/Mocha/src/Mocha/Abstractions/Context/IDispatchContext.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Mocha.Utils; namespace Mocha.Middlewares; diff --git a/src/Mocha/src/Mocha/Abstractions/Context/IExecutionContext.cs b/src/Mocha/src/Mocha/Abstractions/Context/IExecutionContext.cs index c9b8daff1ce..2ca51bb3791 100644 --- a/src/Mocha/src/Mocha/Abstractions/Context/IExecutionContext.cs +++ b/src/Mocha/src/Mocha/Abstractions/Context/IExecutionContext.cs @@ -1,5 +1,3 @@ -using Mocha.Middlewares; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Abstractions/Context/IMessageContext.cs b/src/Mocha/src/Mocha/Abstractions/Context/IMessageContext.cs index 7bd3c021a96..f73d2715e9d 100644 --- a/src/Mocha/src/Mocha/Abstractions/Context/IMessageContext.cs +++ b/src/Mocha/src/Mocha/Abstractions/Context/IMessageContext.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Abstractions/Context/IMessagingSetupContext.cs b/src/Mocha/src/Mocha/Abstractions/Context/IMessagingSetupContext.cs index e6c86436386..6b65cff5471 100644 --- a/src/Mocha/src/Mocha/Abstractions/Context/IMessagingSetupContext.cs +++ b/src/Mocha/src/Mocha/Abstractions/Context/IMessagingSetupContext.cs @@ -1,5 +1,3 @@ -using System.Collections.Immutable; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Builder/MessageBusBuilder.cs b/src/Mocha/src/Mocha/Builder/MessageBusBuilder.cs index fa5ddfdab8e..ad824da1cde 100644 --- a/src/Mocha/src/Mocha/Builder/MessageBusBuilder.cs +++ b/src/Mocha/src/Mocha/Builder/MessageBusBuilder.cs @@ -150,7 +150,7 @@ public IMessageBusBuilder AddBatchHandler(Action? config options.Validate(); var consumerType = typeof(BatchConsumer<,>).MakeGenericType(typeof(THandler), THandler.EventType!); - var consumer = (Consumer)Activator.CreateInstance(consumerType, options, (Action?)null)!; + var consumer = (Consumer)Activator.CreateInstance(consumerType, options, null)!; _consumers.Add(consumer); return this; diff --git a/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs b/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs index 2b78f315b8f..efb387b97db 100644 --- a/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs +++ b/src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs @@ -1,6 +1,5 @@ using Mocha.Events; using Mocha.Features; -using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Consumers/Consumer.cs b/src/Mocha/src/Mocha/Consumers/Consumer.cs index a3096394f6e..4bbd74bda87 100644 --- a/src/Mocha/src/Mocha/Consumers/Consumer.cs +++ b/src/Mocha/src/Mocha/Consumers/Consumer.cs @@ -1,6 +1,3 @@ -using System.Collections.Immutable; -using Microsoft.Extensions.DependencyInjection; -using Mocha.Features; using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Consumers/Implementations/ReplyConsumer.cs b/src/Mocha/src/Mocha/Consumers/Implementations/ReplyConsumer.cs index 498b4318da8..a3868bc002b 100644 --- a/src/Mocha/src/Mocha/Consumers/Implementations/ReplyConsumer.cs +++ b/src/Mocha/src/Mocha/Consumers/Implementations/ReplyConsumer.cs @@ -1,7 +1,4 @@ -using Microsoft.Extensions.DependencyInjection; using Mocha.Events; -using Mocha.Features; -using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/DeferredResponseManager.cs b/src/Mocha/src/Mocha/DeferredResponseManager.cs index 4c17eb90023..fbcebbe0cbd 100644 --- a/src/Mocha/src/Mocha/DeferredResponseManager.cs +++ b/src/Mocha/src/Mocha/DeferredResponseManager.cs @@ -25,10 +25,13 @@ public sealed class DeferredResponseManager(TimeProvider timeProvider) var cts = new CancellationTokenSource(timeout.Value, timeProvider); var promise = new Promise(tcs, cts, timeout.Value); - cts.Token.Register(() => { if (_matches.TryRemove(correlationId, out var p)) + cts.Token.Register(() => { - p.TaskCompletionSource.TrySetException(new ResponseTimeoutException(correlationId, p.Timeout)); - } }); + if (_matches.TryRemove(correlationId, out var p)) + { + p.TaskCompletionSource.TrySetException(new ResponseTimeoutException(correlationId, p.Timeout)); + } + }); _matches.TryAdd(correlationId, promise); return tcs; diff --git a/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint~1.cs b/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint~1.cs index 672df387dda..976cc5a09b0 100644 --- a/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint~1.cs +++ b/src/Mocha/src/Mocha/Endpoints/DispatchEndpoint~1.cs @@ -1,6 +1,3 @@ -using System.Diagnostics; -using Mocha.Middlewares; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Endpoints/ReceiveEndpoint.cs b/src/Mocha/src/Mocha/Endpoints/ReceiveEndpoint.cs index b0caa192eb7..cc42c29f7e3 100644 --- a/src/Mocha/src/Mocha/Endpoints/ReceiveEndpoint.cs +++ b/src/Mocha/src/Mocha/Endpoints/ReceiveEndpoint.cs @@ -241,7 +241,8 @@ public void Complete(IMessagingConfigurationContext context) /// The receive endpoint configuration. protected virtual void OnComplete( IMessagingConfigurationContext context, - ReceiveEndpointConfiguration configuration) { } + ReceiveEndpointConfiguration configuration) + { } /// /// Starts this endpoint, enabling it to begin receiving and processing messages. diff --git a/src/Mocha/src/Mocha/Events/ResponseTimeoutException.cs b/src/Mocha/src/Mocha/Events/ResponseTimeoutException.cs index 892bdac681a..1fa994cd2a6 100644 --- a/src/Mocha/src/Mocha/Events/ResponseTimeoutException.cs +++ b/src/Mocha/src/Mocha/Events/ResponseTimeoutException.cs @@ -1,5 +1,3 @@ -using Mocha.Configuration.Faults; - namespace Mocha.Events; /// diff --git a/src/Mocha/src/Mocha/Execution/PublishOptions.cs b/src/Mocha/src/Mocha/Execution/PublishOptions.cs index 24906d12a01..f32e0d2edd4 100644 --- a/src/Mocha/src/Mocha/Execution/PublishOptions.cs +++ b/src/Mocha/src/Mocha/Execution/PublishOptions.cs @@ -1,5 +1,3 @@ -using System.Text.Json.Serialization; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Execution/ReplyOptions.cs b/src/Mocha/src/Mocha/Execution/ReplyOptions.cs index 2dd46ec7c9c..4262398d3c7 100644 --- a/src/Mocha/src/Mocha/Execution/ReplyOptions.cs +++ b/src/Mocha/src/Mocha/Execution/ReplyOptions.cs @@ -1,5 +1,3 @@ -using System.Text.Json.Serialization; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Extensions/TypesExtensions.cs b/src/Mocha/src/Mocha/Extensions/TypesExtensions.cs index 7e0bc0f5a4f..473828d6916 100644 --- a/src/Mocha/src/Mocha/Extensions/TypesExtensions.cs +++ b/src/Mocha/src/Mocha/Extensions/TypesExtensions.cs @@ -1,5 +1,3 @@ -using Mocha.Sagas; - namespace Mocha; internal static class TypesExtensions diff --git a/src/Mocha/src/Mocha/Features/MessageFeatureContextExtensions.cs b/src/Mocha/src/Mocha/Features/MessageFeatureContextExtensions.cs index a533721c6a1..ef983630f1b 100644 --- a/src/Mocha/src/Mocha/Features/MessageFeatureContextExtensions.cs +++ b/src/Mocha/src/Mocha/Features/MessageFeatureContextExtensions.cs @@ -1,6 +1,4 @@ using Mocha.Features; -using Mocha.Middlewares; -using Mocha.Utils; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Headers/Headers.cs b/src/Mocha/src/Mocha/Headers/Headers.cs index f688e160a0f..91796055ba8 100644 --- a/src/Mocha/src/Mocha/Headers/Headers.cs +++ b/src/Mocha/src/Mocha/Headers/Headers.cs @@ -1,5 +1,4 @@ using System.Collections; -using System.Diagnostics.CodeAnalysis; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Headers/MessageHeaders.cs b/src/Mocha/src/Mocha/Headers/MessageHeaders.cs index 8a52c40e053..35af0cc4318 100644 --- a/src/Mocha/src/Mocha/Headers/MessageHeaders.cs +++ b/src/Mocha/src/Mocha/Headers/MessageHeaders.cs @@ -1,5 +1,3 @@ -using System.Collections.Immutable; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/MessageTypes/InboundRoute.cs b/src/Mocha/src/Mocha/MessageTypes/InboundRoute.cs index caddb9ce389..0dce018d2da 100644 --- a/src/Mocha/src/Mocha/MessageTypes/InboundRoute.cs +++ b/src/Mocha/src/Mocha/MessageTypes/InboundRoute.cs @@ -1,6 +1,4 @@ -using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs b/src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs index 0e260f778f6..f66adea7802 100644 --- a/src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs +++ b/src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; diff --git a/src/Mocha/src/Mocha/Middlewares/Dispatch/DispatchSerializerMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Dispatch/DispatchSerializerMiddleware.cs index 56cca476c81..b123fdad145 100644 --- a/src/Mocha/src/Mocha/Middlewares/Dispatch/DispatchSerializerMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Dispatch/DispatchSerializerMiddleware.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.DependencyInjection; using Mocha.Middlewares; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Middlewares/MiddlewareCompiler.cs b/src/Mocha/src/Mocha/Middlewares/MiddlewareCompiler.cs index 310b9a3327e..871d57adca8 100644 --- a/src/Mocha/src/Mocha/Middlewares/MiddlewareCompiler.cs +++ b/src/Mocha/src/Mocha/Middlewares/MiddlewareCompiler.cs @@ -15,9 +15,9 @@ namespace Mocha; /// internal static class MiddlewareCompiler { - private static List? _dispatchMiddlewares; - private static List? _receiveMiddlewares; - private static List? _handlerMiddlewares; + private static List? s_dispatchMiddlewares; + private static List? s_receiveMiddlewares; + private static List? s_handlerMiddlewares; public static DispatchDelegate CompileDispatch( DispatchMiddlewareFactoryContext context, @@ -26,7 +26,7 @@ public static DispatchDelegate CompileDispatch( ReadOnlySpan>>> pipelineModifiers) { // Atomically claim the reusable list instance, if one is currently cached. - var middlewares = Interlocked.Exchange(ref _dispatchMiddlewares, null); + var middlewares = Interlocked.Exchange(ref s_dispatchMiddlewares, null); middlewares ??= []; foreach (var middleware in middlewareConfigurations) @@ -45,7 +45,7 @@ public static DispatchDelegate CompileDispatch( // Reverse before fold so first configured middleware becomes outermost in execution. middlewares.Reverse(); - DispatchDelegate pipeline = dispatch; + var pipeline = dispatch; foreach (var middleware in middlewares) { @@ -55,7 +55,7 @@ public static DispatchDelegate CompileDispatch( middlewares.Clear(); - Interlocked.CompareExchange(ref _dispatchMiddlewares, middlewares, null); + Interlocked.CompareExchange(ref s_dispatchMiddlewares, middlewares, null); return pipeline; } @@ -67,7 +67,7 @@ public static ReceiveDelegate CompileReceive( ReadOnlySpan>>> pipelineModifiers) { // Atomically claim the reusable list instance, if one is currently cached. - var middlewares = Interlocked.Exchange(ref _receiveMiddlewares, null); + var middlewares = Interlocked.Exchange(ref s_receiveMiddlewares, null); middlewares ??= []; foreach (var middleware in middlewareConfigurations) @@ -85,7 +85,7 @@ public static ReceiveDelegate CompileReceive( middlewares.Reverse(); - ReceiveDelegate pipeline = receive; + var pipeline = receive; foreach (var middleware in middlewares) { @@ -95,7 +95,7 @@ public static ReceiveDelegate CompileReceive( middlewares.Clear(); - Interlocked.CompareExchange(ref _receiveMiddlewares, middlewares, null); + Interlocked.CompareExchange(ref s_receiveMiddlewares, middlewares, null); return pipeline; } @@ -107,7 +107,7 @@ public static ConsumerDelegate CompileHandler( ReadOnlySpan>>> pipelineModifiers) { // Atomically claim the reusable list instance, if one is currently cached. - var middlewares = Interlocked.Exchange(ref _handlerMiddlewares, null); + var middlewares = Interlocked.Exchange(ref s_handlerMiddlewares, null); middlewares ??= []; foreach (var middleware in middlewareConfigurations) @@ -124,7 +124,7 @@ public static ConsumerDelegate CompileHandler( } // Reverse before fold so first configured middleware becomes outermost in execution. - ConsumerDelegate pipeline = handler; + var pipeline = handler; middlewares.Reverse(); @@ -136,7 +136,7 @@ public static ConsumerDelegate CompileHandler( middlewares.Clear(); - Interlocked.CompareExchange(ref _handlerMiddlewares, middlewares, null); + Interlocked.CompareExchange(ref s_handlerMiddlewares, middlewares, null); return pipeline; } diff --git a/src/Mocha/src/Mocha/Middlewares/MiddlewareFeature.cs b/src/Mocha/src/Mocha/Middlewares/MiddlewareFeature.cs index f0cd422461b..502a6fdafb3 100644 --- a/src/Mocha/src/Mocha/Middlewares/MiddlewareFeature.cs +++ b/src/Mocha/src/Mocha/Middlewares/MiddlewareFeature.cs @@ -1,5 +1,3 @@ -using Mocha.Features; - namespace Mocha; /// diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/CircuitBreaker/ReceiveCircuitBreakerMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/CircuitBreaker/ReceiveCircuitBreakerMiddleware.cs index 7b2bb8eacb9..bc92aac05db 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/CircuitBreaker/ReceiveCircuitBreakerMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/CircuitBreaker/ReceiveCircuitBreakerMiddleware.cs @@ -30,7 +30,7 @@ await resiliencePipeline.ExecuteAsync( catch (BrokenCircuitException ex) { // Honor Polly's retry hint when available, but clamp to sane delay bounds. - long totalMilliseconds = (long)(ex.RetryAfter?.TotalMilliseconds ?? breakDuration.TotalMilliseconds); + var totalMilliseconds = (long)(ex.RetryAfter?.TotalMilliseconds ?? breakDuration.TotalMilliseconds); totalMilliseconds = totalMilliseconds is < 0 or > uint.MaxValue ? (long)breakDuration.TotalMilliseconds : totalMilliseconds; diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/MessageTypeSelectionMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/MessageTypeSelectionMiddleware.cs index a52a12811e9..3edb28a53d9 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/MessageTypeSelectionMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/MessageTypeSelectionMiddleware.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha.Features; namespace Mocha.Middlewares; diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveDeadLetterMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveDeadLetterMiddleware.cs index d95f1793092..ffc692f22ed 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveDeadLetterMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveDeadLetterMiddleware.cs @@ -1,4 +1,3 @@ -using System.Buffers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Mocha.Features; diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveExpiryMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveExpiryMiddleware.cs index ca9b7bf9105..1995b56d066 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveExpiryMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/ReceiveExpiryMiddleware.cs @@ -1,4 +1,3 @@ -using System.Buffers; using Microsoft.Extensions.DependencyInjection; using Mocha.Features; diff --git a/src/Mocha/src/Mocha/Middlewares/Receive/ReplyReceiveMiddleware.cs b/src/Mocha/src/Mocha/Middlewares/Receive/ReplyReceiveMiddleware.cs index 22c9fc73e32..c062698278a 100644 --- a/src/Mocha/src/Mocha/Middlewares/Receive/ReplyReceiveMiddleware.cs +++ b/src/Mocha/src/Mocha/Middlewares/Receive/ReplyReceiveMiddleware.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using Mocha.Features; using Mocha.Middlewares; diff --git a/src/Mocha/src/Mocha/Middlewares/ReceiveContext.cs b/src/Mocha/src/Mocha/Middlewares/ReceiveContext.cs index 33205afe8fe..2f7715a5f3e 100644 --- a/src/Mocha/src/Mocha/Middlewares/ReceiveContext.cs +++ b/src/Mocha/src/Mocha/Middlewares/ReceiveContext.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using Mocha.Features; namespace Mocha.Middlewares; diff --git a/src/Mocha/src/Mocha/Naming/DefaultNamingConventions.cs b/src/Mocha/src/Mocha/Naming/DefaultNamingConventions.cs index a68607f9d29..8774917d332 100644 --- a/src/Mocha/src/Mocha/Naming/DefaultNamingConventions.cs +++ b/src/Mocha/src/Mocha/Naming/DefaultNamingConventions.cs @@ -1,7 +1,6 @@ using System.Text; using System.Text.RegularExpressions; using Mocha.Middlewares; -using Mocha.Sagas; namespace Mocha; @@ -13,11 +12,11 @@ namespace Mocha; public sealed class DefaultNamingConventions(IHostInfo host) : IBusNamingConventions { // Source gen - private static readonly Regex KebabCaseRegex = new("(? public string GetReceiveEndpointName(InboundRoute route, ReceiveEndpointKind kind) @@ -177,7 +176,7 @@ private string ConvertToUrnSegment(string name) // Convert PascalCase/namespaces to kebab-case URN-friendly format var result = new StringBuilder(); - for (int i = 0; i < name.Length; i++) + for (var i = 0; i < name.Length; i++) { var c = name[i]; @@ -231,13 +230,13 @@ private static string ApplyEndpointKindSuffix(string baseName, ReceiveEndpointKi private static string FormatHandlerTypeName(Type type) { var name = GetBaseTypeName(type); - name = RemoveSuffixes(name, HandlerSuffixes); + name = RemoveSuffixes(name, s_handlerSuffixes); return ToKebabCase(name); } private static string FormatHandlerName(string name) { - name = RemoveSuffixes(name, HandlerSuffixes); + name = RemoveSuffixes(name, s_handlerSuffixes); return ToKebabCase(name); } @@ -247,7 +246,7 @@ private static string FormatHandlerName(string name) private static string FormatMessageTypeName(Type type) { var name = GetBaseTypeName(type); - name = RemoveSuffixes(name, MessageSuffixes); + name = RemoveSuffixes(name, s_messageSuffixes); return ToKebabCase(name); } @@ -325,7 +324,7 @@ private static string ToKebabCase(string input) return input.ToLowerInvariant().Replace('_', '-'); } - var result = KebabCaseRegex.Replace(input, "-"); + var result = s_kebabCaseRegex.Replace(input, "-"); return result.ToLowerInvariant(); } } diff --git a/src/Mocha/src/Mocha/Observability/OpenTelemetryDiagnosticObserver.cs b/src/Mocha/src/Mocha/Observability/OpenTelemetryDiagnosticObserver.cs index 6abdd4d9412..c0d2957826a 100644 --- a/src/Mocha/src/Mocha/Observability/OpenTelemetryDiagnosticObserver.cs +++ b/src/Mocha/src/Mocha/Observability/OpenTelemetryDiagnosticObserver.cs @@ -124,7 +124,7 @@ public void Dispose() // Enrich activity with context state after all middlewares have run if (_activity is not null) { - string consumerName = _context.MessageType is not null ? _context.MessageType.Identity : "unknown"; + var consumerName = _context.MessageType is not null ? _context.MessageType.Identity : "unknown"; _activity .EnrichMessageDefault() diff --git a/src/Mocha/src/Mocha/Runtime/MessagingRuntime.cs b/src/Mocha/src/Mocha/Runtime/MessagingRuntime.cs index c0b15b7edf4..6694bf21ee5 100644 --- a/src/Mocha/src/Mocha/Runtime/MessagingRuntime.cs +++ b/src/Mocha/src/Mocha/Runtime/MessagingRuntime.cs @@ -1,7 +1,4 @@ -using System.Collections.Frozen; using System.Collections.Immutable; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.ObjectPool; using Mocha.Middlewares; namespace Mocha; @@ -118,7 +115,7 @@ public MessageType GetMessageType(Type type) /// A token to cancel the startup sequence. public async ValueTask StartAsync(CancellationToken cancellationToken) { - if(IsStarted) + if (IsStarted) { return; } diff --git a/src/Mocha/src/Mocha/Runtime/MessagingRuntimeHostedService.cs b/src/Mocha/src/Mocha/Runtime/MessagingRuntimeHostedService.cs index eb534e02ae2..7713c204455 100644 --- a/src/Mocha/src/Mocha/Runtime/MessagingRuntimeHostedService.cs +++ b/src/Mocha/src/Mocha/Runtime/MessagingRuntimeHostedService.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaConfiguration.cs index 83b47494266..921178c1a4a 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventPublishConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventPublishConfiguration.cs index 1f17abb2270..9ebb0af57c8 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventPublishConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventPublishConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventSendConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventSendConfiguration.cs index 0f6c6a73fe5..cdf355861e0 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventSendConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaEventSendConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaLifeCycleConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaLifeCycleConfiguration.cs index 626d93027f8..37d21519045 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaLifeCycleConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaLifeCycleConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaResponseConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaResponseConfiguration.cs index 18f49cd6269..b8c25778605 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaResponseConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaResponseConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaStateConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaStateConfiguration.cs index 51c5fccaa4c..cc23a4c7127 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaStateConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaStateConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Definitions/SagaTransitionConfiguration.cs b/src/Mocha/src/Mocha/Sagas/Definitions/SagaTransitionConfiguration.cs index aa500453a6e..983071831ad 100644 --- a/src/Mocha/src/Mocha/Sagas/Definitions/SagaTransitionConfiguration.cs +++ b/src/Mocha/src/Mocha/Sagas/Definitions/SagaTransitionConfiguration.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaDescriptor.cs index c0ccd5325cc..54372f99b2f 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaFinalStateDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaFinalStateDescriptor.cs index 80c93addb4b..302b9661b78 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaFinalStateDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaFinalStateDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaLifeCycleDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaLifeCycleDescriptor.cs index 74cfd7d49d9..a5cb727741f 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaLifeCycleDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaLifeCycleDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaStateDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaStateDescriptor.cs index aa67817962d..b6a66c5a3c9 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaStateDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaStateDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaTransitionDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaTransitionDescriptor.cs index ee624ca7edb..ee19681dfc0 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaTransitionDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/ISagaTransitionDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaDescriptor.cs index 3e09ea54b0a..c007cf8752f 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptor.cs index f806094df82..e1d711f9ca1 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptorExtensions.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptorExtensions.cs index 4a1abf6e77d..44f8a2bdcc3 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptorExtensions.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaLifeCycleDescriptorExtensions.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaPublishOptions.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaPublishOptions.cs index 6efd68706e8..a7d14519d96 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaPublishOptions.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaPublishOptions.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaSendOptions.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaSendOptions.cs index ac3b302a78c..c216a575202 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaSendOptions.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaSendOptions.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaStateDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaStateDescriptor.cs index 7274024e195..74d820f92c2 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaStateDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaStateDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// @@ -13,7 +11,7 @@ public sealed class SagaStateDescriptor , ISagaFinalStateDescriptor where TState : SagaStateBase { private readonly SagaLifeCycleDescriptor _onEntry; - private readonly List> _transitions = new(); + private readonly List> _transitions = []; protected internal override SagaStateConfiguration Configuration { get; protected set; } diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptor.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptor.cs index 4db65c0440c..04ab88ac2fb 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptor.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptor.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptorExtensions.cs b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptorExtensions.cs index d615a50fcaf..3fbddd0ac2b 100644 --- a/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptorExtensions.cs +++ b/src/Mocha/src/Mocha/Sagas/Descriptors/SagaTransitionDescriptorExtensions.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Execution/ISagaExecutionContext.cs b/src/Mocha/src/Mocha/Sagas/Execution/ISagaExecutionContext.cs index 66891fb7e2e..0640df5bdda 100644 --- a/src/Mocha/src/Mocha/Sagas/Execution/ISagaExecutionContext.cs +++ b/src/Mocha/src/Mocha/Sagas/Execution/ISagaExecutionContext.cs @@ -1,5 +1,3 @@ -using Microsoft.Extensions.Logging; -using Mocha; using Mocha.Features; namespace Mocha.Sagas; diff --git a/src/Mocha/src/Mocha/Sagas/Initialization/ISagaEventMiddleware.cs b/src/Mocha/src/Mocha/Sagas/Initialization/ISagaEventMiddleware.cs index e81bc6dc251..964db9f660e 100644 --- a/src/Mocha/src/Mocha/Sagas/Initialization/ISagaEventMiddleware.cs +++ b/src/Mocha/src/Mocha/Sagas/Initialization/ISagaEventMiddleware.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/Saga.Initialization.cs b/src/Mocha/src/Mocha/Sagas/Saga.Initialization.cs index c32bc524f6c..9fc4a607d18 100644 --- a/src/Mocha/src/Mocha/Sagas/Saga.Initialization.cs +++ b/src/Mocha/src/Mocha/Sagas/Saga.Initialization.cs @@ -1,8 +1,6 @@ using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Mocha; -using Mocha.Features; namespace Mocha.Sagas; @@ -104,7 +102,7 @@ private ImmutableArray InitializeTransitions( SagaStateConfiguration state, ImmutableArray? additionalTransitions = null) { - additionalTransitions ??= ImmutableArray.Empty; + additionalTransitions ??= []; var transitions = ImmutableArray.CreateBuilder(state.Transitions.Count + additionalTransitions.Value.Length); @@ -146,7 +144,8 @@ private ImmutableArray InitializeTransitions( return transitions.MoveToImmutable(); - static void DefaultAction(object _, object __) { } + static void DefaultAction(object _, object __) + { } } private static ImmutableArray InitializeEventPublish( diff --git a/src/Mocha/src/Mocha/Sagas/Saga.cs b/src/Mocha/src/Mocha/Sagas/Saga.cs index 94cb9f78344..5965a44546e 100644 --- a/src/Mocha/src/Mocha/Sagas/Saga.cs +++ b/src/Mocha/src/Mocha/Sagas/Saga.cs @@ -1,10 +1,5 @@ -using System.Buffers; using System.Collections.Immutable; -using System.Text.Json; -using System.Text.Json.Serialization.Metadata; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Mocha; using Mocha.Features; namespace Mocha.Sagas; diff --git a/src/Mocha/src/Mocha/Sagas/SagaContextData.cs b/src/Mocha/src/Mocha/Sagas/SagaContextData.cs index 89d261fdb02..7661219e846 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaContextData.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaContextData.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; internal static class SagaContextData diff --git a/src/Mocha/src/Mocha/Sagas/SagaEventListener.cs b/src/Mocha/src/Mocha/Sagas/SagaEventListener.cs index 6a83a0cd725..9aaacdf6d95 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaEventListener.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaEventListener.cs @@ -1,8 +1,5 @@ using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Mocha; using Mocha.Features; -using Mocha.Middlewares; namespace Mocha.Sagas; diff --git a/src/Mocha/src/Mocha/Sagas/SagaEventPublish.cs b/src/Mocha/src/Mocha/Sagas/SagaEventPublish.cs index 94552f0b5f4..e5cb8d5a1b0 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaEventPublish.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaEventPublish.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/SagaEventSend.cs b/src/Mocha/src/Mocha/Sagas/SagaEventSend.cs index f00766f1a9f..1047493afe4 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaEventSend.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaEventSend.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/SagaRegistry.cs b/src/Mocha/src/Mocha/Sagas/SagaRegistry.cs index 9c2396d5811..2fc5faf097b 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaRegistry.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaRegistry.cs @@ -1,8 +1,3 @@ -using System.Text.Json; -using System.Text.Json.Serialization.Metadata; -using Microsoft.Extensions.Options; -using Mocha; - namespace Mocha.Sagas; // public sealed class SagaRegistry(IEnumerable sagas) diff --git a/src/Mocha/src/Mocha/Sagas/SagaResponse.cs b/src/Mocha/src/Mocha/Sagas/SagaResponse.cs index a5de2df7aa7..d7b2e3ece4b 100644 --- a/src/Mocha/src/Mocha/Sagas/SagaResponse.cs +++ b/src/Mocha/src/Mocha/Sagas/SagaResponse.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas; /// diff --git a/src/Mocha/src/Mocha/Sagas/State/SagaStateBase.cs b/src/Mocha/src/Mocha/Sagas/State/SagaStateBase.cs index b376545010e..6f8bd5ccb46 100644 --- a/src/Mocha/src/Mocha/Sagas/State/SagaStateBase.cs +++ b/src/Mocha/src/Mocha/Sagas/State/SagaStateBase.cs @@ -1,5 +1,4 @@ using System.Text.Json.Serialization; -using Mocha; namespace Mocha.Sagas; diff --git a/src/Mocha/src/Mocha/Sagas/State/Serialization/JsonSagaStateSerializer.cs b/src/Mocha/src/Mocha/Sagas/State/Serialization/JsonSagaStateSerializer.cs index 15d8f6860d1..67758d3742c 100644 --- a/src/Mocha/src/Mocha/Sagas/State/Serialization/JsonSagaStateSerializer.cs +++ b/src/Mocha/src/Mocha/Sagas/State/Serialization/JsonSagaStateSerializer.cs @@ -15,7 +15,7 @@ public sealed class JsonSagaStateSerializer(JsonTypeInfo typeInfo) : ISagaStateS /// public T? Deserialize(ReadOnlyMemory body) - => JsonSerializer.Deserialize(body.Span, typeInfo) is T result ? result : default(T); + => JsonSerializer.Deserialize(body.Span, typeInfo) is T result ? result : default; /// public void Serialize(T message, IBufferWriter writer) diff --git a/src/Mocha/src/Mocha/Serialization/HeadersConverter.cs b/src/Mocha/src/Mocha/Serialization/HeadersConverter.cs index 982623f9558..4f3f6308e63 100644 --- a/src/Mocha/src/Mocha/Serialization/HeadersConverter.cs +++ b/src/Mocha/src/Mocha/Serialization/HeadersConverter.cs @@ -1,4 +1,3 @@ -using System.Collections; using System.Text.Json; using System.Text.Json.Serialization; diff --git a/src/Mocha/src/Mocha/Serialization/JsonMessageSerializer.cs b/src/Mocha/src/Mocha/Serialization/JsonMessageSerializer.cs index e8228a09bd6..1e4516f60db 100644 --- a/src/Mocha/src/Mocha/Serialization/JsonMessageSerializer.cs +++ b/src/Mocha/src/Mocha/Serialization/JsonMessageSerializer.cs @@ -11,7 +11,7 @@ internal sealed class JsonMessageSerializer(JsonTypeInfo typeInfo) : IMessageSer public object? Deserialize(ReadOnlyMemory body) => JsonSerializer.Deserialize(body.Span, typeInfo); public T? Deserialize(ReadOnlyMemory body) - => JsonSerializer.Deserialize(body.Span, typeInfo) is T result ? result : default(T); + => JsonSerializer.Deserialize(body.Span, typeInfo) is T result ? result : default; public void Serialize(T message, IBufferWriter writer) { diff --git a/src/Mocha/src/Mocha/Serialization/MessageTypeRegistry.cs b/src/Mocha/src/Mocha/Serialization/MessageTypeRegistry.cs index 76f9a189dbe..687baa86f9a 100644 --- a/src/Mocha/src/Mocha/Serialization/MessageTypeRegistry.cs +++ b/src/Mocha/src/Mocha/Serialization/MessageTypeRegistry.cs @@ -1,7 +1,4 @@ -using System.Collections.Frozen; using System.Collections.Immutable; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Options; namespace Mocha; diff --git a/src/Mocha/src/Mocha/Transport/MessageEnvelopeReader.cs b/src/Mocha/src/Mocha/Transport/MessageEnvelopeReader.cs index bccac84afd1..35402c72c84 100644 --- a/src/Mocha/src/Mocha/Transport/MessageEnvelopeReader.cs +++ b/src/Mocha/src/Mocha/Transport/MessageEnvelopeReader.cs @@ -1,4 +1,3 @@ -using System.Collections.Frozen; using System.Collections.Immutable; using System.Text.Json; diff --git a/src/Mocha/src/Mocha/Transport/MessagingTransport.cs b/src/Mocha/src/Mocha/Transport/MessagingTransport.cs index 87bba22accf..305269b7edb 100644 --- a/src/Mocha/src/Mocha/Transport/MessagingTransport.cs +++ b/src/Mocha/src/Mocha/Transport/MessagingTransport.cs @@ -102,13 +102,17 @@ public virtual TransportDescription Describe() foreach (var endpoint in ReceiveEndpoints) { if (endpoint.Source is not null) + { outboundResources.Add(endpoint.Source); + } } foreach (var endpoint in DispatchEndpoints) { if (endpoint.Destination is not null) + { inboundResources.Add(endpoint.Destination); + } } foreach (var resource in outboundResources) @@ -125,7 +129,9 @@ public virtual TransportDescription Describe() foreach (var resource in inboundResources) { if (outboundResources.Contains(resource)) + { continue; + } entities.Add( new TopologyEntityDescription( diff --git a/src/Mocha/test/Demo.Catalog.Tests/Sagas/QuickRefundSagaTests.cs b/src/Mocha/test/Demo.Catalog.Tests/Sagas/QuickRefundSagaTests.cs index 824d67ecbc7..dc7a8943d42 100644 --- a/src/Mocha/test/Demo.Catalog.Tests/Sagas/QuickRefundSagaTests.cs +++ b/src/Mocha/test/Demo.Catalog.Tests/Sagas/QuickRefundSagaTests.cs @@ -7,8 +7,8 @@ namespace Demo.Catalog.Tests.Sagas; public sealed class QuickRefundSagaTests { - private static readonly Guid OrderId = Guid.Parse("11111111-1111-1111-1111-111111111111"); - private static readonly Guid RefundId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + private static readonly Guid s_orderId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_refundId = Guid.Parse("22222222-2222-2222-2222-222222222222"); private const decimal Amount = 49.99m; private const string CustomerId = "CUST-001"; private const string Reason = "Item not as described"; @@ -16,7 +16,7 @@ public sealed class QuickRefundSagaTests private static RequestQuickRefundRequest CreateRequest() => new() { - OrderId = OrderId, + OrderId = s_orderId, Amount = Amount, CustomerId = CustomerId, Reason = Reason @@ -25,8 +25,8 @@ private static RequestQuickRefundRequest CreateRequest() private static ProcessRefundResponse CreateSuccessResponse() => new() { - RefundId = RefundId, - OrderId = OrderId, + RefundId = s_refundId, + OrderId = s_orderId, Amount = Amount, Success = true, ProcessedAt = DateTimeOffset.UtcNow @@ -36,7 +36,7 @@ private static ProcessRefundResponse CreateFailureResponse() => new() { RefundId = Guid.Empty, - OrderId = OrderId, + OrderId = s_orderId, Amount = 0, Success = false, FailureReason = "Insufficient funds", @@ -55,7 +55,7 @@ await tester .ExpectSendMessage( (state, cmd) => { - Assert.Equal(OrderId, cmd.OrderId); + Assert.Equal(s_orderId, cmd.OrderId); Assert.Equal(Amount, cmd.Amount); Assert.Equal(Reason, cmd.Reason); Assert.Equal(CustomerId, cmd.CustomerId); @@ -78,9 +78,9 @@ await tester (state, resp) => { Assert.True(resp.Success); - Assert.Equal(RefundId, resp.RefundId); + Assert.Equal(s_refundId, resp.RefundId); Assert.Equal(Amount, resp.RefundedAmount); - Assert.Equal(OrderId, resp.OrderId); + Assert.Equal(s_orderId, resp.OrderId); }) .ExpectCompletion() .RunAll(); @@ -103,7 +103,7 @@ await tester Assert.False(resp.Success); Assert.Equal("Insufficient funds", resp.FailureReason); Assert.Null(resp.RefundId); - Assert.Equal(OrderId, resp.OrderId); + Assert.Equal(s_orderId, resp.OrderId); }) .ExpectCompletion() .RunAll(); @@ -117,7 +117,7 @@ public async Task Should_PopulateStateFromRequest_When_StateFactoryCreates() await tester.Plan().On(CreateRequest()).RunAll(); var state = tester.State!; - Assert.Equal(OrderId, state.OrderId); + Assert.Equal(s_orderId, state.OrderId); Assert.Equal(Amount, state.Amount); Assert.Equal(CustomerId, state.CustomerId); Assert.Equal(Reason, state.Reason); diff --git a/src/Mocha/test/Demo.Catalog.Tests/Sagas/ReturnProcessingSagaTests.cs b/src/Mocha/test/Demo.Catalog.Tests/Sagas/ReturnProcessingSagaTests.cs index 87b16c4c136..bbaab09b492 100644 --- a/src/Mocha/test/Demo.Catalog.Tests/Sagas/ReturnProcessingSagaTests.cs +++ b/src/Mocha/test/Demo.Catalog.Tests/Sagas/ReturnProcessingSagaTests.cs @@ -7,10 +7,10 @@ namespace Demo.Catalog.Tests.Sagas; public sealed class ReturnProcessingSagaTests { - private static readonly Guid OrderId = Guid.Parse("11111111-1111-1111-1111-111111111111"); - private static readonly Guid ProductId = Guid.Parse("22222222-2222-2222-2222-222222222222"); - private static readonly Guid ReturnId = Guid.Parse("33333333-3333-3333-3333-333333333333"); - private static readonly Guid RefundId = Guid.Parse("44444444-4444-4444-4444-444444444444"); + private static readonly Guid s_orderId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_productId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + private static readonly Guid s_returnId = Guid.Parse("33333333-3333-3333-3333-333333333333"); + private static readonly Guid s_refundId = Guid.Parse("44444444-4444-4444-4444-444444444444"); private const int Quantity = 2; private const decimal Amount = 99.99m; private const string CustomerId = "CUST-002"; @@ -20,11 +20,11 @@ public sealed class ReturnProcessingSagaTests private static ReturnPackageReceivedEvent CreatePackageReceivedEvent() => new() { - ReturnId = ReturnId, - OrderId = OrderId, + ReturnId = s_returnId, + OrderId = s_orderId, TrackingNumber = TrackingNumber, ReceivedAt = DateTimeOffset.UtcNow, - ProductId = ProductId, + ProductId = s_productId, Quantity = Quantity, Amount = Amount, CustomerId = CustomerId, @@ -34,9 +34,9 @@ private static ReturnPackageReceivedEvent CreatePackageReceivedEvent() private static InspectReturnResponse CreateInspectionResponse(InspectionResult result = InspectionResult.Passed) => new() { - OrderId = OrderId, - ProductId = ProductId, - ReturnId = ReturnId, + OrderId = s_orderId, + ProductId = s_productId, + ReturnId = s_returnId, Passed = result == InspectionResult.Passed, Result = result, InspectedAt = DateTimeOffset.UtcNow @@ -45,8 +45,8 @@ private static InspectReturnResponse CreateInspectionResponse(InspectionResult r private static RestockInventoryResponse CreateRestockResponse() => new() { - OrderId = OrderId, - ProductId = ProductId, + OrderId = s_orderId, + ProductId = s_productId, QuantityRestocked = Quantity, NewStockLevel = 50, Success = true, @@ -56,8 +56,8 @@ private static RestockInventoryResponse CreateRestockResponse() private static ProcessRefundResponse CreateRefundSuccessResponse() => new() { - RefundId = RefundId, - OrderId = OrderId, + RefundId = s_refundId, + OrderId = s_orderId, Amount = Amount, Success = true, ProcessedAt = DateTimeOffset.UtcNow @@ -67,7 +67,7 @@ private static ProcessRefundResponse CreateRefundFailureResponse() => new() { RefundId = Guid.Empty, - OrderId = OrderId, + OrderId = s_orderId, Amount = 0, Success = false, FailureReason = "Payment gateway unavailable", @@ -86,10 +86,10 @@ await tester .ExpectSendMessage( (state, cmd) => { - Assert.Equal(OrderId, cmd.OrderId); - Assert.Equal(ProductId, cmd.ProductId); + Assert.Equal(s_orderId, cmd.OrderId); + Assert.Equal(s_productId, cmd.ProductId); Assert.Equal(Quantity, cmd.Quantity); - Assert.Equal(ReturnId, cmd.ReturnId); + Assert.Equal(s_returnId, cmd.ReturnId); }) .RunAll(); } @@ -108,15 +108,15 @@ await tester .ExpectSendMessage( (state, cmd) => { - Assert.Equal(OrderId, cmd.OrderId); - Assert.Equal(ProductId, cmd.ProductId); + Assert.Equal(s_orderId, cmd.OrderId); + Assert.Equal(s_productId, cmd.ProductId); Assert.Equal(Quantity, cmd.Quantity); - Assert.Equal(ReturnId, cmd.ReturnId); + Assert.Equal(s_returnId, cmd.ReturnId); }) .ExpectSendMessage( (state, cmd) => { - Assert.Equal(OrderId, cmd.OrderId); + Assert.Equal(s_orderId, cmd.OrderId); Assert.Equal(Amount, cmd.Amount); Assert.Equal(CustomerId, cmd.CustomerId); }) @@ -142,7 +142,7 @@ await tester // Verify final state values before cleanup // State is cleaned up after Finally, so we check outbox instead var refundCmd = tester.ExpectSentMessage(); - Assert.Equal(OrderId, refundCmd.OrderId); + Assert.Equal(s_orderId, refundCmd.OrderId); } [Fact] @@ -170,10 +170,10 @@ public async Task Should_PopulateStateFromEvent_When_StateFactoryCreates() await tester.Plan().On(CreatePackageReceivedEvent()).RunAll(); var state = tester.State!; - Assert.Equal(OrderId, state.OrderId); - Assert.Equal(ProductId, state.ProductId); + Assert.Equal(s_orderId, state.OrderId); + Assert.Equal(s_productId, state.ProductId); Assert.Equal(Quantity, state.Quantity); - Assert.Equal(ReturnId, state.ReturnId); + Assert.Equal(s_returnId, state.ReturnId); Assert.Equal(TrackingNumber, state.ReturnTrackingNumber); Assert.Equal(CustomerId, state.CustomerId); Assert.Equal(Amount, state.Amount); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs index 4733170d04c..0421b24aaf1 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -using Mocha.EntityFrameworkCore; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Outbox; using Mocha.Transport.InMemory; diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs index 8389a1eb63a..ff2d66046e3 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Mocha.EntityFrameworkCore.Postgres; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Middlewares; using Mocha.Outbox; @@ -121,7 +120,7 @@ public void Dispose_Should_NotThrow_When_Called() var outbox = new PostgresMessageOutbox(context, signal, queries.InsertEnvelope); // Act & Assert - var ex = Record.Exception(() => outbox.Dispose()); + var ex = Record.Exception(outbox.Dispose); Assert.Null(ex); } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs index 97202b36f0e..88a68005d84 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs @@ -2,7 +2,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Mocha.EntityFrameworkCore; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Outbox; using Mocha.Transport.InMemory; @@ -11,7 +10,7 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests; public sealed class PostgresOutboxIntegrationTests(PostgresFixture fixture) : IClassFixture { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); [Fact] public async Task Outbox_Should_DeliverMessage_When_EventPublished() @@ -27,7 +26,7 @@ public async Task Outbox_Should_DeliverMessage_When_EventPublished() await bus.PublishAsync(new TestEvent { Payload = "hello" }, default); // Assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler should have received the message"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler should have received the message"); var received = Assert.Single(recorder.Messages.OfType()); Assert.Equal("hello", received.Payload); } @@ -50,7 +49,7 @@ public async Task Outbox_Should_DeliverAllMessages_When_MultipleEventsPublished( } // Assert - Assert.True(await recorder.WaitAsync(Timeout, count), $"Handler should have received all {count} messages"); + Assert.True(await recorder.WaitAsync(s_timeout, count), $"Handler should have received all {count} messages"); var payloads = recorder.Messages.OfType().Select(e => e.Payload).OrderBy(p => p).ToList(); Assert.Equal(count, payloads.Count); for (var i = 0; i < count; i++) @@ -80,7 +79,7 @@ public async Task Outbox_Should_DeliverMessages_When_PublishedUnderLoad() // Assert Assert.True( - await recorder.WaitAsync(Timeout, count), + await recorder.WaitAsync(s_timeout, count), $"Handler should have received all {count} messages under load"); var payloads = recorder.Messages.OfType().Select(e => e.Payload).ToHashSet(); @@ -149,7 +148,7 @@ public async Task Outbox_Should_ProcessPendingMessages_When_WorkerStartsAfterPer { // Assert — all pre-existing messages are processed Assert.True( - await recorder.WaitAsync(Timeout, count), + await recorder.WaitAsync(s_timeout, count), "Worker should process messages that were persisted before it started"); var payloads = recorder.Messages.OfType().Select(e => e.Payload).ToHashSet(); @@ -212,7 +211,7 @@ public async Task Outbox_Should_ResumeProcessing_When_WorkerRestartedAfterInterr await bus.PublishAsync(new TestEvent { Payload = "before-stop" }, default); } - Assert.True(await recorder.WaitAsync(Timeout), "First message should be delivered before worker stops"); + Assert.True(await recorder.WaitAsync(s_timeout), "First message should be delivered before worker stops"); // Phase 2: stop worker foreach (var svc in hostedServices) @@ -239,7 +238,7 @@ public async Task Outbox_Should_ResumeProcessing_When_WorkerRestartedAfterInterr // Assert — message published during downtime is delivered. // Wait until "during-stop" appears in the recorder's messages. - using var waitCts = new CancellationTokenSource(Timeout); + using var waitCts = new CancellationTokenSource(s_timeout); while (!recorder.Messages.OfType().Any(e => e.Payload == "during-stop")) { await Task.Delay(50, waitCts.Token); @@ -279,7 +278,7 @@ public async Task Outbox_Should_ProcessNewMessages_When_PublishedWhileWorkerRunn // Wait for this message to be delivered before publishing the next Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), $"Message live-{i} should be delivered while worker is running"); } @@ -316,7 +315,7 @@ await bus.PublishAsync( // Assert Assert.True( - await recorder.WaitAsync(Timeout, totalMessages), + await recorder.WaitAsync(s_timeout, totalMessages), $"All {totalMessages} messages from {scopeCount} scopes should be delivered"); var payloads = recorder.Messages.OfType().Select(e => e.Payload).ToHashSet(); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSagaStoreTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSagaStoreTests.cs index 6b2cf55cdbe..28aa5d31d34 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSagaStoreTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresSagaStoreTests.cs @@ -1,7 +1,5 @@ using Microsoft.EntityFrameworkCore; -using Mocha.EntityFrameworkCore.Postgres; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; -using Mocha.Sagas; using Mocha.Sagas.EfCore; namespace Mocha.EntityFrameworkCore.Postgres.Tests; diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/SagaServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/SagaServiceRegistrationTests.cs index a73f25cbbcf..e89bc070bb1 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/SagaServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/SagaServiceRegistrationTests.cs @@ -1,8 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Mocha.EntityFrameworkCore; -using Mocha.EntityFrameworkCore.Postgres; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Sagas; using Mocha.Sagas.EfCore; diff --git a/src/Mocha/test/Mocha.Hosting.Tests/Health/HealthRequestHandlerTests.cs b/src/Mocha/test/Mocha.Hosting.Tests/Health/HealthRequestHandlerTests.cs index 9e042e4d470..7ce81dd1c8f 100644 --- a/src/Mocha/test/Mocha.Hosting.Tests/Health/HealthRequestHandlerTests.cs +++ b/src/Mocha/test/Mocha.Hosting.Tests/Health/HealthRequestHandlerTests.cs @@ -1,5 +1,3 @@ -using Mocha.Hosting; - namespace Mocha.Hosting.Tests.Health; public sealed class HealthRequestHandlerTests diff --git a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckExtensionsTests.cs b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckExtensionsTests.cs index fc1a175720d..0b4c0288dbd 100644 --- a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckExtensionsTests.cs +++ b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckExtensionsTests.cs @@ -1,7 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; -using Mocha.Hosting; namespace Mocha.Hosting.Tests.Health; diff --git a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckIntegrationTests.cs b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckIntegrationTests.cs index 53b5e9e2431..ee55fb6fbdc 100644 --- a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckIntegrationTests.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; -using Mocha.Hosting; using Mocha.Transport.InMemory; namespace Mocha.Hosting.Tests.Health; diff --git a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckTests.cs b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckTests.cs index 8f4a878318a..1bf605fdff9 100644 --- a/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckTests.cs +++ b/src/Mocha/test/Mocha.Hosting.Tests/Health/MessageBusHealthCheckTests.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; -using Mocha.Hosting; using Moq; namespace Mocha.Hosting.Tests.Health; diff --git a/src/Mocha/test/Mocha.Hosting.Tests/Topology/MessageBusEndpointRouteBuilderExtensionsTests.cs b/src/Mocha/test/Mocha.Hosting.Tests/Topology/MessageBusEndpointRouteBuilderExtensionsTests.cs index 4ac9229b362..af58a952745 100644 --- a/src/Mocha/test/Mocha.Hosting.Tests/Topology/MessageBusEndpointRouteBuilderExtensionsTests.cs +++ b/src/Mocha/test/Mocha.Hosting.Tests/Topology/MessageBusEndpointRouteBuilderExtensionsTests.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Mocha.Hosting; using Mocha.Transport.InMemory; namespace Mocha.Hosting.Tests.Topology; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/ExtendedPostgresResource.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/ExtendedPostgresResource.cs index 864cc1dc2e9..5987fc2bd11 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/ExtendedPostgresResource.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/ExtendedPostgresResource.cs @@ -1,6 +1,5 @@ using Npgsql; using Squadron; -using Xunit; namespace Mocha.Sagas.Tests; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTestPlan.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTestPlan.cs index fd198bb1e68..ad38c788b5d 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTestPlan.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTestPlan.cs @@ -1,6 +1,3 @@ -using Mocha; -using Xunit; - namespace Mocha.Sagas.Tests; /// @@ -8,7 +5,7 @@ namespace Mocha.Sagas.Tests; /// public sealed class SagaTestPlan where T : SagaStateBase { - private readonly List, Task>> _steps = new(); + private readonly List, Task>> _steps = []; public SagaTester Tester { get; } diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTester.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTester.cs index 2d7a63ca927..be7ff5528d7 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTester.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/SagaTester.cs @@ -1,16 +1,14 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Features; using Mocha.Transport.InMemory; -using Xunit; namespace Mocha.Sagas.Tests; public static class SagaTester { - private static readonly IMessagingRuntime _runtime = CreateRuntime(); + private static readonly IMessagingRuntime s_runtime = CreateRuntime(); - internal static IMessagingRuntime Runtime => _runtime; + internal static IMessagingRuntime Runtime => s_runtime; public static SagaTester Create(Saga saga) where T : SagaStateBase { diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestConsumeContext.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestConsumeContext.cs index af3210877d1..6f156d1bc60 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestConsumeContext.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestConsumeContext.cs @@ -1,4 +1,3 @@ -using Mocha; using Mocha.Features; using Mocha.Middlewares; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestEndpointFormatter.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestEndpointFormatter.cs index f648742fdfd..7fe67eff4c6 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestEndpointFormatter.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestEndpointFormatter.cs @@ -1,5 +1,4 @@ using System.Text; -using Mocha; namespace Mocha.Sagas.Tests; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestExtensions.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestExtensions.cs index 714d3c9c748..c98deeb811e 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestExtensions.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestExtensions.cs @@ -1,4 +1,3 @@ -using Mocha; using Npgsql; namespace Mocha.Sagas.Tests; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageBus.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageBus.cs index 78fa7bf7396..d43c82ab736 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageBus.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageBus.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Sagas.Tests; /// diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageOutbox.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageOutbox.cs index c173ca17d90..90d45011c20 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageOutbox.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessageOutbox.cs @@ -1,4 +1,3 @@ -using Mocha; using Mocha.Middlewares; using Mocha.Outbox; @@ -6,7 +5,7 @@ namespace Mocha.Sagas.Tests; public class TestMessageOutbox : IMessageOutbox { - public List Messages { get; } = new(); + public List Messages { get; } = []; public Task PublishAsync(T message, CancellationToken cancellationToken) where T : notnull { diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessagingSetupContext.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessagingSetupContext.cs index 092f8de7020..fc3d16403dc 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessagingSetupContext.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestMessagingSetupContext.cs @@ -1,8 +1,6 @@ using System.Buffers; using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Mocha; using Mocha.Features; using Mocha.Middlewares; @@ -13,9 +11,9 @@ namespace Mocha.Sagas.Tests; /// public sealed class TestMessagingSetupContext : IMessagingSetupContext { - private static readonly Lazy _instance = new(() => new()); + private static readonly Lazy s_instance = new(() => new()); - public static TestMessagingSetupContext Instance => _instance.Value; + public static TestMessagingSetupContext Instance => s_instance.Value; public IServiceProvider Services { get; } public IBusNamingConventions Naming { get; } = new TestNamingConventions(); @@ -25,7 +23,7 @@ public sealed class TestMessagingSetupContext : IMessagingSetupContext public IEndpointRouter Endpoints => throw new NotSupportedException("Not available in test context"); public IHostInfo Host => throw new NotSupportedException("Not available in test context"); public IConventionRegistry Conventions => throw new NotSupportedException("Not available in test context"); - public ImmutableHashSet Consumers => ImmutableHashSet.Empty; + public ImmutableHashSet Consumers => []; public ImmutableArray Transports => []; public MessagingTransport? Transport => null; diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaCleanup.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaCleanup.cs index 0a7a0416016..76c3217762e 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaCleanup.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaCleanup.cs @@ -2,7 +2,7 @@ namespace Mocha.Sagas.Tests; public class TestSagaCleanup : ISagaCleanup { - public List CleanedStates { get; } = new(); + public List CleanedStates { get; } = []; public Task CleanupAsync(Saga saga, SagaStateBase state, CancellationToken cancellationToken) { diff --git a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaStore.cs b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaStore.cs index 364873d16a4..9e806dd5a73 100644 --- a/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaStore.cs +++ b/src/Mocha/test/Mocha.Sagas.TestHelpers/TestSagaStore.cs @@ -43,7 +43,9 @@ public Task DeleteAsync(Saga saga, Guid id, CancellationToken cancellationToken) var state = States.FirstOrDefault(x => x.Id == id); if (state is T s) { +#pragma warning disable IDE0001 // Simplify Names return Task.FromResult(s); +#pragma warning restore IDE0001 // Simplify Names } return Task.FromResult(default); diff --git a/src/Mocha/test/Mocha.Sagas.Tests/IntegrationTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/IntegrationTests.cs index f4beef17215..f18100e51f0 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/IntegrationTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/IntegrationTests.cs @@ -1,19 +1,12 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Mocha; -using Mocha.Events; -using Mocha.Sagas; using Mocha.Transport.InMemory; namespace Mocha.Sagas.Tests; public class IntegrationTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); private static async Task CreateBusAsync(Action configure) { @@ -49,7 +42,7 @@ public async Task Saga_Should_ExecuteThroughSteps() await bus.PublishAsync(new InitEvent(), CancellationToken.None); // wait for the saga to publish TestMessage so we can get the saga ID - Assert.True(await recorder.WaitAsync(Timeout), "Saga did not publish TestMessage within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Saga did not publish TestMessage within timeout"); var testMessage = Assert.Single(recorder.Messages); var sagaId = Assert.IsType(testMessage).Id; @@ -90,7 +83,7 @@ public async Task Saga_Should_Timeout() await bus.PublishAsync(new StartTimeoutEvent(), CancellationToken.None); // wait for the saga to publish a TriggerEvent so we can observe it started - Assert.True(await recorder.WaitAsync(Timeout), "Saga did not publish event within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Saga did not publish event within timeout"); var recorded = Assert.Single(recorder.Messages); var sagaId = Assert.IsType(recorded).CorrelationId!.Value; diff --git a/src/Mocha/test/Mocha.Sagas.Tests/MessagingTestBase.cs b/src/Mocha/test/Mocha.Sagas.Tests/MessagingTestBase.cs index cfb22dfe0da..71f09af7123 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/MessagingTestBase.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/MessagingTestBase.cs @@ -1,9 +1,5 @@ -using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Npgsql; namespace Mocha.Sagas.Tests; @@ -54,7 +50,7 @@ public async Task StartBusAsync(IServiceProvider services) await runtime.StartAsync(CancellationToken.None); - return new Disposable(async () => await runtime.DisposeAsync()); + return new Disposable(runtime.DisposeAsync); } private sealed class Disposable(Func dispose) : IAsyncDisposable diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaDescriptorTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaDescriptorTests.cs index 0ec9b5623e8..2d0838ad9e1 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaDescriptorTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaDescriptorTests.cs @@ -1,18 +1,14 @@ -using System; -using System.Linq; -using Mocha; - namespace Mocha.Sagas.Tests; public class SagaDescriptorTests { - private static readonly IMessagingConfigurationContext _context = TestMessagingSetupContext.Instance; + private static readonly IMessagingConfigurationContext s_context = TestMessagingSetupContext.Instance; [Fact] public void Name_ShouldSetSagaName() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); // Act sagaDescriptor.Name("TestSaga"); @@ -25,7 +21,7 @@ public void Name_ShouldSetSagaName() public void Initially_ShouldSetInitialState_WhenNoStateExists() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); // Act sagaDescriptor.Initially().OnEvent(); @@ -40,7 +36,7 @@ public void Initially_ShouldSetInitialState_WhenNoStateExists() public void Initially_ShouldReturnExistingInitialState_WhenAlreadyExists() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); var initialState = sagaDescriptor.Initially(); // Act @@ -54,7 +50,7 @@ public void Initially_ShouldReturnExistingInitialState_WhenAlreadyExists() public void During_ShouldAddNewState_WhenStateDoesNotExist() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); // Act sagaDescriptor.During("TestState"); @@ -70,7 +66,7 @@ public void During_ShouldAddNewState_WhenStateDoesNotExist() public void During_ShouldReturnExistingState_WhenStateAlreadyExists() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); var existingState = sagaDescriptor.During("TestState"); // Act @@ -84,7 +80,7 @@ public void During_ShouldReturnExistingState_WhenStateAlreadyExists() public void DuringAny_ShouldAddNewStateWithNullName_WhenNoneExists() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); // Act sagaDescriptor.DuringAny().OnEvent(); @@ -100,7 +96,7 @@ public void DuringAny_ShouldAddNewStateWithNullName_WhenNoneExists() public void DuringAny_ShouldReturnExistingStateWithNullName_WhenAlreadyExists() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); var existingState = sagaDescriptor.DuringAny(); // Act @@ -114,7 +110,7 @@ public void DuringAny_ShouldReturnExistingStateWithNullName_WhenAlreadyExists() public void CreateDefinition_ShouldReturnAllStatesInDescriptor() { // Arrange - var sagaDescriptor = new SagaDescriptor(_context); + var sagaDescriptor = new SagaDescriptor(s_context); sagaDescriptor.Initially(); sagaDescriptor.During("TestState"); sagaDescriptor.DuringAny(); diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaExecutionTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaExecutionTests.cs index b4854d92b21..f31fba939c6 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaExecutionTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaExecutionTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Features; using Mocha.Transport.InMemory; @@ -18,7 +12,7 @@ namespace Mocha.Sagas.Tests; /// public sealed class SagaExecutionTests { - private static readonly IMessagingRuntime _runtime = CreateRuntime(); + private static readonly IMessagingRuntime s_runtime = CreateRuntime(); private readonly TestMessageOutbox _outbox; private readonly TestSagaStore _store; @@ -1416,7 +1410,7 @@ private TestConsumeContext CreateContext(Saga saga, object message) CorrelationId = Guid.NewGuid().ToString(), MessageId = Guid.NewGuid().ToString(), Services = _services, - Runtime = _runtime + Runtime = s_runtime }; // Set the message via MessageParsingFeature so context.GetMessage() works diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaInitializationTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaInitializationTests.cs index b54bcca303a..64655569778 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaInitializationTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaInitializationTests.cs @@ -1,7 +1,3 @@ -using System; -using System.Linq; -using Mocha; - namespace Mocha.Sagas.Tests; public class SagaInitializationTests diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaStateDescriptorTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaStateDescriptorTests.cs index 12433fb36e4..c3987a38169 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaStateDescriptorTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaStateDescriptorTests.cs @@ -1,17 +1,14 @@ -using System; -using Mocha; - namespace Mocha.Sagas.Tests; public class SagaStateDescriptorTests { - private static readonly IMessagingConfigurationContext _context = TestMessagingSetupContext.Instance; + private static readonly IMessagingConfigurationContext s_context = TestMessagingSetupContext.Instance; [Fact] public void OnEvent_ShouldAddNewTransition_WhenEventTypeDoesNotExist() { // Arrange - var stateDescriptor = new SagaStateDescriptor(_context, "TestState"); + var stateDescriptor = new SagaStateDescriptor(s_context, "TestState"); // Act stateDescriptor.OnEvent(); @@ -25,7 +22,7 @@ public void OnEvent_ShouldAddNewTransition_WhenEventTypeDoesNotExist() public void OnEvent_ShouldReturnExistingTransition_WhenEventTypeAlreadyExists() { // Arrange - var stateDescriptor = new SagaStateDescriptor(_context, "TestState"); + var stateDescriptor = new SagaStateDescriptor(s_context, "TestState"); var existingTransition = stateDescriptor.OnEvent(); // Act @@ -39,7 +36,7 @@ public void OnEvent_ShouldReturnExistingTransition_WhenEventTypeAlreadyExists() public void CreateDefinition_ShouldReturnStateDefinitionWithTransitions() { // Arrange - var stateDescriptor = new SagaStateDescriptor(_context, "TestState"); + var stateDescriptor = new SagaStateDescriptor(s_context, "TestState"); stateDescriptor.OnEvent(); stateDescriptor.OnEvent(); diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaStateMachineTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaStateMachineTests.cs index 49f52e3e0c8..3512ae43bf7 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaStateMachineTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaStateMachineTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Features; using Mocha.Transport.InMemory; @@ -11,7 +6,7 @@ namespace Mocha.Sagas.Tests; public sealed class SagaStateMachineTests { - private static readonly IMessagingRuntime _runtime = CreateRuntime(); + private static readonly IMessagingRuntime s_runtime = CreateRuntime(); private readonly TestMessageOutbox _outbox; private readonly TestSagaStore _store; @@ -937,7 +932,7 @@ private TestConsumeContext CreateContext(Saga saga, object message) CorrelationId = Guid.NewGuid().ToString(), MessageId = Guid.NewGuid().ToString(), Services = _services, - Runtime = _runtime + Runtime = s_runtime }; // Set the message via MessageParsingFeature so context.GetMessage() works diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaTransitionDescriptorTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaTransitionDescriptorTests.cs index a13a5e7c969..08e0e60ee54 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaTransitionDescriptorTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaTransitionDescriptorTests.cs @@ -1,18 +1,14 @@ -using System; -using Mocha; -using Mocha.Events; - namespace Mocha.Sagas.Tests; public class SagaTransitionDescriptorTests { - private static readonly IMessagingConfigurationContext _context = TestMessagingSetupContext.Instance; + private static readonly IMessagingConfigurationContext s_context = TestMessagingSetupContext.Instance; [Fact] public void Then_ShouldSetAction_WhenCalled() { // Arrange - var transitionDescriptor = new SagaTransitionDescriptor(_context, SagaTransitionKind.Event); + var transitionDescriptor = new SagaTransitionDescriptor(s_context, SagaTransitionKind.Event); Action action = (state, evt) => { }; // Act @@ -27,7 +23,7 @@ public void Then_ShouldSetAction_WhenCalled() public void TransitionTo_ShouldSetTransitionTo_WhenCalled() { // Arrange - var transitionDescriptor = new SagaTransitionDescriptor(_context, SagaTransitionKind.Event); + var transitionDescriptor = new SagaTransitionDescriptor(s_context, SagaTransitionKind.Event); // Act transitionDescriptor.TransitionTo("NextState"); @@ -41,7 +37,7 @@ public void TransitionTo_ShouldSetTransitionTo_WhenCalled() public void Publish_ShouldAddNewPublishDefinition_WhenCalled() { // Arrange - var transitionDescriptor = new SagaTransitionDescriptor(_context, SagaTransitionKind.Event); + var transitionDescriptor = new SagaTransitionDescriptor(s_context, SagaTransitionKind.Event); // Act transitionDescriptor.Publish((_, state) => new SagaTimedOutEvent(Guid.NewGuid())); @@ -56,7 +52,7 @@ public void Publish_ShouldAddNewPublishDefinition_WhenCalled() public void StateFactory_ShouldSetFactory_WhenCalled() { // Arrange - var transitionDescriptor = new SagaTransitionDescriptor(_context, SagaTransitionKind.Event); + var transitionDescriptor = new SagaTransitionDescriptor(s_context, SagaTransitionKind.Event); Func factory = state => new TestState(Guid.NewGuid(), state); // Act diff --git a/src/Mocha/test/Mocha.Sagas.Tests/SagaValidationTests.cs b/src/Mocha/test/Mocha.Sagas.Tests/SagaValidationTests.cs index 7f3868b676e..8aee3883c3a 100644 --- a/src/Mocha/test/Mocha.Sagas.Tests/SagaValidationTests.cs +++ b/src/Mocha/test/Mocha.Sagas.Tests/SagaValidationTests.cs @@ -1,6 +1,3 @@ -using System; -using Mocha; - namespace Mocha.Sagas.Tests; public class SagaValidationTests diff --git a/src/Mocha/test/Mocha.Tests/CircuitBreaker/CircuitBreakerTests.cs b/src/Mocha/test/Mocha.Tests/CircuitBreaker/CircuitBreakerTests.cs index 11c419335b9..6eb6edc9cd4 100644 --- a/src/Mocha/test/Mocha.Tests/CircuitBreaker/CircuitBreakerTests.cs +++ b/src/Mocha/test/Mocha.Tests/CircuitBreaker/CircuitBreakerTests.cs @@ -6,7 +6,7 @@ namespace Mocha.Tests; public class CircuitBreakerMiddlewareTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task ClosedCircuit_Should_AllowMessageToFlow_When_HandlerSucceeds() @@ -26,7 +26,7 @@ public async Task ClosedCircuit_Should_AllowMessageToFlow_When_HandlerSucceeds() await bus.PublishAsync(new TestEvent { Data = "ok-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); Assert.Single(recorder.Messages); } @@ -50,7 +50,7 @@ public async Task ClosedCircuit_Should_AllowMultipleMessagesToFlow_When_AllHandl await bus.PublishAsync(new TestEvent { Data = "ok-3" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout, expectedCount: 3)); + Assert.True(await recorder.WaitAsync(s_timeout, expectedCount: 3)); Assert.Equal(3, recorder.Messages.Count); } @@ -106,7 +106,7 @@ public async Task CircuitBreaker_Should_AllowMessagesToFlow_When_CustomConfigure await bus.PublishAsync(new TestEvent { Data = "custom-1" }, CancellationToken.None); // assert - messages still flow when circuit is closed - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); Assert.Single(recorder.Messages); } @@ -129,7 +129,7 @@ public async Task CircuitBreaker_Should_AllowMessagesToFlow_When_ExplicitlyDisab await bus.PublishAsync(new TestEvent { Data = "disabled-cb" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); Assert.Single(recorder.Messages); } @@ -204,7 +204,7 @@ public async Task CircuitBreaker_Should_AllowMessagesToFlowAgain_When_RecoveredF await Task.Delay(TimeSpan.FromSeconds(2)); // should now allow a message through (half-open -> closed on success) - var waitForBreak = recorder.WaitAsync(Timeout); + var waitForBreak = recorder.WaitAsync(s_timeout); await bus.PublishAsync(new TestEvent { Data = "third" }, CancellationToken.None); Assert.True(await waitForBreak); diff --git a/src/Mocha/test/Mocha.Tests/Consumers/Batching/BatchCollectorTests.cs b/src/Mocha/test/Mocha.Tests/Consumers/Batching/BatchCollectorTests.cs index 707275c5c6f..6d53cfe65b5 100644 --- a/src/Mocha/test/Mocha.Tests/Consumers/Batching/BatchCollectorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Consumers/Batching/BatchCollectorTests.cs @@ -6,7 +6,7 @@ namespace Mocha.Tests.Consumers.Batching; public sealed class BatchCollectorTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Add_Should_DispatchBatch_When_MaxBatchSizeReached() @@ -19,7 +19,7 @@ public async Task Add_Should_DispatchBatch_When_MaxBatchSizeReached() await AddEntries(collector, 3); // assert - Assert.True(await dispatched.WaitAsync(Timeout), "Batch was not dispatched when MaxBatchSize reached"); + Assert.True(await dispatched.WaitAsync(s_timeout), "Batch was not dispatched when MaxBatchSize reached"); var batch = dispatched.Single(); Assert.Equal(3, batch.Count); @@ -47,7 +47,7 @@ public async Task Add_Should_DispatchBatch_When_TimerFires() fakeTime.Advance(timeout.Add(TimeSpan.FromMilliseconds(10))); // assert - Assert.True(await dispatched.WaitAsync(Timeout), "Batch was not dispatched when timer fired"); + Assert.True(await dispatched.WaitAsync(s_timeout), "Batch was not dispatched when timer fired"); var batch = dispatched.Single(); Assert.Single(batch); @@ -67,7 +67,7 @@ public async Task DisposeAsync_Should_FlushRemaining_When_BufferHasMessages() await collector.DisposeAsync(); // assert - Assert.True(await dispatched.WaitAsync(Timeout), "Remaining buffer was not flushed on dispose"); + Assert.True(await dispatched.WaitAsync(s_timeout), "Remaining buffer was not flushed on dispose"); var batch = dispatched.Single(); Assert.Equal(5, batch.Count); @@ -98,13 +98,13 @@ public async Task Add_Should_DispatchMultipleBatches_When_MoreThanMaxSizeAdded() await AddEntries(collector, 7); // wait for the two size-triggered batches - Assert.True(await dispatched.WaitAsync(Timeout, expectedCount: 2)); + Assert.True(await dispatched.WaitAsync(s_timeout, expectedCount: 2)); // dispose to flush the remaining 1 await collector.DisposeAsync(); // wait for 1 more batch (the forced flush) - Assert.True(await dispatched.WaitAsync(Timeout, expectedCount: 1)); + Assert.True(await dispatched.WaitAsync(s_timeout, expectedCount: 1)); // assert Assert.Equal(3, dispatched.Batches.Count); @@ -132,7 +132,7 @@ public async Task Add_Should_BeThreadSafe_When_CalledConcurrently() // wait for all full batches (100/10 = 10 batches) Assert.True( - await dispatched.WaitAsync(Timeout, expectedCount: totalMessages / batchSize), + await dispatched.WaitAsync(s_timeout, expectedCount: totalMessages / batchSize), "Not all batches were dispatched under concurrent load"); // assert — total messages across all batches should equal totalMessages @@ -159,7 +159,7 @@ public async Task Add_Should_DispatchTwoFullBatches_When_ConcurrentProducersSend // assert — exactly 2 batches dispatched Assert.True( - await dispatched.WaitAsync(Timeout, expectedCount: 2), + await dispatched.WaitAsync(s_timeout, expectedCount: 2), "Expected exactly 2 batches to be dispatched"); Assert.Equal(2, dispatched.Batches.Count); @@ -184,7 +184,7 @@ public async Task Add_Should_PreserveOrdering_When_MessagesAddedSequentially() } // assert — batch dispatched in order - Assert.True(await dispatched.WaitAsync(Timeout), "Batch was not dispatched"); + Assert.True(await dispatched.WaitAsync(s_timeout), "Batch was not dispatched"); var batch = dispatched.Single(); Assert.Equal(5, batch.Count); diff --git a/src/Mocha/test/Mocha.Tests/Consumers/ConsumerBehaviorTests.cs b/src/Mocha/test/Mocha.Tests/Consumers/ConsumerBehaviorTests.cs index 98b4c21c0fc..857dffcd69f 100644 --- a/src/Mocha/test/Mocha.Tests/Consumers/ConsumerBehaviorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Consumers/ConsumerBehaviorTests.cs @@ -261,7 +261,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Tests/Conventions/DefaultNamingConventionsTests.cs b/src/Mocha/test/Mocha.Tests/Conventions/DefaultNamingConventionsTests.cs index 082e08bffcb..5f3c0b9bf4e 100644 --- a/src/Mocha/test/Mocha.Tests/Conventions/DefaultNamingConventionsTests.cs +++ b/src/Mocha/test/Mocha.Tests/Conventions/DefaultNamingConventionsTests.cs @@ -4,7 +4,7 @@ namespace Mocha.Tests; public class DefaultNamingConventionsTests { - private static readonly HostInfo HostWithService = new() + private static readonly HostInfo s_hostWithService = new() { MachineName = "test-machine", ProcessName = "test-process", @@ -21,7 +21,7 @@ public class DefaultNamingConventionsTests InstanceId = Guid.NewGuid() }; - private static readonly HostInfo HostWithoutService = new() + private static readonly HostInfo s_hostWithoutService = new() { MachineName = "test-machine", ProcessName = "test-process", @@ -41,7 +41,7 @@ public class DefaultNamingConventionsTests [Fact] public void GetReceiveEndpointName_Type_Should_ReturnKebabCaseName_When_HandlerSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(OrderCreatedHandler), ReceiveEndpointKind.Default); @@ -51,7 +51,7 @@ public void GetReceiveEndpointName_Type_Should_ReturnKebabCaseName_When_HandlerS [Fact] public void GetReceiveEndpointName_Type_Should_StripConsumerSuffix_When_ConsumerSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(PaymentProcessedConsumer), ReceiveEndpointKind.Default); @@ -61,7 +61,7 @@ public void GetReceiveEndpointName_Type_Should_StripConsumerSuffix_When_Consumer [Fact] public void GetReceiveEndpointName_Type_Should_AppendErrorSuffix_When_ErrorKind() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(OrderCreatedHandler), ReceiveEndpointKind.Error); @@ -71,7 +71,7 @@ public void GetReceiveEndpointName_Type_Should_AppendErrorSuffix_When_ErrorKind( [Fact] public void GetReceiveEndpointName_Type_Should_AppendSkippedSuffix_When_SkippedKind() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(OrderCreatedHandler), ReceiveEndpointKind.Skipped); @@ -81,7 +81,7 @@ public void GetReceiveEndpointName_Type_Should_AppendSkippedSuffix_When_SkippedK [Fact] public void GetReceiveEndpointName_Type_Should_AppendReplySuffix_When_ReplyKind() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(OrderCreatedHandler), ReceiveEndpointKind.Reply); @@ -91,7 +91,7 @@ public void GetReceiveEndpointName_Type_Should_AppendReplySuffix_When_ReplyKind( [Fact] public void GetReceiveEndpointName_Type_Should_StripGenericArity_When_GenericHandler() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(typeof(MyHandler<>), ReceiveEndpointKind.Default); @@ -101,7 +101,7 @@ public void GetReceiveEndpointName_Type_Should_StripGenericArity_When_GenericHan [Fact] public void GetReceiveEndpointName_Type_Should_Throw_When_NullType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetReceiveEndpointName((Type)null!, ReceiveEndpointKind.Default) @@ -111,7 +111,7 @@ public void GetReceiveEndpointName_Type_Should_Throw_When_NullType() [Fact] public void GetReceiveEndpointName_String_Should_ReturnKebabCase_When_PascalCaseName() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName("OrderProcessing", ReceiveEndpointKind.Default); @@ -121,7 +121,7 @@ public void GetReceiveEndpointName_String_Should_ReturnKebabCase_When_PascalCase [Fact] public void GetReceiveEndpointName_String_Should_AppendErrorSuffix_When_ErrorKind() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName("OrderProcessing", ReceiveEndpointKind.Error); @@ -131,7 +131,7 @@ public void GetReceiveEndpointName_String_Should_AppendErrorSuffix_When_ErrorKin [Fact] public void GetReceiveEndpointName_String_Should_StripConsumerSuffix_When_ConsumerSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName("MyCustomConsumer", ReceiveEndpointKind.Default); @@ -141,7 +141,7 @@ public void GetReceiveEndpointName_String_Should_StripConsumerSuffix_When_Consum [Fact] public void GetReceiveEndpointName_String_Should_Throw_When_EmptyString() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetReceiveEndpointName("", ReceiveEndpointKind.Default)); } @@ -149,7 +149,7 @@ public void GetReceiveEndpointName_String_Should_Throw_When_EmptyString() [Fact] public void GetReceiveEndpointName_String_Should_Throw_When_Whitespace() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetReceiveEndpointName(" ", ReceiveEndpointKind.Default)); } @@ -157,7 +157,7 @@ public void GetReceiveEndpointName_String_Should_Throw_When_Whitespace() [Fact] public void GetReceiveEndpointName_String_Should_TrimWhitespace_When_PaddedName() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetReceiveEndpointName(" OrderProcessing ", ReceiveEndpointKind.Default); @@ -167,7 +167,7 @@ public void GetReceiveEndpointName_String_Should_TrimWhitespace_When_PaddedName( [Fact] public void GetSagaName_Should_StripHandlerSuffixAndKebabCase_When_HandlerSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSagaName(typeof(OrderCreatedHandler)); @@ -177,7 +177,7 @@ public void GetSagaName_Should_StripHandlerSuffixAndKebabCase_When_HandlerSuffix [Fact] public void GetSagaName_Should_StripConsumerSuffixAndKebabCase_When_ConsumerSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSagaName(typeof(PaymentProcessedConsumer)); @@ -187,7 +187,7 @@ public void GetSagaName_Should_StripConsumerSuffixAndKebabCase_When_ConsumerSuff [Fact] public void GetSagaName_Should_ReturnKebabCase_When_NoKnownSuffix() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSagaName(typeof(OrderWorkflow)); @@ -197,7 +197,7 @@ public void GetSagaName_Should_ReturnKebabCase_When_NoKnownSuffix() [Fact] public void GetInstanceEndpoint_Should_ReturnFormattedGuid_When_ValidGuid() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var guid = Guid.Parse("12345678-1234-1234-1234-123456789abc"); var result = sut.GetInstanceEndpoint(guid); @@ -208,7 +208,7 @@ public void GetInstanceEndpoint_Should_ReturnFormattedGuid_When_ValidGuid() [Fact] public void GetInstanceEndpoint_Should_Throw_When_EmptyGuid() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetInstanceEndpoint(Guid.Empty)); } @@ -216,7 +216,7 @@ public void GetInstanceEndpoint_Should_Throw_When_EmptyGuid() [Fact] public void GetSendEndpointName_Should_StripCommandSuffix_When_CommandType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSendEndpointName(typeof(CreateOrderCommand)); @@ -226,7 +226,7 @@ public void GetSendEndpointName_Should_StripCommandSuffix_When_CommandType() [Fact] public void GetSendEndpointName_Should_StripMessageSuffix_When_MessageType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSendEndpointName(typeof(ProcessPaymentMessage)); @@ -236,7 +236,7 @@ public void GetSendEndpointName_Should_StripMessageSuffix_When_MessageType() [Fact] public void GetSendEndpointName_Should_StripEventSuffix_When_EventType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetSendEndpointName(typeof(OrderCreatedEvent)); @@ -246,7 +246,7 @@ public void GetSendEndpointName_Should_StripEventSuffix_When_EventType() [Fact] public void GetSendEndpointName_Should_Throw_When_NullType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetSendEndpointName(null!)); } @@ -254,7 +254,7 @@ public void GetSendEndpointName_Should_Throw_When_NullType() [Fact] public void GetPublishEndpointName_Should_ReturnNamespaceDotName_When_ValidType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetPublishEndpointName(typeof(CreateOrderCommand)); @@ -264,7 +264,7 @@ public void GetPublishEndpointName_Should_ReturnNamespaceDotName_When_ValidType( [Fact] public void GetPublishEndpointName_Should_StripMessageSuffix_When_MessageType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetPublishEndpointName(typeof(ProcessPaymentMessage)); @@ -274,7 +274,7 @@ public void GetPublishEndpointName_Should_StripMessageSuffix_When_MessageType() [Fact] public void GetPublishEndpointName_Should_Throw_When_NullType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetPublishEndpointName(null!)); } @@ -282,7 +282,7 @@ public void GetPublishEndpointName_Should_Throw_When_NullType() [Fact] public void GetMessageIdentity_Should_ReturnUrnFormat_When_NonGenericType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetMessageIdentity(typeof(CreateOrderCommand)); @@ -293,7 +293,7 @@ public void GetMessageIdentity_Should_ReturnUrnFormat_When_NonGenericType() [Fact] public void GetMessageIdentity_Should_IncludeNamespace_When_NonGenericType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetMessageIdentity(typeof(CreateOrderCommand)); @@ -303,7 +303,7 @@ public void GetMessageIdentity_Should_IncludeNamespace_When_NonGenericType() [Fact] public void GetMessageIdentity_Should_IncludeGenericNotation_When_OpenGenericWithOneArg() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetMessageIdentity(typeof(GenericMessage<>)); @@ -313,7 +313,7 @@ public void GetMessageIdentity_Should_IncludeGenericNotation_When_OpenGenericWit [Fact] public void GetMessageIdentity_Should_IncludeGenericNotation_When_OpenGenericWithTwoArgs() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetMessageIdentity(typeof(GenericMessage<,>)); @@ -323,7 +323,7 @@ public void GetMessageIdentity_Should_IncludeGenericNotation_When_OpenGenericWit [Fact] public void GetMessageIdentity_Should_IncludeClosedGenericArgs_When_ClosedGeneric() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); var result = sut.GetMessageIdentity(typeof(GenericMessage)); @@ -333,7 +333,7 @@ public void GetMessageIdentity_Should_IncludeClosedGenericArgs_When_ClosedGeneri [Fact] public void GetMessageIdentity_Should_Throw_When_NullType() { - var sut = new DefaultNamingConventions(HostWithService); + var sut = new DefaultNamingConventions(s_hostWithService); Assert.Throws(() => sut.GetMessageIdentity(null!)); } diff --git a/src/Mocha/test/Mocha.Tests/Descriptions/MessageBusDescriptionVisitorTests.cs b/src/Mocha/test/Mocha.Tests/Descriptions/MessageBusDescriptionVisitorTests.cs index 722c136f696..5e2096e9a82 100644 --- a/src/Mocha/test/Mocha.Tests/Descriptions/MessageBusDescriptionVisitorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Descriptions/MessageBusDescriptionVisitorTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Sagas; using Mocha.Transport.InMemory; diff --git a/src/Mocha/test/Mocha.Tests/Descriptions/MessagingVisitorTests.cs b/src/Mocha/test/Mocha.Tests/Descriptions/MessagingVisitorTests.cs index 25c715866bf..8ed4a0bce5e 100644 --- a/src/Mocha/test/Mocha.Tests/Descriptions/MessagingVisitorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Descriptions/MessagingVisitorTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Sagas; using Mocha.Transport.InMemory; @@ -345,7 +344,7 @@ private static MessagingRuntime CreateRuntime(Action con public sealed class RecordingContext { - public List Calls { get; } = new(); + public List Calls { get; } = []; } public class RecordingVisitor : MessagingVisitor diff --git a/src/Mocha/test/Mocha.Tests/Endpoints/EndpointRouterTests.cs b/src/Mocha/test/Mocha.Tests/Endpoints/EndpointRouterTests.cs index c45f9151517..6ae47e0a6fe 100644 --- a/src/Mocha/test/Mocha.Tests/Endpoints/EndpointRouterTests.cs +++ b/src/Mocha/test/Mocha.Tests/Endpoints/EndpointRouterTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory; namespace Mocha.Tests; @@ -201,12 +200,15 @@ public async Task ConcurrentReadWrite_Should_NotCorruptState() var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)); // act - concurrent reads and writes - var readTask = Task.Run(() => { while (!cts.IsCancellationRequested) + var readTask = Task.Run(() => { - _ = endpoints.Endpoints; - endpoints.TryGet(new Uri("queue:test"), out _); - _ = endpoints.GetAll(new Uri("queue:test")); - } }, default); + while (!cts.IsCancellationRequested) + { + _ = endpoints.Endpoints; + endpoints.TryGet(new Uri("queue:test"), out _); + _ = endpoints.GetAll(new Uri("queue:test")); + } + }, default); var writeTask = Task.Run(() => { diff --git a/src/Mocha/test/Mocha.Tests/Faults/FaultHandlingTests.cs b/src/Mocha/test/Mocha.Tests/Faults/FaultHandlingTests.cs index 734b541a4fc..c867a45af40 100644 --- a/src/Mocha/test/Mocha.Tests/Faults/FaultHandlingTests.cs +++ b/src/Mocha/test/Mocha.Tests/Faults/FaultHandlingTests.cs @@ -1,6 +1,4 @@ -using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Events; using Mocha.Transport.InMemory; @@ -49,7 +47,7 @@ public async Task RequestAsync_Should_ThrowException_When_HandlerThrows() // act & assert — exact exception type depends on transport timing: // RemoteErrorException if the fault response arrives, TaskCanceledException // if the CTS fires first. Both confirm the handler did not succeed. - using var cts = new CancellationTokenSource(Timeout); + using var cts = new CancellationTokenSource(s_timeout); await Assert.ThrowsAnyAsync(async () => await bus.RequestAsync(new TestRequest { Data = "fail-me" }, cts.Token) ); @@ -68,7 +66,7 @@ public async Task RequestAsync_Should_PreserveExceptionType_When_HandlerThrows() // act & assert — exact exception type depends on transport timing: // RemoteErrorException if the fault response arrives, TaskCanceledException // if the CTS fires first. Both confirm the handler did not succeed. - using var cts = new CancellationTokenSource(Timeout); + using var cts = new CancellationTokenSource(s_timeout); var ex = await Assert.ThrowsAnyAsync(async () => await bus.RequestAsync(new TestRequest { Data = "err" }, cts.Token) ); @@ -125,7 +123,7 @@ public async Task PublishEvent_Should_ProcessSuccessfully_When_EventHandlerSucce await bus.PublishAsync(new TestEvent { Data = "success" }, CancellationToken.None); // assert - handler received it - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); Assert.Single(recorder.Messages); } @@ -168,7 +166,7 @@ public async Task RequestAsync_Should_PropagateExceptions_When_ConcurrentRequest var bus = scope.ServiceProvider.GetRequiredService(); // exact exception type depends on transport timing (see above) - using var cts = new CancellationTokenSource(Timeout); + using var cts = new CancellationTokenSource(s_timeout); var ex = await Assert.ThrowsAnyAsync(async () => await bus.RequestAsync(new TestRequest { Data = $"concurrent-{i}" }, cts.Token) ); @@ -192,7 +190,7 @@ await bus.RequestAsync(new TestRequest { Data = $"concurrent-{i}" }, cts.Token) }); } - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); private static async Task CreateBusAsync(Action configure) { diff --git a/src/Mocha/test/Mocha.Tests/Headers/HeadersSerializationTests.cs b/src/Mocha/test/Mocha.Tests/Headers/HeadersSerializationTests.cs index dd545b0bdf9..3f0bc895750 100644 --- a/src/Mocha/test/Mocha.Tests/Headers/HeadersSerializationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Headers/HeadersSerializationTests.cs @@ -1,5 +1,4 @@ using System.Text.Json; -using Mocha; namespace Mocha.Tests; diff --git a/src/Mocha/test/Mocha.Tests/Headers/HeadersTests.cs b/src/Mocha/test/Mocha.Tests/Headers/HeadersTests.cs index f2d7ec49bb1..73facfe4072 100644 --- a/src/Mocha/test/Mocha.Tests/Headers/HeadersTests.cs +++ b/src/Mocha/test/Mocha.Tests/Headers/HeadersTests.cs @@ -1,6 +1,4 @@ -using System.Text; using System.Text.Json; -using Mocha; namespace Mocha.Tests; @@ -55,7 +53,7 @@ public void TryGetValue_Should_ReturnFalse_When_KeyMissing() { var headers = new Headers(); - var found = headers.TryGetValue("missing", out var value); + var found = headers.TryGetValue("missing", out _); Assert.False(found); } diff --git a/src/Mocha/test/Mocha.Tests/Host/HostInfoTests.cs b/src/Mocha/test/Mocha.Tests/Host/HostInfoTests.cs index b6964c98e07..a1d0c76633f 100644 --- a/src/Mocha/test/Mocha.Tests/Host/HostInfoTests.cs +++ b/src/Mocha/test/Mocha.Tests/Host/HostInfoTests.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Extensions.DependencyInjection; -using Mocha.Middlewares; using Mocha.Transport.InMemory; namespace Mocha.Tests; diff --git a/src/Mocha/test/Mocha.Tests/IntegrationTests/ConsumerIntegrationTestsBase.cs b/src/Mocha/test/Mocha.Tests/IntegrationTests/ConsumerIntegrationTestsBase.cs index 6abaf1a62b1..cc347b7fa1c 100644 --- a/src/Mocha/test/Mocha.Tests/IntegrationTests/ConsumerIntegrationTestsBase.cs +++ b/src/Mocha/test/Mocha.Tests/IntegrationTests/ConsumerIntegrationTestsBase.cs @@ -1,6 +1,4 @@ -using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory; namespace Mocha.Tests.IntegrationTests; diff --git a/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeRegistryTests.cs b/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeRegistryTests.cs index c8271ff48e3..5e7d189ded6 100644 --- a/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeRegistryTests.cs +++ b/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeRegistryTests.cs @@ -124,12 +124,17 @@ public void GetOrAdd_Should_ReturnSameInstance_When_ConcurrentCallsForSameType() .ToArray(); foreach (var thread in threads) + { thread.Start(); + } + foreach (var thread in threads) + { thread.Join(); + } // assert - Assert.All(results, r => Assert.NotNull(r)); + Assert.All(results, Assert.NotNull); Assert.All(results, r => Assert.Same(results[0], r)); } diff --git a/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeTests.cs b/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeTests.cs index fb17d82bc51..ab3a30af856 100644 --- a/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeTests.cs +++ b/src/Mocha/test/Mocha.Tests/MessageTypes/MessageTypeTests.cs @@ -94,7 +94,7 @@ public void MessageTypeEnclosedMessageIdentities_Should_MatchEnclosedMessageType Assert.NotNull(messageType); Assert.Equal(messageType.EnclosedMessageTypes.Length, messageType.EnclosedMessageIdentities.Length); - for (int i = 0; i < messageType.EnclosedMessageTypes.Length; i++) + for (var i = 0; i < messageType.EnclosedMessageTypes.Length; i++) { Assert.Equal(messageType.EnclosedMessageTypes[i].Identity, messageType.EnclosedMessageIdentities[i]); } diff --git a/src/Mocha/test/Mocha.Tests/Middlewares/MiddlewareTests.cs b/src/Mocha/test/Mocha.Tests/Middlewares/MiddlewareTests.cs index 3b3da2f5511..44fa61f6408 100644 --- a/src/Mocha/test/Mocha.Tests/Middlewares/MiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Tests/Middlewares/MiddlewareTests.cs @@ -46,7 +46,7 @@ public async Task PublishAsync_Should_FlowEventThroughMiddleware_When_EventPubli await bus.PublishAsync(new OrderCreated { OrderId = "MW-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Event did not flow through middleware pipeline"); + Assert.True(await recorder.WaitAsync(s_timeout), "Event did not flow through middleware pipeline"); var message = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal("MW-1", message.OrderId); @@ -92,7 +92,7 @@ public async Task RequestAsync_Should_FlowRequestThroughMiddleware_When_SendRequ await bus.RequestAsync(new ProcessPayment { Amount = 42.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Request did not flow through middleware pipeline"); + Assert.True(await recorder.WaitAsync(s_timeout), "Request did not flow through middleware pipeline"); var message = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal(42.00m, message.Amount); @@ -266,7 +266,7 @@ public async Task Pipeline_Should_ProcessAllEvents_When_MultipleEventsPublished( } // assert - Assert.True(await recorder.WaitAsync(Timeout, expectedCount: 5)); + Assert.True(await recorder.WaitAsync(s_timeout, expectedCount: 5)); Assert.Equal(5, recorder.Messages.Count); } @@ -294,7 +294,7 @@ public async Task Pipeline_Should_ProcessAllEventsWhenConcurrent_When_Concurrent await Task.WhenAll(tasks); // assert - Assert.True(await recorder.WaitAsync(Timeout, expectedCount: 10)); + Assert.True(await recorder.WaitAsync(s_timeout, expectedCount: 10)); Assert.Equal(10, recorder.Messages.Count); } @@ -329,7 +329,7 @@ public async Task Pipeline_Should_ProcessAllRequestsWhenConcurrent_When_Concurre Assert.All(responses, r => Assert.Equal("Shipped", r.Status)); } - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); private static MessagingRuntime CreateRuntime(Action configure) { diff --git a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/MessageTypeSelectionMiddlewareTests.cs b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/MessageTypeSelectionMiddlewareTests.cs index 27ec2f4149a..0db4c63513f 100644 --- a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/MessageTypeSelectionMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/MessageTypeSelectionMiddlewareTests.cs @@ -140,7 +140,7 @@ public async Task InvokeAsync_Should_CallNext_When_EnvelopeIsNull() private sealed class MockMessageTypeRegistry : IMessageTypeRegistry { - private readonly Dictionary _typesByIdentity = new(); + private readonly Dictionary _typesByIdentity = []; public IMessageSerializerRegistry Serializers => null!; public IReadOnlySet MessageTypes => new HashSet(_typesByIdentity.Values); diff --git a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveDeadLetterMiddlewareTests.cs b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveDeadLetterMiddlewareTests.cs index 839beb2906e..a3187fac2ee 100644 --- a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveDeadLetterMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveDeadLetterMiddlewareTests.cs @@ -625,11 +625,13 @@ public StubDispatchEndpoint(MessagingTransport transport) : base(transport) { } protected override void OnInitialize( IMessagingConfigurationContext context, - DispatchEndpointConfiguration configuration) { } + DispatchEndpointConfiguration configuration) + { } protected override void OnComplete( IMessagingConfigurationContext context, - DispatchEndpointConfiguration configuration) { } + DispatchEndpointConfiguration configuration) + { } protected override ValueTask DispatchAsync(IDispatchContext context) => ValueTask.CompletedTask; } diff --git a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveFaultMiddlewareTests.cs b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveFaultMiddlewareTests.cs index 517ba931e4f..056df4f83ea 100644 --- a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveFaultMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveFaultMiddlewareTests.cs @@ -330,7 +330,7 @@ await bus.RequestAsync(new FaultTestRequest { Id = $"conc-fail-{i}" }, cts.Token // assert - all 5 requests should have failed Assert.Equal(5, exceptions.Length); - Assert.All(exceptions, ex => Assert.NotNull(ex)); + Assert.All(exceptions, Assert.NotNull); } [Fact] diff --git a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveMiddlewareTestBase.cs b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveMiddlewareTestBase.cs index 5c30851dfd0..4d99c560e7f 100644 --- a/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveMiddlewareTestBase.cs +++ b/src/Mocha/test/Mocha.Tests/Middlewares/Receive/ReceiveMiddlewareTestBase.cs @@ -23,7 +23,7 @@ public abstract class ReceiveMiddlewareTestBase protected static IServiceProvider CreateServices(Action? configure = null) { var services = new ServiceCollection(); - services.AddSingleton(TimeProvider.System); + services.AddSingleton(TimeProvider.System); services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); configure?.Invoke(services); return services.BuildServiceProvider(); diff --git a/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs b/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs index 04bb9ed8a3e..fd48dc55d48 100644 --- a/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Outbox/OutboxIntegrationTests.cs @@ -1,6 +1,5 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Middlewares; using Mocha.Outbox; using Mocha.Transport.InMemory; @@ -9,7 +8,7 @@ namespace Mocha.Tests.Outbox; public class OutboxIntegrationTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); // ────────────────────────────────────────────────────────────────────── // Test 1: Outbox captures a published message @@ -29,7 +28,7 @@ public async Task Outbox_Should_CaptureMessage_When_EventPublished() await bus.PublishAsync(new OutboxTestEvent { Payload = "capture-me" }, CancellationToken.None); // assert — message captured by outbox, not delivered to transport - await WaitUntilAsync(() => outbox.Envelopes.Count >= 1, Timeout); + await WaitUntilAsync(() => outbox.Envelopes.Count >= 1, s_timeout); Assert.Single(outbox.Envelopes); } @@ -53,7 +52,7 @@ public async Task Outbox_Should_CaptureMultipleMessages_When_MultipleEventsPubli await bus.PublishAsync(new OutboxTestEvent { Payload = "third" }, CancellationToken.None); // assert — all three captured - await WaitUntilAsync(() => outbox.Envelopes.Count >= 3, Timeout); + await WaitUntilAsync(() => outbox.Envelopes.Count >= 3, s_timeout); Assert.Equal(3, outbox.Envelopes.Count); } @@ -91,8 +90,8 @@ await bus.PublishAsync( // assert — only one message captured (the one without skip), the skipped one // was delivered to handler - Assert.True(await recorder.WaitAsync(Timeout), "Skipped message should have been delivered to handler"); - await WaitUntilAsync(() => outbox.Envelopes.Count >= 1, Timeout); + Assert.True(await recorder.WaitAsync(s_timeout), "Skipped message should have been delivered to handler"); + await WaitUntilAsync(() => outbox.Envelopes.Count >= 1, s_timeout); Assert.Single(outbox.Envelopes); Assert.Single(recorder.Messages); @@ -123,7 +122,7 @@ public async Task Outbox_Should_SignalWorker_When_MessagePersisted() await bus.PublishAsync(new OutboxTestEvent { Payload = "signal-test" }, CancellationToken.None); // assert — signal was set after persist - await WaitUntilAsync(() => signal.SignalCount > 0, Timeout); + await WaitUntilAsync(() => signal.SignalCount > 0, s_timeout); Assert.True(signal.SignalCount >= 1, "Signal should have been set at least once"); } diff --git a/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStateStorageTests.cs b/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStateStorageTests.cs index c729ef869a6..faf42079e37 100644 --- a/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStateStorageTests.cs +++ b/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStateStorageTests.cs @@ -118,7 +118,7 @@ public async Task Storage_ThreadSafety_Concurrent_Save_And_Load() const int stateCount = 100; // act - concurrent saves - for (int i = 0; i < stateCount; i++) + for (var i = 0; i < stateCount; i++) { var localI = i; tasks.Add( diff --git a/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStoreTests.cs b/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStoreTests.cs index e7babed9663..12482da2efe 100644 --- a/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStoreTests.cs +++ b/src/Mocha/test/Mocha.Tests/Sagas/InMemorySagaStoreTests.cs @@ -1,7 +1,5 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Sagas; -using Mocha.Transport.InMemory; namespace Mocha.Tests; @@ -112,7 +110,7 @@ public void Registration_Multiple_Calls_Do_Not_Duplicate_Registrations() public async Task StoreSaveAndLoadAsync_Should_RoundTrip_When_SaveAndLoadAsyncAreCalled() { // arrange - var (store, storage, saga) = CreateStore(); + var (store, _, saga) = CreateStore(); var state = new TestSagaState { OrderId = "ORD-100", Amount = 50m }; // act - save without a transaction (goes directly to storage) diff --git a/src/Mocha/test/Mocha.Tests/Sagas/SagaIntegrationTests.cs b/src/Mocha/test/Mocha.Tests/Sagas/SagaIntegrationTests.cs index fdc3389fa2c..552d6401fac 100644 --- a/src/Mocha/test/Mocha.Tests/Sagas/SagaIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Sagas/SagaIntegrationTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Sagas; using Mocha.Transport.InMemory; @@ -7,7 +6,7 @@ namespace Mocha.Tests; public class SagaIntegrationTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task SagaInitialEvent_Should_CreateNewSagaInstance_When_Published() @@ -32,7 +31,7 @@ await bus.PublishAsync( CancellationToken.None); // assert — saga should transition to "AwaitingPayment" - await WaitUntilAsync(() => storage.Load("order-processing-saga", sagaId) is not null, Timeout); + await WaitUntilAsync(() => storage.Load("order-processing-saga", sagaId) is not null, s_timeout); var state = storage.Load("order-processing-saga", sagaId)!; Assert.Equal("AwaitingPayment", state.State); Assert.Equal("ORD-SAGA-1", state.OrderId); @@ -63,7 +62,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-processing-saga", sagaId)?.State == "AwaitingPayment", - Timeout); + s_timeout); var state = storage.Load("order-processing-saga", sagaId)!; Assert.Equal("AwaitingPayment", state.State); @@ -74,7 +73,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-processing-saga", sagaId)?.State == "AwaitingShipment", - Timeout); + s_timeout); state = storage.Load("order-processing-saga", sagaId)!; Assert.Equal("AwaitingShipment", state.State); Assert.Equal("PAY-001", state.PaymentId); @@ -84,7 +83,7 @@ await bus.PublishAsync( new OrderShippedEvent { CorrelationId = sagaId, TrackingNumber = "TRACK-001" }, CancellationToken.None); - await WaitUntilAsync(() => storage.Load("order-processing-saga", sagaId) is null, Timeout); + await WaitUntilAsync(() => storage.Load("order-processing-saga", sagaId) is null, s_timeout); Assert.Null(storage.Load("order-processing-saga", sagaId)); } @@ -123,7 +122,7 @@ await WaitUntilAsync( () => storage.Load("order-processing-saga", id1)?.State == "AwaitingPayment" && storage.Load("order-processing-saga", id2)?.State == "AwaitingPayment", - Timeout); + s_timeout); // act - advance only saga 1 await bus.PublishAsync( @@ -132,7 +131,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-processing-saga", id1)?.State == "AwaitingShipment", - Timeout); + s_timeout); // assert - saga 2 should still be in AwaitingPayment var state2 = storage.Load("order-processing-saga", id2)!; @@ -166,7 +165,7 @@ await bus.PublishAsync( CancellationToken.None); // assert - the handler should still receive the event - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); } private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) diff --git a/src/Mocha/test/Mocha.Tests/Sagas/SagaMessageBusIntegrationTests.cs b/src/Mocha/test/Mocha.Tests/Sagas/SagaMessageBusIntegrationTests.cs index 8750e58b1f0..41475ec5751 100644 --- a/src/Mocha/test/Mocha.Tests/Sagas/SagaMessageBusIntegrationTests.cs +++ b/src/Mocha/test/Mocha.Tests/Sagas/SagaMessageBusIntegrationTests.cs @@ -1,6 +1,4 @@ -using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Sagas; using Mocha.Transport.InMemory; @@ -8,7 +6,7 @@ namespace Mocha.Tests.Sagas; public class SagaMessageBusIntegrationTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); // ────────────────────────────────────────────────────────────────────── // Test 1: Custom state data persisted across multi-step transitions @@ -38,7 +36,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-workflow-saga", sagaId)?.State == "PaymentPending", - Timeout); + s_timeout); // assert step 1 custom data var state = storage.Load("order-workflow-saga", sagaId)!; @@ -52,7 +50,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-workflow-saga", sagaId)?.State == "ShipmentPending", - Timeout); + s_timeout); // assert step 2 custom data state = storage.Load("order-workflow-saga", sagaId)!; @@ -65,7 +63,7 @@ await bus.PublishAsync( new OrderShipped { CorrelationId = sagaId, TrackingNumber = "TRACK-300" }, CancellationToken.None); - await WaitUntilAsync(() => storage.Load("order-workflow-saga", sagaId) is null, Timeout); + await WaitUntilAsync(() => storage.Load("order-workflow-saga", sagaId) is null, s_timeout); Assert.Null(storage.Load("order-workflow-saga", sagaId)); } @@ -102,7 +100,7 @@ await bus.PublishAsync( CancellationToken.None); // assert - downstream handler received the notification - Assert.True(await recorder.WaitAsync(Timeout), "OrderNotification was not received by downstream handler"); + Assert.True(await recorder.WaitAsync(s_timeout), "OrderNotification was not received by downstream handler"); var notification = recorder.Messages.OfType().Single(); Assert.Equal("ORD-HDR", notification.OrderId); @@ -141,7 +139,7 @@ await bus.PublishAsync( CancellationToken.None); // assert - command handler received the command - Assert.True(await recorder.WaitAsync(Timeout), "ProcessPaymentCommand was not received by handler"); + Assert.True(await recorder.WaitAsync(s_timeout), "ProcessPaymentCommand was not received by handler"); var command = recorder.Messages.OfType().Single(); Assert.Equal("ORD-SEND", command.OrderId); @@ -176,7 +174,7 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("order-workflow-saga", sagaId) is not null, - Timeout); + s_timeout); // assert - metadata keys exist in state var state = storage.Load("order-workflow-saga", sagaId)!; @@ -218,7 +216,7 @@ await bus.PublishAsync( CancellationToken.None); // assert - lifecycle-published event was received - Assert.True(await recorder.WaitAsync(Timeout), "OnEntry-published OrderNotification was not received"); + Assert.True(await recorder.WaitAsync(s_timeout), "OnEntry-published OrderNotification was not received"); var notification = recorder.Messages.OfType().Single(); Assert.Equal("ORD-LIFECYCLE", notification.OrderId); @@ -253,13 +251,13 @@ await bus.PublishAsync( await WaitUntilAsync( () => storage.Load("cancellable-saga", sagaId)?.State == "Active", - Timeout); + s_timeout); // act - step 2: cancel from Active state via DuringAny await bus.PublishAsync(new CancelOrder { CorrelationId = sagaId }, CancellationToken.None); // assert - saga reaches final state and is deleted - await WaitUntilAsync(() => storage.Load("cancellable-saga", sagaId) is null, Timeout); + await WaitUntilAsync(() => storage.Load("cancellable-saga", sagaId) is null, s_timeout); Assert.Null(storage.Load("cancellable-saga", sagaId)); } @@ -302,7 +300,7 @@ await WaitUntilAsync( sagaIds.All(id => storage.Load("order-workflow-saga", id)?.State == "PaymentPending" ), - Timeout); + s_timeout); // assert each instance has correct, isolated data for (var i = 0; i < instanceCount; i++) @@ -326,7 +324,7 @@ await WaitUntilAsync( sagaIds.All(id => storage.Load("order-workflow-saga", id)?.State == "ShipmentPending" ), - Timeout); + s_timeout); // assert each instance preserved its own data after concurrent step for (var i = 0; i < instanceCount; i++) @@ -499,7 +497,7 @@ protected override void Configure(ISagaDescriptor descriptor OrderId = e.OrderId, Amount = e.Amount }) - .Publish( + .Publish( (_, s) => new OrderNotification { OrderId = s.OrderId, Reason = "OrderSubmitted" }) .TransitionTo("Active"); @@ -524,7 +522,7 @@ protected override void Configure(ISagaDescriptor descriptor OrderId = e.OrderId, Amount = e.Amount }) - .Send( + .Send( (_, s) => new ProcessPaymentCommand { OrderId = s.OrderId, Amount = s.Amount }) .TransitionTo("AwaitingPayment"); @@ -553,7 +551,7 @@ protected override void Configure(ISagaDescriptor descriptor descriptor .During("Active") .OnEntry() - .Publish( + .Publish( (_, s) => new OrderNotification { OrderId = s.OrderId, Reason = "EnteredActive" }, null); diff --git a/src/Mocha/test/Mocha.Tests/Sagas/SagaStateBaseTests.cs b/src/Mocha/test/Mocha.Tests/Sagas/SagaStateBaseTests.cs index f8051ed18b6..9ada94f3e25 100644 --- a/src/Mocha/test/Mocha.Tests/Sagas/SagaStateBaseTests.cs +++ b/src/Mocha/test/Mocha.Tests/Sagas/SagaStateBaseTests.cs @@ -1,4 +1,3 @@ -using Mocha; using Mocha.Sagas; namespace Mocha.Tests; diff --git a/src/Mocha/test/Mocha.Tests/Telemetry/OpenTelemetryTests.cs b/src/Mocha/test/Mocha.Tests/Telemetry/OpenTelemetryTests.cs index 1b695669b07..19f8f35e038 100644 --- a/src/Mocha/test/Mocha.Tests/Telemetry/OpenTelemetryTests.cs +++ b/src/Mocha/test/Mocha.Tests/Telemetry/OpenTelemetryTests.cs @@ -2,7 +2,6 @@ using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory; namespace Mocha.Tests; @@ -29,7 +28,7 @@ public async Task Publish_Should_CreateActivity_When_EventPublished() // act await bus.PublishAsync(new TracedEvent { Data = "traced" }, CancellationToken.None); - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); // Task.Delay: ActivityListener callbacks fire asynchronously; brief wait lets all callbacks complete await Task.Delay(100, default); @@ -85,7 +84,7 @@ public async Task Activities_Should_HaveCorrectSourceName_When_Published() // act await bus.PublishAsync(new TracedEvent { Data = "source-check" }, CancellationToken.None); - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); // Task.Delay: ActivityListener callbacks fire asynchronously; brief wait lets all callbacks complete await Task.Delay(100, default); @@ -117,7 +116,7 @@ public async Task MultiplePublishes_Should_CreateMultipleActivities_When_Publish { await bus.PublishAsync(new TracedEvent { Data = $"batch-{i}" }, CancellationToken.None); } - Assert.True(await recorder.WaitAsync(Timeout, expectedCount: 3)); + Assert.True(await recorder.WaitAsync(s_timeout, expectedCount: 3)); // Task.Delay: ActivityListener callbacks fire asynchronously; brief wait lets all callbacks complete await Task.Delay(100, default); @@ -144,7 +143,7 @@ public async Task MessageBus_Should_ProcessMessages_When_NoListenerRegistered() await bus.PublishAsync(new TracedEvent { Data = "no-trace" }, CancellationToken.None); // assert - message still delivered - Assert.True(await recorder.WaitAsync(Timeout)); + Assert.True(await recorder.WaitAsync(s_timeout)); Assert.Single(recorder.Messages); } @@ -816,7 +815,7 @@ public void RecordConsumeMessage_With_Null_Subscription_Does_Not_Throw() Assert.NotEmpty(measurements); } - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); private static async Task CreateBusAsync(Action configure) { diff --git a/src/Mocha/test/Mocha.Tests/Telemetry/SemanticConventionsActivityTests.cs b/src/Mocha/test/Mocha.Tests/Telemetry/SemanticConventionsActivityTests.cs index 5a376502a95..7605e56c0b6 100644 --- a/src/Mocha/test/Mocha.Tests/Telemetry/SemanticConventionsActivityTests.cs +++ b/src/Mocha/test/Mocha.Tests/Telemetry/SemanticConventionsActivityTests.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using Mocha; namespace Mocha.Tests; diff --git a/src/Mocha/test/Mocha.Tests/Threading/ChannelProcessorTests.cs b/src/Mocha/test/Mocha.Tests/Threading/ChannelProcessorTests.cs index f3eb6819f0b..c2eccd5a389 100644 --- a/src/Mocha/test/Mocha.Tests/Threading/ChannelProcessorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Threading/ChannelProcessorTests.cs @@ -5,7 +5,7 @@ namespace Mocha.Tests.Threading; public sealed class ChannelProcessorTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Handler_Should_ReceiveAllItems_When_ItemsWrittenToChannel() @@ -29,7 +29,7 @@ public async Task Handler_Should_ReceiveAllItems_When_ItemsWrittenToChannel() channel.Writer.TryWrite(3); // assert - await received.WaitAsync(Timeout, expectedCount: 3); + await received.WaitAsync(s_timeout, expectedCount: 3); Assert.Equal([1, 2, 3], received.Items.OrderBy(x => x)); } @@ -59,7 +59,7 @@ public async Task Handler_Should_ProcessConcurrently_When_ConcurrencyGreaterThan channel.Writer.TryWrite(2); // assert — if both workers entered, the barrier completes within timeout - var completed = await Task.WhenAny(barrier.Task, Task.Delay(Timeout)); + var completed = await Task.WhenAny(barrier.Task, Task.Delay(s_timeout)); Assert.Same(barrier.Task, completed); } @@ -80,7 +80,7 @@ public async Task DisposeAsync_Should_StopWorkers_When_Called() concurrency: 1); channel.Writer.TryWrite(1); - await received.WaitAsync(Timeout, expectedCount: 1); + await received.WaitAsync(s_timeout, expectedCount: 1); // act channel.Writer.Complete(); @@ -121,7 +121,7 @@ public async Task Handler_Should_ContinueProcessing_When_HandlerThrows() channel.Writer.TryWrite(2); // assert — item 2 is eventually processed after ContinuousTask restarts the loop - await received.WaitAsync(Timeout, expectedCount: 1); + await received.WaitAsync(s_timeout, expectedCount: 1); Assert.Contains(2, received.Items); } @@ -138,7 +138,7 @@ public async Task Handler_Should_ReceiveCancelledToken_When_ProcessorIsDisposed( { try { - await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct); + await Task.Delay(Timeout.InfiniteTimeSpan, ct); } catch (OperationCanceledException) { @@ -153,7 +153,7 @@ public async Task Handler_Should_ReceiveCancelledToken_When_ProcessorIsDisposed( await processor.DisposeAsync(); // assert — the handler's cancellation token was triggered - var completed = await Task.WhenAny(tokenCancelled.Task, Task.Delay(Timeout)); + var completed = await Task.WhenAny(tokenCancelled.Task, Task.Delay(s_timeout)); Assert.Same(tokenCancelled.Task, completed); } @@ -174,7 +174,7 @@ public async Task Handler_Should_ReceiveItems_When_SourceIsCustomAsyncEnumerable concurrency: 1); // assert - await received.WaitAsync(Timeout, expectedCount: 3); + await received.WaitAsync(s_timeout, expectedCount: 3); Assert.Equal([10, 20, 30], received.Items.OrderBy(x => x)); } @@ -190,7 +190,7 @@ private static async IAsyncEnumerable ToAsyncEnumerable( } // Block until cancelled so ContinuousTask doesn't spin-restart - await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct); + await Task.Delay(Timeout.InfiniteTimeSpan, ct); } /// diff --git a/src/Mocha/test/Mocha.Tests/Transport/MessageEnvelopeWriterTests.cs b/src/Mocha/test/Mocha.Tests/Transport/MessageEnvelopeWriterTests.cs index eadb05c6c9e..2a8ebf82406 100644 --- a/src/Mocha/test/Mocha.Tests/Transport/MessageEnvelopeWriterTests.cs +++ b/src/Mocha/test/Mocha.Tests/Transport/MessageEnvelopeWriterTests.cs @@ -28,7 +28,7 @@ public void WriteMessage_Should_ProduceValidJson_When_AllFieldsPopulated() DeliverBy = new DateTimeOffset(2026, 6, 1, 23, 59, 59, TimeSpan.Zero), DeliveryCount = 1, Headers = new Headers(), - Body = Encoding.UTF8.GetBytes("""{"orderId":"1"}""") + Body = """{"orderId":"1"}"""u8.ToArray() }; envelope.Headers!.Set("x-trace", "abc123"); @@ -442,7 +442,7 @@ public void Roundtrip_Should_PreserveData_When_WritingAndReadingFullEnvelope() DeliveryCount = 3, EnclosedMessageTypes = ImmutableArray.Create("urn:message:TestEvent", "urn:message:IEvent"), Headers = new Headers(), - Body = Encoding.UTF8.GetBytes("""{"orderId":"1"}""") + Body = """{"orderId":"1"}"""u8.ToArray() }; original.Headers!.Set("x-trace", "abc123"); diff --git a/src/Mocha/test/Mocha.Tests/Utils/StringExtensionsTests.cs b/src/Mocha/test/Mocha.Tests/Utils/StringExtensionsTests.cs index ae945ce058d..cdf2f5021cb 100644 --- a/src/Mocha/test/Mocha.Tests/Utils/StringExtensionsTests.cs +++ b/src/Mocha/test/Mocha.Tests/Utils/StringExtensionsTests.cs @@ -1,5 +1,3 @@ -using Mocha; - namespace Mocha.Tests; public class StringExtensionsTests diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/BatchingTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/BatchingTests.cs index b0270962909..e7104103658 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/BatchingTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/BatchingTests.cs @@ -5,7 +5,7 @@ namespace Mocha.Transport.InMemory.Tests.Behaviors; public class BatchingTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Handler_Should_ReceiveBatch_When_SingleMessageSizeTrigger() @@ -25,7 +25,7 @@ public async Task Handler_Should_ReceiveBatch_When_SingleMessageSizeTrigger() await bus.PublishAsync(new OrderCreated { OrderId = "1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked within timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Single(batch); @@ -55,7 +55,7 @@ public async Task Handler_Should_ReceiveBatch_When_TimeoutExpires() await bus.PublishAsync(new OrderCreated { OrderId = "timeout-1" }, CancellationToken.None); // assert — batch should arrive via timeout with 1 message - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked via timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked via timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Equal(BatchCompletionMode.Time, batch.CompletionMode); @@ -87,7 +87,7 @@ public async Task Handler_Should_ReceiveMultiMessageBatch_When_ConcurrentDeliver } // assert — single batch containing all 5 messages - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked within timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Equal(messageCount, batch.Count); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyLimiterTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyLimiterTests.cs index ea358077a34..1cef7f4aa27 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyLimiterTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyLimiterTests.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class ConcurrencyLimiterTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Handler_Should_LimitConcurrency_When_ConcurrencyLimiterConfigured() @@ -34,7 +33,7 @@ public async Task Handler_Should_LimitConcurrency_When_ConcurrencyLimiterConfigu // assert — wait for all messages and check peak concurrency Assert.True( - await tracker.WaitAsync(Timeout, messageCount), + await tracker.WaitAsync(s_timeout, messageCount), $"Handler did not process all {messageCount} messages"); Assert.Equal(1, tracker.PeakConcurrency); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyTests.cs index 11d61d63752..280384a858d 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ConcurrencyTests.cs @@ -5,7 +5,7 @@ namespace Mocha.Transport.InMemory.Tests.Behaviors; public class ConcurrencyTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Handler_Should_LimitConcurrency_When_MaxConcurrencySetToOne() @@ -35,7 +35,7 @@ public async Task Handler_Should_LimitConcurrency_When_MaxConcurrencySetToOne() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not process all {messageCount} messages within timeout"); Assert.Equal(1, tracker.PeakConcurrency); @@ -69,7 +69,7 @@ public async Task Handler_Should_AllowParallelism_When_MaxConcurrencyGreaterThan // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not process all {messageCount} messages within timeout"); Assert.True(tracker.PeakConcurrency > 1, $"Expected parallelism > 1, but peak was {tracker.PeakConcurrency}"); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CorrelationTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CorrelationTests.cs index 1ed4b9fba2d..7e49a93e70a 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CorrelationTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CorrelationTests.cs @@ -1,13 +1,12 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class CorrelationTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Publish_Should_AutoGenerateIds_When_NoIdsSet() @@ -28,7 +27,7 @@ public async Task Publish_Should_AutoGenerateIds_When_NoIdsSet() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, default); // assert - Assert.True(await capture.WaitAsync(Timeout)); + Assert.True(await capture.WaitAsync(s_timeout)); var ctx = Assert.Single(capture.Contexts); Assert.NotNull(ctx.MessageId); @@ -56,10 +55,10 @@ public async Task Publish_Should_AssignUniqueIds_When_MultipleSeparatePublishes( // act — two independent publishes await bus.PublishAsync(new OrderCreated { OrderId = "ORD-A" }, default); - Assert.True(await capture.WaitAsync(Timeout)); + Assert.True(await capture.WaitAsync(s_timeout)); await bus.PublishAsync(new OrderCreated { OrderId = "ORD-B" }, default); - Assert.True(await capture.WaitAsync(Timeout)); + Assert.True(await capture.WaitAsync(s_timeout)); // assert — each publish gets its own MessageId and ConversationId Assert.Equal(2, capture.Contexts.Count); @@ -88,7 +87,7 @@ public async Task Consumer_Should_SeeAllCorrelationIds_When_MessageReceived() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-CTX" }, default); // assert - Assert.True(await capture.WaitAsync(Timeout)); + Assert.True(await capture.WaitAsync(s_timeout)); var ctx = Assert.Single(capture.Contexts); Assert.NotNull(ctx.ConversationId); @@ -116,7 +115,7 @@ public async Task Publish_Should_HaveDistinctMessageIdButSharedCorrelationScope_ await bus.PublishAsync(new OrderCreated { OrderId = "ORD-FAN" }, default); // assert — both consumers received the event - Assert.True(await capture.WaitAsync(Timeout, 2)); + Assert.True(await capture.WaitAsync(s_timeout, 2)); Assert.Equal(2, capture.Contexts.Count); var all = capture.Contexts.ToArray(); @@ -152,7 +151,7 @@ public async Task Chain_Should_PropagateConversationId_When_HandlerPublishesNewM await bus.PublishAsync(new OrderCreated { OrderId = "ORD-CHAIN" }, default); // assert — wait for both captures (OrderCreated + ProcessPayment) - Assert.True(await capture.WaitAsync(Timeout, 2), "Both handlers should fire"); + Assert.True(await capture.WaitAsync(s_timeout, 2), "Both handlers should fire"); Assert.Equal(2, capture.Contexts.Count); var hop1 = capture.Contexts.Single(c => c.Label == "OrderCreatedForwarder"); @@ -198,7 +197,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CustomHeaderTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CustomHeaderTests.cs index 4908cb24e69..c831f07ab68 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CustomHeaderTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/CustomHeaderTests.cs @@ -1,13 +1,12 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class CustomHeaderTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task PublishAsync_Should_PropagateHeaders_When_CustomHeadersSet() @@ -37,7 +36,7 @@ await bus.PublishAsync( CancellationToken.None); // assert — consumer wiretap receives headers through the pipeline - Assert.True(await capture.WaitAsync(Timeout), "Consumer did not receive the event within timeout"); + Assert.True(await capture.WaitAsync(s_timeout), "Consumer did not receive the event within timeout"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.TryGetValue("x-tenant", out var tenant), "Custom header 'x-tenant' not found"); Assert.Equal("acme", tenant); @@ -81,7 +80,7 @@ await bus.SendAsync( CancellationToken.None); // assert — error queue consumer preserves custom headers alongside fault headers - Assert.True(await capture.WaitAsync(Timeout), "Error consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error consumer did not receive the faulted message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True( headers.TryGetValue("x-tenant", out var tenant), @@ -113,7 +112,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ErrorQueueTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ErrorQueueTests.cs index d6e59896f89..f58e8a5098f 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ErrorQueueTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/ErrorQueueTests.cs @@ -1,13 +1,12 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class ErrorQueueTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task PublishAsync_Should_RouteToErrorQueue_When_HandlerThrows() @@ -40,7 +39,7 @@ public async Task PublishAsync_Should_RouteToErrorQueue_When_HandlerThrows() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-FAULT" }, CancellationToken.None); // assert — faulted message lands in error queue with fault headers - Assert.True(await capture.WaitAsync(Timeout), "Error consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error consumer did not receive the faulted message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.TryGetValue("fault-exception-type", out var exType)); Assert.Contains("InvalidOperationException", (string?)exType); @@ -83,7 +82,7 @@ public async Task SendAsync_Should_RouteToErrorQueue_When_HandlerThrows() await bus.SendAsync(new ProcessPayment { OrderId = "ORD-FAULT", Amount = 10.00m }, CancellationToken.None); // assert — faulted message lands in error queue - Assert.True(await capture.WaitAsync(Timeout), "Error consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error consumer did not receive the faulted message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.TryGetValue("fault-exception-type", out var exType)); Assert.Contains("InvalidOperationException", (string?)exType); @@ -120,7 +119,7 @@ public async Task ErrorQueue_Should_PreserveOriginalBody_When_HandlerFaults() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-PRESERVE" }, CancellationToken.None); // assert — error queue consumer receives the original message - Assert.True(await capture.WaitAsync(Timeout), "Error consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error consumer did not receive the faulted message"); var msg = Assert.Single(capture.Messages); Assert.Equal("ORD-PRESERVE", msg.OrderId); } @@ -159,7 +158,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/FaultHandlingTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/FaultHandlingTests.cs index dacdefca8e3..0e5bf4b510b 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/FaultHandlingTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/FaultHandlingTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Events; using Mocha.Transport.InMemory.Tests.Helpers; @@ -7,7 +6,7 @@ namespace Mocha.Transport.InMemory.Tests.Behaviors; public class FaultHandlingTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task PublishAsync_Should_NotAffectOtherHandlers_When_OneHandlerThrows() @@ -38,7 +37,7 @@ public async Task PublishAsync_Should_NotAffectOtherHandlers_When_OneHandlerThro // assert - the second handler still works Assert.True( - await normalRecorder.WaitAsync(Timeout), + await normalRecorder.WaitAsync(s_timeout), "Normal handler did not receive event after a previous handler threw"); } diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/PublishSubscribeTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/PublishSubscribeTests.cs index 48c7c41e12a..30203ad60c8 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/PublishSubscribeTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/PublishSubscribeTests.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class PublishSubscribeTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task PublishAsync_Should_DeliverToHandler_When_SingleHandlerRegistered() @@ -27,7 +26,7 @@ public async Task PublishAsync_Should_DeliverToHandler_When_SingleHandlerRegiste await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the event within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the event within timeout"); var message = Assert.Single(recorder.Messages); var order = Assert.IsType(message); @@ -56,8 +55,8 @@ public async Task PublishAsync_Should_FanOutToAllHandlers_When_MultipleHandlersR await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder1.WaitAsync(Timeout), "First handler did not receive the event"); - Assert.True(await recorder2.WaitAsync(Timeout), "Second handler did not receive the event"); + Assert.True(await recorder1.WaitAsync(s_timeout), "First handler did not receive the event"); + Assert.True(await recorder2.WaitAsync(s_timeout), "Second handler did not receive the event"); Assert.Single(recorder1.Messages); Assert.Single(recorder2.Messages); @@ -101,8 +100,8 @@ public async Task PublishAsync_Should_RouteToCorrectHandler_When_DifferentEventT await bus.PublishAsync(new ItemShipped { TrackingNumber = "TRK-1" }, CancellationToken.None); // assert - Assert.True(await orderRecorder.WaitAsync(Timeout), "OrderCreated handler did not receive the event"); - Assert.True(await shipmentRecorder.WaitAsync(Timeout), "ItemShipped handler did not receive the event"); + Assert.True(await orderRecorder.WaitAsync(s_timeout), "OrderCreated handler did not receive the event"); + Assert.True(await shipmentRecorder.WaitAsync(s_timeout), "ItemShipped handler did not receive the event"); Assert.IsType(Assert.Single(orderRecorder.Messages)); Assert.IsType(Assert.Single(shipmentRecorder.Messages)); @@ -130,7 +129,7 @@ public async Task PublishAsync_Should_DeliverAll_When_MultipleEventsSequential() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: 3), + await recorder.WaitAsync(s_timeout, expectedCount: 3), "Handler did not receive all 3 events within timeout"); Assert.Equal(3, recorder.Messages.Count); @@ -164,7 +163,7 @@ public async Task PublishAsync_Should_DeliverAll_When_RapidFire() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not receive all {messageCount} events within timeout"); Assert.Equal(messageCount, recorder.Messages.Count); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/RequestReplyTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/RequestReplyTests.cs index 345434a2417..9e6618930f8 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/RequestReplyTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/RequestReplyTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Events; using Mocha.Transport.InMemory.Tests.Helpers; @@ -7,7 +6,7 @@ namespace Mocha.Transport.InMemory.Tests.Behaviors; public class RequestReplyTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task RequestAsync_Should_ReturnTypedResponse_When_HandlerRegistered() @@ -50,7 +49,7 @@ public async Task RequestAsync_Should_ThrowRemoteError_When_HandlerReturnsNull() // act & assert — null response triggers an internal exception caught by the fault // middleware, which sends NotAcknowledgedEvent back as RemoteErrorException - using var cts = new CancellationTokenSource(Timeout); + using var cts = new CancellationTokenSource(s_timeout); await Assert.ThrowsAsync(async () => await bus.RequestAsync(new GetOrderStatus { OrderId = "ORD-1" }, cts.Token) ); @@ -106,7 +105,7 @@ public async Task RequestAsync_Should_Complete_When_VoidRequestAcknowledged() await bus.RequestAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 50.00m }, CancellationToken.None); // assert - if we got here without exception, the acknowledgement round-trip succeeded - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the request within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the request within timeout"); } [Fact] diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/SendTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/SendTests.cs index 9e70c81c529..f1c8057575e 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/SendTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/SendTests.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class SendTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task SendAsync_Should_DeliverToHandler_When_RequestHandlerRegistered() @@ -27,7 +26,7 @@ public async Task SendAsync_Should_DeliverToHandler_When_RequestHandlerRegistere await bus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 99.99m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the request"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the request"); var message = Assert.Single(recorder.Messages); var payment = Assert.IsType(message); @@ -54,7 +53,7 @@ public async Task SendAsync_Should_DeliverAsynchronously_When_FireAndForget() await bus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 99.99m }, CancellationToken.None); // assert - handler receives it asynchronously - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the request"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the request"); var msg = Assert.Single(recorder.Messages); var payment = Assert.IsType(msg); @@ -83,7 +82,7 @@ public async Task SendAsync_Should_DeliverToCorrectHandler_When_MultipleQueuesEx await bus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 50.00m }, CancellationToken.None); // assert - payment handler received the message - Assert.True(await paymentRecorder.WaitAsync(Timeout), "Payment handler did not receive the send message"); + Assert.True(await paymentRecorder.WaitAsync(s_timeout), "Payment handler did not receive the send message"); var msg = Assert.Single(paymentRecorder.Messages); Assert.IsType(msg); @@ -119,8 +118,8 @@ public async Task SendAsync_Should_DeliverToEachHandler_When_SendingToDifferentQ await bus.SendAsync(new ProcessRefund { OrderId = "ORD-2", Amount = 25.00m }, CancellationToken.None); // assert - each handler received exactly its own message - Assert.True(await paymentRecorder.WaitAsync(Timeout), "Payment handler did not receive the message"); - Assert.True(await refundRecorder.WaitAsync(Timeout), "Refund handler did not receive the message"); + Assert.True(await paymentRecorder.WaitAsync(s_timeout), "Payment handler did not receive the message"); + Assert.True(await refundRecorder.WaitAsync(s_timeout), "Refund handler did not receive the message"); var payment = Assert.IsType(Assert.Single(paymentRecorder.Messages)); Assert.Equal("ORD-1", payment.OrderId); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/VolumeTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/VolumeTests.cs index 96d0026c8c0..f00ee68dbbb 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/VolumeTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Behaviors/VolumeTests.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests.Behaviors; public class VolumeTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task PublishAsync_Should_DeliverAll_When_1000EventsPublished() @@ -33,7 +32,7 @@ public async Task PublishAsync_Should_DeliverAll_When_1000EventsPublished() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: eventCount), + await recorder.WaitAsync(s_timeout, expectedCount: eventCount), $"Handler did not receive all {eventCount} events within timeout"); Assert.Equal(eventCount, recorder.Messages.Count); @@ -76,7 +75,7 @@ await bus.PublishAsync( // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: totalMessages), + await recorder.WaitAsync(s_timeout, expectedCount: totalMessages), $"Handler did not receive all {totalMessages} messages within timeout"); Assert.Equal(totalMessages, recorder.Messages.Count); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Configuration/HandlerResolutionTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Configuration/HandlerResolutionTests.cs index d0c31d95c05..842dbbb580c 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Configuration/HandlerResolutionTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Configuration/HandlerResolutionTests.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests; public class HandlerResolutionTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task AddEventHandler_Should_ResolveDependency_When_HandlerHasDIConstructor() @@ -29,7 +28,7 @@ public async Task AddEventHandler_Should_ResolveDependency_When_HandlerHasDICons await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the event"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the event"); Assert.Equal(1, counter.Count); } @@ -51,7 +50,7 @@ public async Task AddHandler_Should_CreateSubscribeConsumer_When_EventHandlerReg // assert Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), "Handler was not called - AddHandler did not create SubscribeConsumer"); var message = Assert.IsType(Assert.Single(recorder.Messages)); @@ -75,7 +74,7 @@ public async Task AddHandler_Should_CreateSendConsumer_When_RequestHandlerRegist // assert Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), "Handler was not called - AddHandler did not create SendConsumer"); } diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Helpers/TopologySnapshotHelper.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Helpers/TopologySnapshotHelper.cs index eeb7ee4fc99..9e9e278c68b 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Helpers/TopologySnapshotHelper.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Helpers/TopologySnapshotHelper.cs @@ -6,7 +6,7 @@ namespace Mocha.Transport.InMemory.Tests.Helpers; public static partial class TopologySnapshotHelper { - private static readonly JsonSerializerOptions JsonOptions = new() + private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -50,7 +50,7 @@ public static string CreateSnapshot(InMemoryMessagingTopology topology) .ToList(); var snapshot = new TopologySnapshot(topics, queues, bindings); - return JsonSerializer.Serialize(snapshot, JsonOptions); + return JsonSerializer.Serialize(snapshot, s_jsonOptions); } public static string CreateDescribeSnapshot(TransportDescription description) @@ -91,7 +91,7 @@ public static string CreateDescribeSnapshot(TransportDescription description) receiveEndpoints, dispatchEndpoints); - return JsonSerializer.Serialize(snapshot, JsonOptions); + return JsonSerializer.Serialize(snapshot, s_jsonOptions); } private static bool IsReplyName(string name) diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryBuilderApiTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryBuilderApiTests.cs index 9591770b837..b7a56cdb40c 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryBuilderApiTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryBuilderApiTests.cs @@ -6,7 +6,7 @@ namespace Mocha.Transport.InMemory.Tests; public class InMemoryBuilderApiTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task DeclareBinding_Should_DeliverMessage_When_TopicBoundToQueue() @@ -36,7 +36,7 @@ await bus.SendAsync( // assert — queue receives the message via the binding Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), "Handler should receive message routed via ToQueue on dispatch endpoint"); } @@ -80,9 +80,9 @@ public async Task DeclareBinding_Should_FanOut_When_MultipleQueuesBoundToTopic() await bus.PublishAsync(new OrderCreated { OrderId = "fan-msg" }, CancellationToken.None); // assert — all 3 handlers receive the message - Assert.True(await recorder1.WaitAsync(Timeout), "First fan-out handler did not receive the event"); - Assert.True(await recorder2.WaitAsync(Timeout), "Second fan-out handler did not receive the event"); - Assert.True(await recorder3.WaitAsync(Timeout), "Third fan-out handler did not receive the event"); + Assert.True(await recorder1.WaitAsync(s_timeout), "First fan-out handler did not receive the event"); + Assert.True(await recorder2.WaitAsync(s_timeout), "Second fan-out handler did not receive the event"); + Assert.True(await recorder3.WaitAsync(s_timeout), "Third fan-out handler did not receive the event"); var msg1 = Assert.IsType(Assert.Single(recorder1.Messages)); var msg2 = Assert.IsType(Assert.Single(recorder2.Messages)); @@ -122,7 +122,7 @@ public async Task DeclareBinding_Should_Chain_When_TopicBoundToTopicBoundToQueue await bus.PublishAsync(new OrderCreated { OrderId = "chain-msg" }, CancellationToken.None); // assert — message traverses topic chain and lands at the handler - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the chained event"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the chained event"); var msg = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal("chain-msg", msg.OrderId); @@ -150,10 +150,10 @@ public async Task DeclareBinding_Should_CoexistWithConvention_When_HandlerAlsoRe await bus.PublishAsync(new OrderCreated { OrderId = "coexist-test" }, CancellationToken.None); // assert — convention handler receives the message - Assert.True(await recorder.WaitAsync(Timeout), "Convention handler should receive the event"); + Assert.True(await recorder.WaitAsync(s_timeout), "Convention handler should receive the event"); // assert — consumer also receives the message via fan-out - Assert.True(await extraRecorder.WaitAsync(Timeout), "Consumer should receive the event via fan-out"); + Assert.True(await extraRecorder.WaitAsync(s_timeout), "Consumer should receive the event via fan-out"); } [Fact] @@ -177,7 +177,7 @@ public async Task ToInMemoryQueue_Should_RouteMessage_When_SpecifiedOnDispatchEn // assert Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), "Handler should receive message routed via ToQueue on dispatch endpoint"); var msg = Assert.IsType(Assert.Single(recorder.Messages)); @@ -203,7 +203,7 @@ public async Task ToInMemoryTopic_Should_RouteMessage_When_SpecifiedOnDispatchEn await bus.PublishAsync(new OrderCreated { OrderId = "ORD-TOPIC" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler should receive message routed via topic"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler should receive message routed via topic"); var msg = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal("ORD-TOPIC", msg.OrderId); @@ -231,7 +231,7 @@ public async Task Endpoint_Should_ReceiveMessages_When_ConfiguredWithQueueAndHan await bus.SendAsync(new ProcessPayment { OrderId = "ORD-EP", Amount = 25m }, CancellationToken.None); // assert — handler receives - Assert.True(await recorder.WaitAsync(Timeout), "Handler on configured endpoint should receive message"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler on configured endpoint should receive message"); var msg = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal("ORD-EP", msg.OrderId); diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryReceiveEndpointLifecycleTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryReceiveEndpointLifecycleTests.cs index 2d5f7b39a09..af3dfa532f7 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryReceiveEndpointLifecycleTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryReceiveEndpointLifecycleTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests; @@ -10,7 +9,7 @@ namespace Mocha.Transport.InMemory.Tests; /// public class InMemoryReceiveEndpointLifecycleTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); [Fact] public async Task Runtime_Should_StartAndStopCleanly_When_NoHandlersRegistered() @@ -49,7 +48,7 @@ public async Task PublishAsync_Should_Deliver_When_RuntimeStarted() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the event after start"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the event after start"); } [Fact] @@ -71,7 +70,7 @@ public async Task ReceiveEndpoint_Should_ProcessMessages_When_Started() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Receive endpoint should process messages after start"); + Assert.True(await recorder.WaitAsync(s_timeout), "Receive endpoint should process messages after start"); var msg = Assert.IsType(Assert.Single(recorder.Messages)); Assert.Equal("ORD-1", msg.OrderId); @@ -96,13 +95,13 @@ public async Task ReceiveEndpoint_Should_NotAcceptNewScopes_When_ProviderDispose await bus.PublishAsync(new OrderCreated { OrderId = "ORD-BEFORE" }, CancellationToken.None); } - Assert.True(await recorder.WaitAsync(Timeout), "Message should be delivered before dispose"); + Assert.True(await recorder.WaitAsync(s_timeout), "Message should be delivered before dispose"); // act - dispose the provider (which tears down the DI container) await provider.DisposeAsync(); // assert - creating a new scope should fail after dispose - Assert.Throws(() => provider.CreateScope()); + Assert.Throws(provider.CreateScope); } [Fact] @@ -123,13 +122,13 @@ public async Task ReceiveEndpoint_Should_StopProcessing_When_RuntimeDisposed() await bus.PublishAsync(new OrderCreated { OrderId = "ORD-BEFORE" }, CancellationToken.None); } - Assert.True(await recorder.WaitAsync(Timeout), "Message should be delivered before dispose"); + Assert.True(await recorder.WaitAsync(s_timeout), "Message should be delivered before dispose"); // act - dispose the runtime await provider.DisposeAsync(); // assert - provider is disposed, no new scopes can be created - Assert.Throws(() => provider.CreateScope()); + Assert.Throws(provider.CreateScope); } [Fact] @@ -160,7 +159,7 @@ public async Task ReceiveEndpoint_Should_ContinueProcessing_When_HandlerThrows() // assert - the second message should be delivered despite the first throwing Assert.True( - await recorder.WaitAsync(Timeout), + await recorder.WaitAsync(s_timeout), "Receive endpoint should continue processing after handler exception"); // The recorder should have received at least the successful message @@ -189,7 +188,7 @@ public async Task ReceiveEndpoint_Should_ProcessSubsequentMessages_When_Previous // assert - all 3 messages should be recorded (handler records before throwing) Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: 3), + await recorder.WaitAsync(s_timeout, expectedCount: 3), "Receive endpoint should process all messages even when handler throws each time"); Assert.Equal(3, recorder.Messages.Count); @@ -221,7 +220,7 @@ public async Task ReceiveEndpoint_Should_ProcessMessages_When_RestartedAfterErro } // assert - 5 odd messages should be recorded (handler throws on even calls) - Assert.True(await recorder.WaitAsync(Timeout, expectedCount: 5), "Expected 5 successful messages"); + Assert.True(await recorder.WaitAsync(s_timeout, expectedCount: 5), "Expected 5 successful messages"); Assert.Equal(5, recorder.Messages.Count); // With concurrent consumers, which messages hit even vs odd invocations diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryTransportTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryTransportTests.cs index ce102c4e6f6..4dfb49a1abd 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryTransportTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/InMemoryTransportTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha.Middlewares; using Mocha.Transport.InMemory.Tests.Helpers; namespace Mocha.Transport.InMemory.Tests; @@ -467,7 +466,7 @@ public async Task SendAsync_Should_DeliverToQueue_When_RequestHandlerRegistered( await bus.SendAsync(new ProcessPayment { OrderId = "ORD-T1", Amount = 42.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message sent to queue"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message sent to queue"); var msg = Assert.Single(recorder.Messages); var payment = Assert.IsType(msg); @@ -493,7 +492,7 @@ public async Task PublishAsync_Should_DeliverToSubscriber_When_EventHandlerRegis await bus.PublishAsync(new OrderCreated { OrderId = "ORD-T2" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message published to topic"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message published to topic"); var msg = Assert.Single(recorder.Messages); var order = Assert.IsType(msg); @@ -1001,7 +1000,7 @@ public ValueTask HandleAsync(GetOrderStatus request, Cancel } } - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10); private static ( MessagingRuntime Runtime, diff --git a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Topology/InMemoryMessagingTopologyTests.cs b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Topology/InMemoryMessagingTopologyTests.cs index d9c3c7ac049..5943c0a60fc 100644 --- a/src/Mocha/test/Mocha.Transport.InMemory.Tests/Topology/InMemoryMessagingTopologyTests.cs +++ b/src/Mocha/test/Mocha.Transport.InMemory.Tests/Topology/InMemoryMessagingTopologyTests.cs @@ -294,7 +294,7 @@ public async Task AddTopicAndQueue_Should_NotCorrupt_When_ConcurrentAdds() Assert.Equal(queueNames.Count, queueNames.Distinct().Count()); // Verify all expected names are present - for (int i = 0; i < operationCount; i++) + for (var i = 0; i < operationCount; i++) { Assert.Contains(topology.Topics, t => t.Name == $"topic-{i}"); Assert.Contains(topology.Queues, q => q.Name == $"queue-{i}"); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/BatchingTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/BatchingTests.cs index d21e80176e4..c742711ec59 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/BatchingTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/BatchingTests.cs @@ -6,7 +6,7 @@ namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class BatchingTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(60); private readonly RabbitMQFixture _fixture; public BatchingTests(RabbitMQFixture fixture) @@ -35,7 +35,7 @@ public async Task Handler_Should_ReceiveBatch_When_SingleMessageSizeTrigger() await messageBus.PublishAsync(new OrderCreated { OrderId = "1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked within timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Single(batch); @@ -68,7 +68,7 @@ public async Task Handler_Should_ReceiveBatch_When_TimeoutExpires() await messageBus.PublishAsync(new OrderCreated { OrderId = "timeout-1" }, CancellationToken.None); // assert — batch should arrive via timeout with 1 message - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked via timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked via timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Equal(BatchCompletionMode.Time, batch.CompletionMode); @@ -107,7 +107,7 @@ public async Task Handler_Should_ReceiveMultiMessageBatch_When_ConcurrentDeliver } // assert — single batch containing all 5 messages - Assert.True(await recorder.WaitAsync(Timeout), "Batch handler was not invoked within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Batch handler was not invoked within timeout"); var batch = Assert.IsAssignableFrom>(Assert.Single(recorder.Batches)); Assert.Equal(messageCount, batch.Count); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyLimiterTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyLimiterTests.cs index dac30b410fa..3f6925b157c 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyLimiterTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyLimiterTests.cs @@ -6,7 +6,7 @@ namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class ConcurrencyLimiterTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(60); private readonly RabbitMQFixture _fixture; public ConcurrencyLimiterTests(RabbitMQFixture fixture) @@ -44,7 +44,7 @@ public async Task Handler_Should_LimitConcurrency_When_ConcurrencyLimiterConfigu // assert — wait for all messages and check peak concurrency Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not process all {messageCount} messages within timeout"); Assert.Equal(1, tracker.PeakConcurrency); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyTests.cs index ba9f62297d0..294cb7224c7 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConcurrencyTests.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class ConcurrencyTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(60); private readonly RabbitMQFixture _fixture; public ConcurrencyTests(RabbitMQFixture fixture) @@ -44,7 +43,7 @@ public async Task Handler_Should_LimitConcurrency_When_MaxConcurrencySetToOne() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not process all {messageCount} messages within timeout"); Assert.Equal(1, tracker.PeakConcurrency); @@ -60,7 +59,7 @@ public async Task Handler_Should_AllowParallelism_When_MaxConcurrencyGreaterThan await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -79,7 +78,7 @@ public async Task Handler_Should_AllowParallelism_When_MaxConcurrencyGreaterThan // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not process all {messageCount} messages within timeout"); Assert.True(tracker.PeakConcurrency > 1, $"Expected parallelism > 1, but peak was {tracker.PeakConcurrency}"); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConnectionRecoveryTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConnectionRecoveryTests.cs index 9317875f59a..e04039dd2f5 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConnectionRecoveryTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ConnectionRecoveryTests.cs @@ -1,14 +1,13 @@ using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class ConnectionRecoveryTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); - private static readonly TimeSpan RecoveryTimeout = TimeSpan.FromSeconds(15); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_recoveryTimeout = TimeSpan.FromSeconds(15); private readonly RabbitMQFixture _fixture; public ConnectionRecoveryTests(RabbitMQFixture fixture) @@ -23,7 +22,7 @@ public async Task Consumer_Should_ResumeReceiving_When_ConnectionRecovered() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddEventHandler() @@ -35,7 +34,7 @@ public async Task Consumer_Should_ResumeReceiving_When_ConnectionRecovered() // act - publish message 1, verify received await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, default); - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive message 1"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive message 1"); // drop all connections await _fixture.CloseAllConnectionsAsync("recovery-test"); @@ -54,7 +53,7 @@ public async Task Consumer_Should_HandleMultipleDisconnects_When_ConnectionDropp var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddEventHandler() @@ -66,7 +65,7 @@ public async Task Consumer_Should_HandleMultipleDisconnects_When_ConnectionDropp // act - publish message 1 await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, default); - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive message 1"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive message 1"); // drop connections twice await _fixture.CloseAllConnectionsAsync("recovery-test-1"); @@ -87,7 +86,7 @@ public async Task ChannelPool_Should_RecoverGracefully_When_ConnectionLost() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddRequestHandler() @@ -99,7 +98,7 @@ public async Task ChannelPool_Should_RecoverGracefully_When_ConnectionLost() // send message 1 await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 50.00m }, default); - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive message 1"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive message 1"); // drop connections await _fixture.CloseAllConnectionsAsync("channel-pool-recovery"); @@ -113,7 +112,7 @@ public async Task ChannelPool_Should_RecoverGracefully_When_ConnectionLost() private static async Task WaitForRecoveryAsync(IMessageBus messageBus, MessageRecorder recorder, int expectedCount) { - var deadline = DateTimeOffset.UtcNow.Add(RecoveryTimeout); + var deadline = DateTimeOffset.UtcNow.Add(s_recoveryTimeout); while (DateTimeOffset.UtcNow < deadline) { try @@ -141,7 +140,7 @@ private static async Task WaitForDispatchRecoveryAsync( MessageRecorder recorder, int expectedCount) { - var deadline = DateTimeOffset.UtcNow.Add(RecoveryTimeout); + var deadline = DateTimeOffset.UtcNow.Add(s_recoveryTimeout); while (DateTimeOffset.UtcNow < deadline) { try diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/CustomHeaderTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/CustomHeaderTests.cs index 5a1f04385f1..2918f7a2d8e 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/CustomHeaderTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/CustomHeaderTests.cs @@ -1,14 +1,13 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class CustomHeaderTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public CustomHeaderTests(RabbitMQFixture fixture) @@ -23,7 +22,7 @@ public async Task PublishAsync_Should_PropagateHeaders_When_CustomHeadersSet() var capture = new HeaderCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddConsumer() @@ -43,7 +42,7 @@ await messageBus.PublishAsync( CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Consumer did not receive the published message"); + Assert.True(await capture.WaitAsync(s_timeout), "Consumer did not receive the published message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.TryGetValue("x-tenant", out var tenant), "Custom header 'x-tenant' not found"); @@ -74,7 +73,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/EndpointMiddlewareTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/EndpointMiddlewareTests.cs index 95d37b262cf..c29619c5793 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/EndpointMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/EndpointMiddlewareTests.cs @@ -1,14 +1,13 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class EndpointMiddlewareTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public EndpointMiddlewareTests(RabbitMQFixture fixture) @@ -24,7 +23,7 @@ public async Task UseReceive_Should_InvokeMiddleware_When_MessageReceived() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -52,7 +51,7 @@ public async Task UseReceive_Should_InvokeMiddleware_When_MessageReceived() await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-MW" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("receive-mw", tracker.Invocations); } @@ -64,7 +63,7 @@ public async Task AppendReceive_Should_InvokeMiddleware_When_MessageReceived() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -93,7 +92,7 @@ public async Task AppendReceive_Should_InvokeMiddleware_When_MessageReceived() await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-MW2" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("append-receive-mw", tracker.Invocations); } @@ -105,7 +104,7 @@ public async Task PrependReceive_Should_InvokeMiddleware_When_MessageReceived() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -134,7 +133,7 @@ public async Task PrependReceive_Should_InvokeMiddleware_When_MessageReceived() await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-MW3" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("prepend-receive-mw", tracker.Invocations); } @@ -146,7 +145,7 @@ public async Task UseDispatch_Should_InvokeMiddleware_When_MessageDispatched() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -174,7 +173,7 @@ public async Task UseDispatch_Should_InvokeMiddleware_When_MessageDispatched() await messageBus.PublishAsync(new ProcessPayment { OrderId = "ORD-DM", Amount = 50.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("dispatch-mw", tracker.Invocations); } @@ -186,7 +185,7 @@ public async Task AppendDispatch_Should_InvokeMiddleware_When_MessageDispatched( var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -215,7 +214,7 @@ public async Task AppendDispatch_Should_InvokeMiddleware_When_MessageDispatched( await messageBus.PublishAsync(new ProcessPayment { OrderId = "ORD-DM2", Amount = 25.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("append-dispatch-mw", tracker.Invocations); } @@ -227,7 +226,7 @@ public async Task PrependDispatch_Should_InvokeMiddleware_When_MessageDispatched var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -256,7 +255,7 @@ public async Task PrependDispatch_Should_InvokeMiddleware_When_MessageDispatched await messageBus.PublishAsync(new ProcessPayment { OrderId = "ORD-DM3", Amount = 10.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("prepend-dispatch-mw", tracker.Invocations); } diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ErrorQueueTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ErrorQueueTests.cs index 17b4d460428..6c3f0431229 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ErrorQueueTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ErrorQueueTests.cs @@ -1,14 +1,13 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class ErrorQueueTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public ErrorQueueTests(RabbitMQFixture fixture) @@ -23,7 +22,7 @@ public async Task PublishAsync_Should_RouteToErrorQueue_When_HandlerThrows() var capture = new ErrorCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddEventHandler() @@ -47,7 +46,7 @@ public async Task PublishAsync_Should_RouteToErrorQueue_When_HandlerThrows() await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-FAULT" }, CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Error queue consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error queue consumer did not receive the faulted message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.ContainsKey("fault-exception-type"), "Missing fault-exception-type header"); @@ -63,7 +62,7 @@ public async Task SendAsync_Should_RouteToErrorQueue_When_HandlerThrows() var capture = new ErrorCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddRequestHandler() @@ -91,7 +90,7 @@ await messageBus.SendAsync( CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Error queue consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error queue consumer did not receive the faulted message"); var headers = Assert.Single(capture.CapturedHeaders); Assert.True(headers.ContainsKey("fault-exception-type"), "Missing fault-exception-type header"); @@ -105,7 +104,7 @@ public async Task ErrorQueue_Should_PreserveOriginalBody_When_HandlerFaults() var capture = new ErrorCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddEventHandler() @@ -129,7 +128,7 @@ public async Task ErrorQueue_Should_PreserveOriginalBody_When_HandlerFaults() await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-PRESERVE" }, CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Error queue consumer did not receive the faulted message"); + Assert.True(await capture.WaitAsync(s_timeout), "Error queue consumer did not receive the faulted message"); var message = Assert.Single(capture.Messages); Assert.Equal("ORD-PRESERVE", message.OrderId); @@ -171,7 +170,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ExplicitTopologyTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ExplicitTopologyTests.cs index cb57501754b..88af57d8e12 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ExplicitTopologyTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/ExplicitTopologyTests.cs @@ -1,14 +1,13 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class ExplicitTopologyTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public ExplicitTopologyTests(RabbitMQFixture fixture) @@ -23,7 +22,7 @@ public async Task PublishAsync_Should_RouteToQueue_When_ExplicitTopologyDeclared var capture = new OrderCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddConsumer() @@ -47,7 +46,7 @@ public async Task PublishAsync_Should_RouteToQueue_When_ExplicitTopologyDeclared await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-TOPO" }, CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Consumer on custom-q did not receive the published message"); + Assert.True(await capture.WaitAsync(s_timeout), "Consumer on custom-q did not receive the published message"); var message = Assert.Single(capture.Messages); Assert.Equal("ORD-TOPO", message.OrderId); @@ -60,7 +59,7 @@ public async Task PublishAsync_Should_RouteToQueue_When_ExplicitTopologyDeclared var capture = new OrderCapture(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(capture) .AddMessageBus() .AddConsumer() @@ -84,7 +83,7 @@ public async Task PublishAsync_Should_RouteToQueue_When_ExplicitTopologyDeclared await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-TOPO" }, CancellationToken.None); // assert - Assert.True(await capture.WaitAsync(Timeout), "Consumer on custom-q did not receive the published message"); + Assert.True(await capture.WaitAsync(s_timeout), "Consumer on custom-q did not receive the published message"); var message = Assert.Single(capture.Messages); Assert.Equal("ORD-TOPO", message.OrderId); @@ -106,7 +105,9 @@ public async Task WaitAsync(TimeSpan timeout, int expectedCount = 1) for (var i = 0; i < expectedCount; i++) { if (!await _semaphore.WaitAsync(timeout)) + { return false; + } } return true; } diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/FaultHandlingTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/FaultHandlingTests.cs index dd0740957ce..9e4c542535d 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/FaultHandlingTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/FaultHandlingTests.cs @@ -1,14 +1,13 @@ using Microsoft.Extensions.DependencyInjection; using Mocha.Events; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class FaultHandlingTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public FaultHandlingTests(RabbitMQFixture fixture) @@ -23,7 +22,7 @@ public async Task RequestAsync_Should_ThrowRemoteError_When_HandlerThrows() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddRequestHandler() @@ -49,7 +48,7 @@ public async Task PublishAsync_Should_NotAffectOtherHandlers_When_OneHandlerThro var normalRecorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddKeyedSingleton("throwing", throwingRecorder) .AddKeyedSingleton("shipment", normalRecorder) .AddMessageBus() @@ -72,7 +71,7 @@ public async Task PublishAsync_Should_NotAffectOtherHandlers_When_OneHandlerThro // assert - the second handler still works Assert.True( - await normalRecorder.WaitAsync(Timeout), + await normalRecorder.WaitAsync(s_timeout), "Normal handler did not receive event after a previous handler threw"); } diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/PublishSubscribeTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/PublishSubscribeTests.cs index faa1b9984b5..e7130c93b40 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/PublishSubscribeTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/PublishSubscribeTests.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class PublishSubscribeTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public PublishSubscribeTests(RabbitMQFixture fixture) @@ -22,7 +21,7 @@ public async Task PublishAsync_Should_DeliverToHandler_When_SingleHandlerRegiste var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddEventHandler() @@ -36,7 +35,7 @@ public async Task PublishAsync_Should_DeliverToHandler_When_SingleHandlerRegiste await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the event within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the event within timeout"); var message = Assert.Single(recorder.Messages); var order = Assert.IsType(message); @@ -51,7 +50,7 @@ public async Task PublishAsync_Should_FanOutToAllHandlers_When_MultipleHandlersR var recorder2 = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddKeyedSingleton("r1", recorder1) .AddKeyedSingleton("r2", recorder2) .AddMessageBus() @@ -67,8 +66,8 @@ public async Task PublishAsync_Should_FanOutToAllHandlers_When_MultipleHandlersR await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-1" }, CancellationToken.None); // assert - Assert.True(await recorder1.WaitAsync(Timeout), "First handler did not receive the event"); - Assert.True(await recorder2.WaitAsync(Timeout), "Second handler did not receive the event"); + Assert.True(await recorder1.WaitAsync(s_timeout), "First handler did not receive the event"); + Assert.True(await recorder2.WaitAsync(s_timeout), "Second handler did not receive the event"); Assert.Single(recorder1.Messages); Assert.Single(recorder2.Messages); @@ -81,7 +80,7 @@ public async Task PublishAsync_Should_DeliverAll_When_MultipleEventsSequential() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddEventHandler() @@ -98,7 +97,7 @@ public async Task PublishAsync_Should_DeliverAll_When_MultipleEventsSequential() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: 3), + await recorder.WaitAsync(s_timeout, expectedCount: 3), "Handler did not receive all 3 events within timeout"); Assert.Equal(3, recorder.Messages.Count); @@ -115,7 +114,7 @@ public async Task PublishAsync_Should_DeliverAll_When_RapidFire() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddEventHandler() @@ -134,7 +133,7 @@ public async Task PublishAsync_Should_DeliverAll_When_RapidFire() // assert Assert.True( - await recorder.WaitAsync(Timeout, expectedCount: messageCount), + await recorder.WaitAsync(s_timeout, expectedCount: messageCount), $"Handler did not receive all {messageCount} events within timeout"); Assert.Equal(messageCount, recorder.Messages.Count); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RequestReplyTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RequestReplyTests.cs index fc75ccb939d..c1dffbb46e2 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RequestReplyTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/RequestReplyTests.cs @@ -1,14 +1,12 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha.Events; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class RequestReplyTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public RequestReplyTests(RabbitMQFixture fixture) @@ -22,7 +20,7 @@ public async Task RequestAsync_Should_ReturnTypedResponse_When_HandlerRegistered // arrange await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddMessageBus() .AddRequestHandler() .AddRabbitMQ() @@ -46,7 +44,7 @@ public async Task RequestAsync_Should_CorrelateResponses_When_ConcurrentRequests // arrange await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddMessageBus() .AddRequestHandler() .AddRabbitMQ() @@ -80,7 +78,7 @@ public async Task RequestAsync_Should_Complete_When_VoidRequestAcknowledged() var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddRequestHandler() @@ -96,7 +94,7 @@ await messageBus.RequestAsync( CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the request within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the request within timeout"); } [Fact] @@ -105,7 +103,7 @@ public async Task RequestAsync_Should_ReturnCorrectResponse_When_MultipleRequest // arrange await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddMessageBus() .AddRequestHandler() .AddRequestHandler() diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/SendTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/SendTests.cs index c657df3fee2..cf67487381a 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/SendTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/SendTests.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class SendTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public SendTests(RabbitMQFixture fixture) @@ -22,7 +21,7 @@ public async Task SendAsync_Should_DeliverToHandler_When_RequestHandlerRegistere var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(recorder) .AddMessageBus() .AddRequestHandler() @@ -36,7 +35,7 @@ public async Task SendAsync_Should_DeliverToHandler_When_RequestHandlerRegistere await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 99.99m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the request"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the request"); var message = Assert.Single(recorder.Messages); var payment = Assert.IsType(message); @@ -52,7 +51,7 @@ public async Task SendAsync_Should_DeliverToCorrectHandler_When_MultipleQueuesEx var refundRecorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddKeyedSingleton("payment", paymentRecorder) .AddKeyedSingleton("refund", refundRecorder) .AddMessageBus() @@ -68,7 +67,7 @@ public async Task SendAsync_Should_DeliverToCorrectHandler_When_MultipleQueuesEx await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-1", Amount = 50.00m }, CancellationToken.None); // assert - Assert.True(await paymentRecorder.WaitAsync(Timeout), "Payment handler did not receive the send message"); + Assert.True(await paymentRecorder.WaitAsync(s_timeout), "Payment handler did not receive the send message"); var msg = Assert.Single(paymentRecorder.Messages); Assert.IsType(msg); @@ -87,7 +86,7 @@ public async Task SendAsync_Should_DeliverToEachHandler_When_SendingToDifferentQ var refundRecorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddKeyedSingleton("payment", paymentRecorder) .AddKeyedSingleton("refund", refundRecorder) .AddMessageBus() @@ -104,8 +103,8 @@ public async Task SendAsync_Should_DeliverToEachHandler_When_SendingToDifferentQ await messageBus.SendAsync(new ProcessRefund { OrderId = "ORD-2", Amount = 25.00m }, CancellationToken.None); // assert - Assert.True(await paymentRecorder.WaitAsync(Timeout), "Payment handler did not receive the message"); - Assert.True(await refundRecorder.WaitAsync(Timeout), "Refund handler did not receive the message"); + Assert.True(await paymentRecorder.WaitAsync(s_timeout), "Payment handler did not receive the message"); + Assert.True(await refundRecorder.WaitAsync(s_timeout), "Refund handler did not receive the message"); var payment = Assert.IsType(Assert.Single(paymentRecorder.Messages)); Assert.Equal("ORD-1", payment.OrderId); diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/TransportMiddlewareTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/TransportMiddlewareTests.cs index d5dc4505dbf..e2336c33690 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/TransportMiddlewareTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Behaviors/TransportMiddlewareTests.cs @@ -1,14 +1,13 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Mocha.Transport.RabbitMQ.Tests.Helpers; -using RabbitMQ.Client; namespace Mocha.Transport.RabbitMQ.Tests.Behaviors; [Collection("RabbitMQ")] public class TransportMiddlewareTests { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); private readonly RabbitMQFixture _fixture; public TransportMiddlewareTests(RabbitMQFixture fixture) @@ -24,7 +23,7 @@ public async Task UseReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTransp var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -56,7 +55,7 @@ public async Task UseReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTransp await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-T1" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("transport-receive-mw", tracker.Invocations); } @@ -68,7 +67,7 @@ public async Task AppendReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTra var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -101,7 +100,7 @@ public async Task AppendReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTra await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-T2" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("transport-append-receive", tracker.Invocations); } @@ -113,7 +112,7 @@ public async Task PrependReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTr var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -146,7 +145,7 @@ public async Task PrependReceive_Should_InvokeOnAllEndpoints_When_ConfiguredAtTr await messageBus.PublishAsync(new OrderCreated { OrderId = "ORD-T3" }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Consumer did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Consumer did not receive the message within timeout"); Assert.Contains("transport-prepend-receive", tracker.Invocations); } @@ -158,7 +157,7 @@ public async Task UseDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtTrans var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -184,7 +183,7 @@ public async Task UseDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtTrans await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-TD1", Amount = 50.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("transport-dispatch-mw", tracker.Invocations); } @@ -196,7 +195,7 @@ public async Task AppendDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtTr var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -223,7 +222,7 @@ public async Task AppendDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtTr await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-TD2", Amount = 25.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("transport-append-dispatch", tracker.Invocations); } @@ -235,7 +234,7 @@ public async Task PrependDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtT var recorder = new MessageRecorder(); await using var vhost = await _fixture.CreateVhostAsync(); await using var bus = await new ServiceCollection() - .AddSingleton(vhost.ConnectionFactory) + .AddSingleton(vhost.ConnectionFactory) .AddSingleton(tracker) .AddSingleton(recorder) .AddMessageBus() @@ -262,7 +261,7 @@ public async Task PrependDispatch_Should_InvokeOnAllEndpoints_When_ConfiguredAtT await messageBus.SendAsync(new ProcessPayment { OrderId = "ORD-TD3", Amount = 10.00m }, CancellationToken.None); // assert - Assert.True(await recorder.WaitAsync(Timeout), "Handler did not receive the message within timeout"); + Assert.True(await recorder.WaitAsync(s_timeout), "Handler did not receive the message within timeout"); Assert.Contains("transport-prepend-dispatch", tracker.Invocations); } diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQConsumerManagerTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQConsumerManagerTests.cs index 07557fb71e8..cf36e75970c 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQConsumerManagerTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQConsumerManagerTests.cs @@ -1,8 +1,6 @@ -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using RabbitMQ.Client; -using RabbitMQ.Client.Events; namespace Mocha.Transport.RabbitMQ.Tests.Connection; @@ -50,7 +48,7 @@ public async Task AddConsumerAsync_Should_BeThreadSafe_When_ConcurrentCalls() // assert Assert.Equal(10, results.Length); - Assert.All(results, r => Assert.NotNull(r)); + Assert.All(results, Assert.NotNull); } [Fact] diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQDispatcherTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQDispatcherTests.cs index 527863da43d..3fee9d92195 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQDispatcherTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/Connection/RabbitMQDispatcherTests.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using RabbitMQ.Client; diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQMessageEnvelopeParserTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQMessageEnvelopeParserTests.cs index 9585c63e41b..0f16f78b122 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQMessageEnvelopeParserTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQMessageEnvelopeParserTests.cs @@ -1,4 +1,3 @@ -using System.Text; using RabbitMQ.Client; using RabbitMQ.Client.Events; diff --git a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQTransportTests.cs b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQTransportTests.cs index 698ed343be2..2a5d9019f92 100644 --- a/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQTransportTests.cs +++ b/src/Mocha/test/Mocha.Transport.RabbitMQ.Tests/RabbitMQTransportTests.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using Mocha.Middlewares; using Mocha.Transport.RabbitMQ.Tests.Helpers; namespace Mocha.Transport.RabbitMQ.Tests; diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Fusion/FusionDownloadCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Fusion/FusionDownloadCommand.cs index a32e313d1b9..2832d7ce529 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Fusion/FusionDownloadCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Fusion/FusionDownloadCommand.cs @@ -3,11 +3,9 @@ using System.Diagnostics.CodeAnalysis; #endif -using ChilliCream.Nitro.CommandLine.Client; using ChilliCream.Nitro.CommandLine.Configuration; using ChilliCream.Nitro.CommandLine.Helpers; using ChilliCream.Nitro.CommandLine.Options; -using ChilliCream.Nitro.CommandLine.Services.Sessions; namespace ChilliCream.Nitro.CommandLine.Commands.Fusion;