diff --git a/docs/adr/0057-box-schema-versioning-and-migrations.md b/docs/adr/0057-box-schema-versioning-and-migrations.md index af91e7c510..82203d20a5 100644 --- a/docs/adr/0057-box-schema-versioning-and-migrations.md +++ b/docs/adr/0057-box-schema-versioning-and-migrations.md @@ -336,7 +336,7 @@ The advisory-lock primitive that wraps the runner's chain (§3, §5a) is exposed - SQLite is **exempt** from the abstraction — it has no advisory lock; serialization is provided by `BEGIN IMMEDIATE`'s writer slot (per §5 table). The runner's existing `BeginImmediateWithRetryAsync` handles `SQLITE_BUSY` retry directly; introducing an `ISqliteAdvisoryLock` would invent a primitive that does not exist in the database. - Spanner is **exempt** — degenerate runner per §6, no concurrency primitive of its own. -**Constructor injection (additive)**: each runner ctor gains two optional parameters — `I*AdvisoryLock? advisoryLock = null` (default: `new *AdvisoryLock()`) and `ILogger? logger = null` (default: `ApplicationLogging.CreateLogger<*BoxMigrationRunner>()`). Both are non-breaking additions; existing call sites continue to compile and run with default behaviour. The DI extensions (`UseBoxProvisioning`) do not register the abstractions — operators wanting custom impls construct the runner explicitly. This matches the existing wiring approach for `IAmABoxMigrationRunner` itself. +**Constructor injection**: each runner ctor accepts an optional `I*AdvisoryLock? advisoryLock = null` (default: `new *AdvisoryLock()`) and requires an `ILoggerFactory`. An optional `ILogger? logger = null` can override the logger created by that factory. There is no implicit null-logger fallback; callers that want logging disabled must explicitly supply `NullLoggerFactory.Instance` or a null logger. The DI extensions obtain `ILoggerFactory` from the container. Operators wanting custom advisory-lock implementations construct the runner explicitly. **What does not absorb into the abstraction**: diff --git a/docs/adr/0064-pipeline-cache-type-key.md b/docs/adr/0064-pipeline-cache-type-key.md index e5748fc9ec..11c3b39714 100644 --- a/docs/adr/0064-pipeline-cache-type-key.md +++ b/docs/adr/0064-pipeline-cache-type-key.md @@ -84,8 +84,6 @@ All three are converted in one change (FR-3, FR-4, NFR-3, AC-11). 3. Leave everything else untouched: `ClearPipelineCache()` (`PipelineBuilder.cs:253`; `TransformPipelineBuilder.cs:223`; `TransformPipelineBuilderAsync.cs:186`), `Describe`/`Describe()` (which do not read the cache, `PipelineBuilder.cs:106-137, 144-155`), `DescribeTransforms` (`TransformPipelineBuilder.cs:197-221`), the `AddGlobalInboxAttributes`/`AddGlobalInboxAttributesAsync` `UseInbox` construction (`PipelineBuilder.cs:350-389`), `HandlerName`, and `RequestHandler.Name` — no public-API change (FR-7, AC-8, AC-9, OOS-3). 4. Update the one white-box test that inspects memento keys, `tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Post_Attributes_Are_Cached.cs`: the helper `GetPostAttributesCacheKeys` reflects `s_postAttributesMemento` and returns `cache.Keys.Cast()` as `IEnumerable`, asserted via `Assert.Contains(nameof(MyPreAndPostDecoratedHandler), …)`. After the change the keys are `Type`, so the helper's return type moves to `IEnumerable` and its body to `cache.Keys.Cast()`, and each assertion moves to `Assert.Contains(typeof(MyPreAndPostDecoratedHandler), …)` (and the async variant). Re-typing the helper is mandatory, not optional: `Cast()` over `Type` keys is not a compile error — it throws `InvalidCastException` at runtime. This is a test internal-detail update only; it is permitted because it asserts the cache's internal representation, which C-5 leaves unconstrained. -The pre-existing mis-typed logger generic in the async builder (`ApplicationLogging.CreateLogger` at `TransformPipelineBuilderAsync.cs:50`) is deliberately left untouched (OOS-2). - ## Consequences ### Positive diff --git a/samples/AsyncAPI/KafkaAsyncAPI/Program.cs b/samples/AsyncAPI/KafkaAsyncAPI/Program.cs index b0dd624236..26adf6eeb8 100644 --- a/samples/AsyncAPI/KafkaAsyncAPI/Program.cs +++ b/samples/AsyncAPI/KafkaAsyncAPI/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Jonny Olliff-Lee @@ -47,7 +47,7 @@ THE SOFTWARE. */ BootStrapServers = new[] { "localhost:9092" } }; -var kafkaMessageConsumerFactory = new KafkaMessageConsumerFactory(kafkaConfig); +var kafkaMessageConsumerFactory = new KafkaMessageConsumerFactory(kafkaConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // KafkaProducerRegistryFactory.Create() opens a real broker connection at construction // time, so we only build the registry when actually starting the producer side. In @@ -86,7 +86,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - }).Create(); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); brighter.AddProducers(configure => { diff --git a/samples/AsyncAPI/RMQAsyncAPI/Program.cs b/samples/AsyncAPI/RMQAsyncAPI/Program.cs index 52c42b0b2c..012361c342 100644 --- a/samples/AsyncAPI/RMQAsyncAPI/Program.cs +++ b/samples/AsyncAPI/RMQAsyncAPI/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Jonny Olliff-Lee @@ -45,7 +45,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.asyncapi.exchange"), }; -var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); +var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Build a producer registry with a typed Publication to demonstrate RequestType auto-discovery var producerRegistry = new RmqProducerRegistryFactory( @@ -58,7 +58,7 @@ THE SOFTWARE. */ MakeChannels = OnMissingChannel.Create, Topic = new RoutingKey("order.created") } - }).Create(); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); var host = new HostBuilder() .ConfigureServices((_, services) => diff --git a/samples/CommandProcessor/HelloWorldInternalBus/Program.cs b/samples/CommandProcessor/HelloWorldInternalBus/Program.cs index 6182ce401a..0f7b6be570 100644 --- a/samples/CommandProcessor/HelloWorldInternalBus/Program.cs +++ b/samples/CommandProcessor/HelloWorldInternalBus/Program.cs @@ -36,7 +36,7 @@ THE SOFTWARE. */ var bus = new InternalBus(); -var publications = new[] { new Publication { Topic = routingKey, RequestType = typeof(GreetingCommand)} }; +var publications = new[] { new Publication { Topic = routingKey, RequestType = typeof(GreetingCommand) } }; var subscriptions = new[] { @@ -52,14 +52,14 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + options.DefaultChannelFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); options.HandlerLifetime = ServiceLifetime.Scoped; options.MapperLifetime = ServiceLifetime.Singleton; options.InboxConfiguration = new InboxConfiguration(new InMemoryInbox(TimeProvider.System)); }) .AddProducers((config) => { - config.ProducerRegistry = new InMemoryProducerRegistryFactory(bus, publications, InstrumentationOptions.All).Create(); + config.ProducerRegistry = new InMemoryProducerRegistryFactory(bus, publications, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All).Create(); config.Outbox = new InMemoryOutbox(TimeProvider.System); }) .AutoFromAssemblies(); diff --git a/samples/Scheduler/AwsTaskQueue/GreetingsPumper/Program.cs b/samples/Scheduler/AwsTaskQueue/GreetingsPumper/Program.cs index 2c412d5d24..3e78e71356 100644 --- a/samples/Scheduler/AwsTaskQueue/GreetingsPumper/Program.cs +++ b/samples/Scheduler/AwsTaskQueue/GreetingsPumper/Program.cs @@ -66,8 +66,8 @@ private static async Task Main(string[] args) Topic = new RoutingKey("message-scheduler-topic"), RequestType = typeof(FireAwsScheduler) } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); services.AddBrighter() .AddProducers(configure => @@ -125,7 +125,7 @@ public async Task StartAsync(CancellationToken cancellationToken) { continue; } - + logger.LogInformation("Pausing for breath..."); await Task.Delay(TimeSpan.FromMinutes(2), cancellationToken); } diff --git a/samples/Scheduler/AwsTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/Scheduler/AwsTaskQueue/GreetingsReceiverConsole/Program.cs index b6e60e7f12..b1112ddcda 100644 --- a/samples/Scheduler/AwsTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/Scheduler/AwsTaskQueue/GreetingsReceiverConsole/Program.cs @@ -107,7 +107,7 @@ public static async Task Main(string[] args) services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AddProducers(configure => { @@ -132,8 +132,8 @@ public static async Task Main(string[] args) Topic = new RoutingKey("message-scheduler-topic"), RequestType = typeof(FireAwsScheduler) } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); }) .AutoFromAssemblies(); } diff --git a/samples/Scheduler/QuartzTaskQueue/GreetingsPumper/Program.cs b/samples/Scheduler/QuartzTaskQueue/GreetingsPumper/Program.cs index aecedc72f3..1ffdd1521a 100644 --- a/samples/Scheduler/QuartzTaskQueue/GreetingsPumper/Program.cs +++ b/samples/Scheduler/QuartzTaskQueue/GreetingsPumper/Program.cs @@ -56,8 +56,8 @@ Topic = new RoutingKey(typeof(GreetingEvent).FullName.ToValidSNSTopicName()), RequestType = typeof(GreetingEvent) } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); services.AddBrighter() .AddProducers((configure) => @@ -96,7 +96,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) logger.LogInformation("Scheduling message #{Loop}", loop); commandProcessor.Post(TimeSpan.FromSeconds(10), new GreetingEvent($"Scheduler message Ian #{loop}")); - + if (loop % 100 != 0) { continue; diff --git a/samples/Scheduler/QuartzTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/Scheduler/QuartzTaskQueue/GreetingsReceiverConsole/Program.cs index f6f8781ef9..5b95817c89 100644 --- a/samples/Scheduler/QuartzTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/Scheduler/QuartzTaskQueue/GreetingsReceiverConsole/Program.cs @@ -60,7 +60,7 @@ THE SOFTWARE. */ }; //create the gateway - var serviceURL = "http://localhost:4566/"; + var serviceURL = "http://localhost:4566/"; var region = RegionEndpoint.USEast1; var awsConnection = new AWSMessagingGatewayConnection(new BasicAWSCredentials("test", "test"), region, cfg => { cfg.ServiceURL = serviceURL; }); @@ -68,7 +68,7 @@ THE SOFTWARE. */ services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AutoFromAssemblies(); diff --git a/samples/Scheduler/TickerQ/Greeting.Consumer/Program.cs b/samples/Scheduler/TickerQ/Greeting.Consumer/Program.cs index 1a488c1453..3b55c758f1 100644 --- a/samples/Scheduler/TickerQ/Greeting.Consumer/Program.cs +++ b/samples/Scheduler/TickerQ/Greeting.Consumer/Program.cs @@ -34,7 +34,7 @@ }; opt.DefaultChannelFactory = new ChannelFactory( - new RmqMessageConsumerFactory(rmqConnection) + new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ); }) @@ -53,7 +53,7 @@ app.MapGet("/", () => { - return "helloConsumer"; + return "helloConsumer"; }); app.Run(); diff --git a/samples/Scheduler/TickerQ/Greeting.Producer/Program.cs b/samples/Scheduler/TickerQ/Greeting.Producer/Program.cs index 09af938406..af27bb8f62 100644 --- a/samples/Scheduler/TickerQ/Greeting.Producer/Program.cs +++ b/samples/Scheduler/TickerQ/Greeting.Producer/Program.cs @@ -56,7 +56,7 @@ RequestType = typeof(GreetingEvent), MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); }).UseScheduler(provider => { @@ -92,7 +92,7 @@ app.MapPost("/send-multiple", async (IAmACommandProcessor commandProcessor) => { - var iterations = 5; + var iterations = 5; for (int i = 1; i <= iterations; i++) { var content = $"Manual multiple message #{i}"; diff --git a/samples/TaskQueue/ASBTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/ASBTaskQueue/GreetingsReceiverConsole/Program.cs index e5f6900269..0c42a560fe 100644 --- a/samples/TaskQueue/ASBTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/ASBTaskQueue/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using Greetings.Ports.CommandHandlers; using Greetings.Ports.Events; using Microsoft.Extensions.DependencyInjection; @@ -42,7 +42,7 @@ //TODO: add your ASB qualified name here var clientProvider = new ServiceBusConnectionStringClientProvider("Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"); -var asbConsumerFactory = new AzureServiceBusConsumerFactory(clientProvider); +var asbConsumerFactory = new AzureServiceBusConsumerFactory(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; diff --git a/samples/TaskQueue/ASBTaskQueue/GreetingsScopedReceiverConsole/Program.cs b/samples/TaskQueue/ASBTaskQueue/GreetingsScopedReceiverConsole/Program.cs index 08ec1e8eb6..2b389660f5 100644 --- a/samples/TaskQueue/ASBTaskQueue/GreetingsScopedReceiverConsole/Program.cs +++ b/samples/TaskQueue/ASBTaskQueue/GreetingsScopedReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -// If you run this receiver with the other receiver, and send you'll see different behaviours. +// If you run this receiver with the other receiver, and send you'll see different behaviours. // This scoped receiver will refresh the scoped dependency for each pipeline (Event/Command dispatch) using System; @@ -44,7 +44,7 @@ //TODO: add your ASB qualified name here var asbClientProvider = new ServiceBusConnectionStringClientProvider("Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"); -var asbConsumerFactory = new AzureServiceBusConsumerFactory(asbClientProvider); +var asbConsumerFactory = new AzureServiceBusConsumerFactory(asbClientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services .AddConsumers(options => { diff --git a/samples/TaskQueue/ASBTaskQueue/GreetingsSender.Web/Program.cs b/samples/TaskQueue/ASBTaskQueue/GreetingsSender.Web/Program.cs index 644150b352..e73418b142 100644 --- a/samples/TaskQueue/ASBTaskQueue/GreetingsSender.Web/Program.cs +++ b/samples/TaskQueue/ASBTaskQueue/GreetingsSender.Web/Program.cs @@ -37,7 +37,7 @@ var asbConnection = new ServiceBusConnectionStringClientProvider(asbEndpoint); -var outboxConfig = new RelationalDatabaseConfiguration(dbConnString, +var outboxConfig = new RelationalDatabaseConfiguration(dbConnString, databaseName: "BrighterTests", outBoxTableName: "BrighterOutbox"); var producerRegistry = new AzureServiceBusProducerRegistryFactory( @@ -46,8 +46,8 @@ new() { Topic = new RoutingKey("greeting.event"), MakeChannels = OnMissingChannel.Assume}, new() { Topic = new RoutingKey("greeting.addGreetingCommand"), MakeChannels = OnMissingChannel.Assume }, new() { Topic = new RoutingKey("greeting.Asyncevent"), MakeChannels = OnMissingChannel.Assume } - ] - ) + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); builder.Services @@ -64,7 +64,7 @@ .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; - configure.Outbox = new MsSqlOutbox(outboxConfig); + configure.Outbox = new MsSqlOutbox(outboxConfig, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); configure.TransactionProvider = typeof(MsSqlEntityFrameworkCoreTransactionProvider); }); diff --git a/samples/TaskQueue/ASBTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/ASBTaskQueue/GreetingsSender/Program.cs index d4c9511a36..79dc1da836 100644 --- a/samples/TaskQueue/ASBTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/ASBTaskQueue/GreetingsSender/Program.cs @@ -35,9 +35,9 @@ static void Main(string[] args) { Topic = new RoutingKey("greeting.Asyncevent"), } - ] - ).Create(); - + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection.AddBrighter() .AddProducers((config) => { @@ -61,12 +61,12 @@ static void Main(string[] args) Console.WriteLine("Sending...."); var distroGreeting = new GreetingEvent("Paul - Distributed"); commandProcessor.DepositPost(distroGreeting); - + commandProcessor.Post(new GreetingEvent("Paul")); commandProcessor.Post(new GreetingAsyncEvent("Paul - Async")); commandProcessor.ClearOutbox([distroGreeting.Id.Value]); - + Console.WriteLine("Press q to Quit or any other key to continue"); var keyPress = Console.ReadKey(); diff --git a/samples/TaskQueue/ASBTaskQueue/GreetingsWorker/Program.cs b/samples/TaskQueue/ASBTaskQueue/GreetingsWorker/Program.cs index 225f26126b..6fbfd3dcc6 100644 --- a/samples/TaskQueue/ASBTaskQueue/GreetingsWorker/Program.cs +++ b/samples/TaskQueue/ASBTaskQueue/GreetingsWorker/Program.cs @@ -60,7 +60,7 @@ }; string dbConnString = "Server=127.0.0.1,11433;Database=BrighterTests;User Id=sa;Password=Password1!;Application Name=BrighterTests;MultipleActiveResultSets=True"; - + //EF builder.Services.AddDbContext(o => { @@ -69,17 +69,17 @@ var clientProvider = new ServiceBusConnectionStringClientProvider("Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"); -var asbConsumerFactory = new AzureServiceBusConsumerFactory(clientProvider); +var asbConsumerFactory = new AzureServiceBusConsumerFactory(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; options.DefaultChannelFactory = new AzureServiceBusChannelFactory(asbConsumerFactory); - + }) .AutoFromAssemblies(); builder.Services.AddHostedService(); - + builder.Logging.SetMinimumLevel(LogLevel.Information).AddConsole(); diff --git a/samples/TaskQueue/AWSTaskQueue/GreetingsPumper/Program.cs b/samples/TaskQueue/AWSTaskQueue/GreetingsPumper/Program.cs index 25422726d7..afba960f47 100644 --- a/samples/TaskQueue/AWSTaskQueue/GreetingsPumper/Program.cs +++ b/samples/TaskQueue/AWSTaskQueue/GreetingsPumper/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using Amazon; @@ -39,8 +39,8 @@ typeof(FarewellEvent).FullName.ToValidSNSTopicName(true)), TopicAttributes = new SnsAttributes { Type = SqsType.Fifo } } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); builder.Services.AddBrighter() .AddProducers((configure) => diff --git a/samples/TaskQueue/AWSTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/AWSTaskQueue/GreetingsReceiverConsole/Program.cs index 37dfa989e0..55ed2b9234 100644 --- a/samples/TaskQueue/AWSTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/AWSTaskQueue/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -78,7 +78,7 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/AWSTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/AWSTaskQueue/GreetingsSender/Program.cs index f2f0667d5c..98cf5906be 100644 --- a/samples/TaskQueue/AWSTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/AWSTaskQueue/GreetingsSender/Program.cs @@ -79,8 +79,8 @@ static async Task Main(string[] args) Type = SqsType.Fifo } } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); serviceCollection .AddBrighter() diff --git a/samples/TaskQueue/KafkaDeferOnError/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/KafkaDeferOnError/GreetingsReceiverConsole/Program.cs index f81dd3d7af..611f240743 100644 --- a/samples/TaskQueue/KafkaDeferOnError/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaDeferOnError/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -75,9 +75,10 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } - ); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -86,7 +87,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); services.AddHostedService(); diff --git a/samples/TaskQueue/KafkaDeferOnError/GreetingsSender/Program.cs b/samples/TaskQueue/KafkaDeferOnError/GreetingsSender/Program.cs index 05e9bc87b3..99644dab88 100644 --- a/samples/TaskQueue/KafkaDeferOnError/GreetingsSender/Program.cs +++ b/samples/TaskQueue/KafkaDeferOnError/GreetingsSender/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -52,7 +52,8 @@ THE SOFTWARE. */ var producerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -64,14 +65,14 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); services .AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/TaskQueue/KafkaDontAckOnError/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/KafkaDontAckOnError/GreetingsReceiverConsole/Program.cs index 02266908d9..fa5de2ae7e 100644 --- a/samples/TaskQueue/KafkaDontAckOnError/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaDontAckOnError/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -75,16 +75,17 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } - ); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { options.Subscriptions = subscriptions; options.DefaultChannelFactory = new ChannelFactory(consumerFactory); }) - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); services.AddHostedService(); diff --git a/samples/TaskQueue/KafkaDontAckOnError/GreetingsSender/Program.cs b/samples/TaskQueue/KafkaDontAckOnError/GreetingsSender/Program.cs index 8f7df77794..1a04d1f0e5 100644 --- a/samples/TaskQueue/KafkaDontAckOnError/GreetingsSender/Program.cs +++ b/samples/TaskQueue/KafkaDontAckOnError/GreetingsSender/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -52,7 +52,8 @@ THE SOFTWARE. */ var producerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -64,12 +65,12 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); services .AddBrighter() - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/TaskQueue/KafkaDynamicEventStream/TaskReceiverConsole/Program.cs b/samples/TaskQueue/KafkaDynamicEventStream/TaskReceiverConsole/Program.cs index d81ff51613..c140b6c98f 100644 --- a/samples/TaskQueue/KafkaDynamicEventStream/TaskReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaDynamicEventStream/TaskReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -65,13 +65,14 @@ THE SOFTWARE. */ new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } - )); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) //This is the default mapper type, but we are explicit for the sample anyway .AutoFromAssemblies([typeof(TaskCreated).Assembly], defaultMessageMapper: typeof(JsonMessageMapper<>), asyncDefaultMessageMapper: typeof(JsonMessageMapper<>)); diff --git a/samples/TaskQueue/KafkaDynamicEventStream/TaskStatusSender/Program.cs b/samples/TaskQueue/KafkaDynamicEventStream/TaskStatusSender/Program.cs index d46a0d5caa..6e8cab4001 100644 --- a/samples/TaskQueue/KafkaDynamicEventStream/TaskStatusSender/Program.cs +++ b/samples/TaskQueue/KafkaDynamicEventStream/TaskStatusSender/Program.cs @@ -41,7 +41,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new KafkaProducerRegistryFactory( @@ -66,7 +66,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) //This is the default mapper type, but we are explicit for the sample anyway diff --git a/samples/TaskQueue/KafkaSchemaRegistry/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/KafkaSchemaRegistry/GreetingsReceiverConsole/Program.cs index 4d041ca34d..2cd636ef00 100644 --- a/samples/TaskQueue/KafkaSchemaRegistry/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaSchemaRegistry/GreetingsReceiverConsole/Program.cs @@ -63,13 +63,14 @@ THE SOFTWARE. */ new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = ["localhost:9092"] - } - )); + Name = "paramore.brighter", + BootStrapServers = ["localhost:9092"] + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/KafkaSchemaRegistry/GreetingsSender/Program.cs b/samples/TaskQueue/KafkaSchemaRegistry/GreetingsSender/Program.cs index addd77d556..053c50d5e7 100644 --- a/samples/TaskQueue/KafkaSchemaRegistry/GreetingsSender/Program.cs +++ b/samples/TaskQueue/KafkaSchemaRegistry/GreetingsSender/Program.cs @@ -49,13 +49,14 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = ["localhost:9092"] + Name = "paramore.brighter.greetingsender", + BootStrapServers = ["localhost:9092"] }, [ new KafkaPublication @@ -66,7 +67,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/KafkaTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/KafkaTaskQueue/GreetingsReceiverConsole/Program.cs index 0a9521655a..fbff3fa4a2 100644 --- a/samples/TaskQueue/KafkaTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaTaskQueue/GreetingsReceiverConsole/Program.cs @@ -54,9 +54,10 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } -); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { @@ -65,7 +66,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/KafkaTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/KafkaTaskQueue/GreetingsSender/Program.cs index 26de70c991..f3a3824f96 100644 --- a/samples/TaskQueue/KafkaTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/KafkaTaskQueue/GreetingsSender/Program.cs @@ -67,13 +67,14 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -85,7 +86,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/KafkaTaskQueueWithDLQ/DlqConsole/Program.cs b/samples/TaskQueue/KafkaTaskQueueWithDLQ/DlqConsole/Program.cs index afda851e0a..9a50342d56 100644 --- a/samples/TaskQueue/KafkaTaskQueueWithDLQ/DlqConsole/Program.cs +++ b/samples/TaskQueue/KafkaTaskQueueWithDLQ/DlqConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -75,9 +75,10 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.dlq", BootStrapServers = new[] { "localhost:9092" } - } - ); + Name = "paramore.brighter.dlq", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -86,7 +87,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs index a5e90e9535..d17849dcbd 100644 --- a/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -76,9 +76,10 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } - ); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -87,7 +88,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsSender/Program.cs b/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsSender/Program.cs index 93f5444c43..526a4a6f24 100644 --- a/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsSender/Program.cs +++ b/samples/TaskQueue/KafkaTaskQueueWithDLQ/GreetingsSender/Program.cs @@ -83,13 +83,14 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -101,7 +102,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/MsSqlMessagingGateway/CompetingReceiverConsole/Program.cs b/samples/TaskQueue/MsSqlMessagingGateway/CompetingReceiverConsole/Program.cs index 1bbbbcb024..8e4c3bb89f 100644 --- a/samples/TaskQueue/MsSqlMessagingGateway/CompetingReceiverConsole/Program.cs +++ b/samples/TaskQueue/MsSqlMessagingGateway/CompetingReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using CompetingReceiverConsole; @@ -27,16 +27,16 @@ @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", databaseName: "BrighterSqlQueue", queueStoreTable: "QueueData"); -var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration); +var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(messageConsumerFactory); + options.DefaultChannelFactory = new ChannelFactory(messageConsumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/MsSqlMessagingGateway/CompetingSender/Program.cs b/samples/TaskQueue/MsSqlMessagingGateway/CompetingSender/Program.cs index e7f1ba8085..664bf17ef1 100644 --- a/samples/TaskQueue/MsSqlMessagingGateway/CompetingSender/Program.cs +++ b/samples/TaskQueue/MsSqlMessagingGateway/CompetingSender/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using System.Transactions; @@ -32,13 +32,13 @@ var producerRegistry = new MsSqlProducerRegistryFactory( messagingConfiguration, - [new Publication()]) + [new Publication()], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); builder.Services.AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/TaskQueue/MsSqlMessagingGateway/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/MsSqlMessagingGateway/GreetingsReceiverConsole/Program.cs index 6e52daa3d8..1fc56d966c 100644 --- a/samples/TaskQueue/MsSqlMessagingGateway/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/MsSqlMessagingGateway/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -52,13 +52,13 @@ THE SOFTWARE. */ @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", databaseName: "BrighterSqlQueue", queueStoreTable: "QueueData" - ) - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/MsSqlMessagingGateway/GreetingsSender/Program.cs b/samples/TaskQueue/MsSqlMessagingGateway/GreetingsSender/Program.cs index 9022f39a4a..38d3905088 100644 --- a/samples/TaskQueue/MsSqlMessagingGateway/GreetingsSender/Program.cs +++ b/samples/TaskQueue/MsSqlMessagingGateway/GreetingsSender/Program.cs @@ -25,7 +25,7 @@ static void Main() serviceCollection.AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new MsSqlProducerRegistryFactory( @@ -33,8 +33,8 @@ static void Main() @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", databaseName: "BrighterSqlQueue", queueStoreTable: "QueueData"), - [new Publication{Topic = new RoutingKey("greeting.event"), RequestType = typeof(GreetingEvent)}] - ) + [new Publication { Topic = new RoutingKey("greeting.event"), RequestType = typeof(GreetingEvent) }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/MultiBus/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/MultiBus/GreetingsReceiverConsole/Program.cs index 88112280af..90cb15ee74 100644 --- a/samples/TaskQueue/MultiBus/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/MultiBus/GreetingsReceiverConsole/Program.cs @@ -65,9 +65,10 @@ THE SOFTWARE. */ var consumerFactory = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } -); + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var rmqConnection = new RmqMessagingGatewayConnection { @@ -75,7 +76,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.exchange") }; -var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); +var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { @@ -87,7 +88,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/MultiBus/GreetingsSender/Program.cs b/samples/TaskQueue/MultiBus/GreetingsSender/Program.cs index f389e4503b..50cf6716ba 100644 --- a/samples/TaskQueue/MultiBus/GreetingsSender/Program.cs +++ b/samples/TaskQueue/MultiBus/GreetingsSender/Program.cs @@ -65,7 +65,8 @@ THE SOFTWARE. */ var kafkaMessageProducerFactory = new KafkaMessageProducerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -77,7 +78,7 @@ THE SOFTWARE. */ MessageTimeoutMs = 1000, MaxInFlightRequestsPerConnection = 1 } - ]); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var rmqConnection = new RmqMessagingGatewayConnection { @@ -95,7 +96,7 @@ THE SOFTWARE. */ Topic = new RoutingKey("another.greeting.event"), RequestType = typeof(AnotherGreetingEvent) } - ]); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddBrighter(options => { @@ -103,7 +104,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new CombinedProducerRegistryFactory( diff --git a/samples/TaskQueue/PostgresTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/PostgresTaskQueue/GreetingsReceiverConsole/Program.cs index 5bbe3b5838..01729f3e4c 100644 --- a/samples/TaskQueue/PostgresTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/PostgresTaskQueue/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -56,7 +56,7 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new PostgresChannelFactory(connection); + options.DefaultChannelFactory = new PostgresChannelFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AutoFromAssemblies(); diff --git a/samples/TaskQueue/PostgresTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/PostgresTaskQueue/GreetingsSender/Program.cs index f45b43bac2..6d6a4b97f9 100644 --- a/samples/TaskQueue/PostgresTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/PostgresTaskQueue/GreetingsSender/Program.cs @@ -50,7 +50,7 @@ public static void Main(string[] args) var connection = new PostgresMessagingGatewayConnection(new RelationalDatabaseConfiguration("Host=localhost;Username=postgres;Password=password;Database=brightertests;")); var producerRegistry = new PostgresProducerRegistryFactory( - connection, + connection, [ new PostgresPublication { @@ -64,8 +64,8 @@ public static void Main(string[] args) Topic = new RoutingKey("farewell.event"), RequestType = typeof(FarewellEvent) } - ]).Create(); - + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection .AddBrighter() .AddProducers((configure) => diff --git a/samples/TaskQueue/RMQDeferOnError/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/RMQDeferOnError/GreetingsReceiverConsole/Program.cs index cb8d2be019..c36a57f02f 100644 --- a/samples/TaskQueue/RMQDeferOnError/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/RMQDeferOnError/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -73,7 +73,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -81,7 +81,7 @@ THE SOFTWARE. */ options.DefaultChannelFactory = new ChannelFactory(rmqMessageConsumerFactory); }) // InMemorySchedulerFactory provides requeue delay support for deferred messages. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); services.AddHostedService(); diff --git a/samples/TaskQueue/RMQDeferOnError/GreetingsSender/Program.cs b/samples/TaskQueue/RMQDeferOnError/GreetingsSender/Program.cs index 0f833718fe..72dd4b63bb 100644 --- a/samples/TaskQueue/RMQDeferOnError/GreetingsSender/Program.cs +++ b/samples/TaskQueue/RMQDeferOnError/GreetingsSender/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -65,13 +65,13 @@ THE SOFTWARE. */ Topic = new RoutingKey("greeting.event"), RequestType = typeof(GreetingEvent) } - ]).Create(); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); services .AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/TaskQueue/RMQRequestReply/GreetingsClient/Program.cs b/samples/TaskQueue/RMQRequestReply/GreetingsClient/Program.cs index 7ffdd2af41..3862bc0f5e 100644 --- a/samples/TaskQueue/RMQRequestReply/GreetingsClient/Program.cs +++ b/samples/TaskQueue/RMQRequestReply/GreetingsClient/Program.cs @@ -57,7 +57,7 @@ static void Main(string[] args) .AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = new RmqProducerRegistryFactory( @@ -68,19 +68,19 @@ static void Main(string[] args) Topic = new RoutingKey("Greeting.Request"), RequestType = typeof(GreetingRequest) } - ]).Create(); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); configure.UseRpc = true; configure.ReplyQueueSubscriptions = [ new RmqSubscription( - new SubscriptionName("ReplySubscription"), - new ChannelName("ReplyChannel"), - new RoutingKey("Reply"), + new SubscriptionName("ReplySubscription"), + new ChannelName("ReplyChannel"), + new RoutingKey("Reply"), typeof(GreetingReply), messagePumpType: MessagePumpType.Reactor ) ]; - configure.ResponseChannelFactory = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)); + configure.ResponseChannelFactory = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) .AutoFromAssemblies(); @@ -94,8 +94,9 @@ static void Main(string[] args) commandProcessor.Call( new GreetingRequest { - Name = "Ian", Language = "en-gb" - }, + Name = "Ian", + Language = "en-gb" + }, timeOut: TimeSpan.FromMilliseconds(2000) ); diff --git a/samples/TaskQueue/RMQRequestReply/GreetingsServer/Program.cs b/samples/TaskQueue/RMQRequestReply/GreetingsServer/Program.cs index 7c9db14c70..fb0cba212b 100644 --- a/samples/TaskQueue/RMQRequestReply/GreetingsServer/Program.cs +++ b/samples/TaskQueue/RMQRequestReply/GreetingsServer/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2017 Ian Cooper @@ -53,7 +53,7 @@ THE SOFTWARE. */ highAvailability: true, messagePumpType: MessagePumpType.Reactor) ]; - options.DefaultChannelFactory = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)); + options.DefaultChannelFactory = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); }) .AddProducers((configure) => { @@ -67,11 +67,11 @@ THE SOFTWARE. */ RequestType = typeof(GreetingReply), MakeChannels = OnMissingChannel.Assume } - ]).Create(); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/RMQTaskQueue/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/RMQTaskQueue/GreetingsReceiverConsole/Program.cs index 69a9a8d979..cf1faeeb32 100644 --- a/samples/TaskQueue/RMQTaskQueue/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/RMQTaskQueue/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -62,7 +62,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.exchange") }; -var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); +var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { @@ -71,7 +71,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/RMQTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/RMQTaskQueue/GreetingsSender/Program.cs index 224cce11c1..375ebff130 100644 --- a/samples/TaskQueue/RMQTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/RMQTaskQueue/GreetingsSender/Program.cs @@ -71,13 +71,13 @@ static void Main(string[] args) Topic = new RoutingKey("farewell.event"), RequestType = typeof(FarewellEvent) } - ]).Create(); - + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection .AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; @@ -113,7 +113,7 @@ public override Publication Find(IAmAProducerRegistry registry, Reques // topic.Replace("{tenant}", tenantContext.Tenant) return registry.LookupBy(topic).Publication; } - + return base.Find(registry, context); } } diff --git a/samples/TaskQueue/RMQTaskQueueWithDLQ/DlqConsole/Program.cs b/samples/TaskQueue/RMQTaskQueueWithDLQ/DlqConsole/Program.cs index 55ec9baa54..d8332b2651 100644 --- a/samples/TaskQueue/RMQTaskQueueWithDLQ/DlqConsole/Program.cs +++ b/samples/TaskQueue/RMQTaskQueueWithDLQ/DlqConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -73,7 +73,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -82,7 +82,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); services.AddHostedService(); diff --git a/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs b/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs index 2e5cf83657..2895cee5b7 100644 --- a/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs +++ b/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -75,7 +75,7 @@ THE SOFTWARE. */ Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -84,7 +84,7 @@ THE SOFTWARE. */ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); services.AddHostedService(); diff --git a/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsSender/Program.cs b/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsSender/Program.cs index 1cef3f7d3d..5b987f6684 100644 --- a/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsSender/Program.cs +++ b/samples/TaskQueue/RMQTaskQueueWithDLQ/GreetingsSender/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -65,13 +65,13 @@ THE SOFTWARE. */ Topic = new RoutingKey("greeting.event"), RequestType = typeof(GreetingEvent) } - ]).Create(); + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); services .AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/TaskQueue/RedisTaskQueue/GreetingsReceiver/Program.cs b/samples/TaskQueue/RedisTaskQueue/GreetingsReceiver/Program.cs index 9c20d1e8db..59d4d8f3dd 100644 --- a/samples/TaskQueue/RedisTaskQueue/GreetingsReceiver/Program.cs +++ b/samples/TaskQueue/RedisTaskQueue/GreetingsReceiver/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using Greetings.Ports.Events; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -27,7 +27,7 @@ MessageTimeToLive = TimeSpan.FromMinutes(10) }; -var redisConsumerFactory = new RedisMessageConsumerFactory(redisConnection); +var redisConsumerFactory = new RedisMessageConsumerFactory(redisConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; @@ -35,7 +35,7 @@ }) // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. -.UseScheduler(new InMemorySchedulerFactory()) +.UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); builder.Services.AddHostedService(); diff --git a/samples/TaskQueue/RedisTaskQueue/GreetingsSender/Program.cs b/samples/TaskQueue/RedisTaskQueue/GreetingsSender/Program.cs index 38d69f49a6..a83583d937 100644 --- a/samples/TaskQueue/RedisTaskQueue/GreetingsSender/Program.cs +++ b/samples/TaskQueue/RedisTaskQueue/GreetingsSender/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2017 Ian Cooper @@ -48,13 +48,13 @@ THE SOFTWARE. */ Topic = new RoutingKey("greeting.event"), RequestType = typeof(GreetingEvent) } - ] -).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); builder.Services.AddBrighter() // InMemorySchedulerFactory is the default — shown here explicitly to demonstrate scheduler configuration. // Replace with HangfireMessageSchedulerFactory or QuartzSchedulerFactory for durable scheduling. - .UseScheduler(new InMemorySchedulerFactory()) + .UseScheduler(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AddProducers((configure) => { configure.ProducerRegistry = producerRegistry; diff --git a/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsReceiverConsole/Program.cs b/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsReceiverConsole/Program.cs index 04fa8225d6..96af3fac2f 100644 --- a/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsReceiverConsole/Program.cs +++ b/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -62,7 +62,7 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .UseExternalLuggageStore(provider => new S3LuggageStore(new S3LuggageOptions( new AWSS3Connection(credentials, RegionEndpoint.EUWest1), @@ -70,7 +70,7 @@ THE SOFTWARE. */ { HttpClientFactory = provider.GetService(), Strategy = StorageStrategy.Validate - })) + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies(); //We need this for the check as to whether an S3 bucket exists diff --git a/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsSender/Program.cs b/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsSender/Program.cs index 215a14092f..58a781e81a 100644 --- a/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsSender/Program.cs +++ b/samples/Transforms/AWSTransfomers/ClaimCheck/GreetingsSender/Program.cs @@ -54,7 +54,7 @@ static void Main(string[] args) var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(new SerilogLoggerFactory()); - + if (new CredentialProfileStoreChain().TryGetAWSCredentials("default", out var credentials)) { var awsConnection = new AWSMessagingGatewayConnection(credentials, RegionEndpoint.EUWest1); @@ -71,9 +71,9 @@ static void Main(string[] args) FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Create } - ] - ).Create(); - + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection.AddBrighter() .AddProducers((configure) => { @@ -85,30 +85,30 @@ static void Main(string[] args) { HttpClientFactory = provider.GetService(), Strategy = StorageStrategy.Validate - })) + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .AutoFromAssemblies([typeof(GreetingEvent).Assembly]); //We need this for the check as to whether an S3 bucket exists serviceCollection.AddHttpClient(); - + var serviceProvider = serviceCollection.BuildServiceProvider(); var commandProcessor = serviceProvider.GetService(); - + Console.WriteLine($"Sending Event to SNS topic {topic} "); //create a 512K string, too large for a payload, that needs offloading commandProcessor.Post(new GreetingEvent($"Hi - {CreateString(524288)}")); - + Console.WriteLine($"Sent Event to SNS topic {topic} "); } } - + public static string CreateString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[new Random().Next(s.Length)]).ToArray()); - } + } } } diff --git a/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsReceiverConsole/Program.cs b/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsReceiverConsole/Program.cs index 3f06dc8f4f..f49b21a93e 100644 --- a/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsReceiverConsole/Program.cs +++ b/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -58,7 +58,7 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AutoFromAssemblies(); } diff --git a/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsSender/Program.cs b/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsSender/Program.cs index a621a535a9..4c2d3a44d5 100644 --- a/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsSender/Program.cs +++ b/samples/Transforms/AWSTransfomers/CloudEvents/GreetingsSender/Program.cs @@ -53,7 +53,7 @@ static void Main(string[] args) var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(new SerilogLoggerFactory()); - + if (new CredentialProfileStoreChain().TryGetAWSCredentials("default", out var credentials)) { var awsConnection = new AWSMessagingGatewayConnection(credentials, RegionEndpoint.EUWest1); @@ -70,9 +70,9 @@ static void Main(string[] args) FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Create } - ] - ).Create(); - + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection.AddBrighter() .AddProducers((configure) => { @@ -83,20 +83,20 @@ static void Main(string[] args) var serviceProvider = serviceCollection.BuildServiceProvider(); var commandProcessor = serviceProvider.GetRequiredService(); - + Console.WriteLine($"Sending Event to SNS topic {topic} "); commandProcessor.Post(new GreetingEvent("Hi Ian")); - + Console.WriteLine($"Sent Event to SNS topic {topic} "); } } - + public static string CreateString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[new Random().Next(s.Length)]).ToArray()); - } + } } } diff --git a/samples/Transforms/AWSTransfomers/Compression/GreetingsReceiverConsole/Program.cs b/samples/Transforms/AWSTransfomers/Compression/GreetingsReceiverConsole/Program.cs index 56cd20c288..78a793da7b 100644 --- a/samples/Transforms/AWSTransfomers/Compression/GreetingsReceiverConsole/Program.cs +++ b/samples/Transforms/AWSTransfomers/Compression/GreetingsReceiverConsole/Program.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -58,7 +58,7 @@ THE SOFTWARE. */ builder.Services.AddConsumers(options => { options.Subscriptions = subscriptions; - options.DefaultChannelFactory = new ChannelFactory(awsConnection); + options.DefaultChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AutoFromAssemblies(); } diff --git a/samples/Transforms/AWSTransfomers/Compression/GreetingsSender/Program.cs b/samples/Transforms/AWSTransfomers/Compression/GreetingsSender/Program.cs index 418c29730e..774ee6ae7c 100644 --- a/samples/Transforms/AWSTransfomers/Compression/GreetingsSender/Program.cs +++ b/samples/Transforms/AWSTransfomers/Compression/GreetingsSender/Program.cs @@ -53,7 +53,7 @@ static void Main(string[] args) var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(new SerilogLoggerFactory()); - + if (new CredentialProfileStoreChain().TryGetAWSCredentials("default", out var credentials)) { var awsConnection = new AWSMessagingGatewayConnection(credentials, RegionEndpoint.EUWest1); @@ -70,9 +70,9 @@ static void Main(string[] args) FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Create } - ] - ).Create(); - + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + serviceCollection.AddBrighter() .AddProducers((configure) => { @@ -83,23 +83,23 @@ static void Main(string[] args) var serviceProvider = serviceCollection.BuildServiceProvider(); var commandProcessor = serviceProvider.GetService(); - + Console.WriteLine($"Sending Event to SNS topic {topic} "); //create a string that is too large for a payload, that needs compression but will give some good compression var largeString = new string('a', 512000); //var largeString = "hello world"; commandProcessor.Post(new GreetingEvent($"Hi -{largeString}")); - + Console.WriteLine($"Sent Event to SNS topic {topic} "); } } - + public static string CreateString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[new Random().Next(s.Length)]).ToArray()); - } + } } } diff --git a/samples/Transforms/JustSaying/BrighterSide/Program.cs b/samples/Transforms/JustSaying/BrighterSide/Program.cs index 8f2c24fee8..67afa999a4 100644 --- a/samples/Transforms/JustSaying/BrighterSide/Program.cs +++ b/samples/Transforms/JustSaying/BrighterSide/Program.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; using Amazon; using Amazon.Runtime; using Microsoft.Extensions.DependencyInjection; @@ -33,7 +33,7 @@ messagePumpType: MessagePumpType.Reactor) ]; - configure.DefaultChannelFactory = new ChannelFactory(connection); + configure.DefaultChannelFactory = new ChannelFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AddProducers(configure => { @@ -44,7 +44,7 @@ Topic = nameof(Greeting).ToLower(), RequestType = typeof(Greeting) } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .TransformsFromAssemblies([typeof(JustSayingAttribute).Assembly]) @@ -56,7 +56,7 @@ await host.StartAsync(); var cts = new CancellationTokenSource(); -Console.CancelKeyPress += (_,_) => cts.Cancel(); +Console.CancelKeyPress += (_, _) => cts.Cancel(); while (!cts.IsCancellationRequested) { @@ -100,12 +100,12 @@ public Task MapToRequestAsync(Message message, CancellationToken cance public Message MapToMessage(Greeting request, Publication publication) { return new Message(new MessageHeader - { - MessageId = request.Id, - CorrelationId = Id.Random(), - MessageType = MessageType.MT_COMMAND, - Topic = publication.Topic!, - }, + { + MessageId = request.Id, + CorrelationId = Id.Random(), + MessageType = MessageType.MT_COMMAND, + Topic = publication.Topic!, + }, new MessageBody(JsonSerializer.SerializeToUtf8Bytes(request, JsonSerialisationOptions.Options))); } diff --git a/samples/Transforms/MassTransit/MBrigtherSide/Program.cs b/samples/Transforms/MassTransit/MBrigtherSide/Program.cs index 395dd1ec3f..4e98f6ff80 100644 --- a/samples/Transforms/MassTransit/MBrigtherSide/Program.cs +++ b/samples/Transforms/MassTransit/MBrigtherSide/Program.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; using Amazon; using Amazon.Runtime; using Microsoft.Extensions.DependencyInjection; @@ -33,7 +33,7 @@ messagePumpType: MessagePumpType.Reactor) ]; - configure.DefaultChannelFactory = new ChannelFactory(connection); + configure.DefaultChannelFactory = new ChannelFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AddProducers(configure => { @@ -44,7 +44,7 @@ Topic = "brighter-topic", RequestType = typeof(Greeting) } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); }) .TransformsFromAssemblies([typeof(MassTransitWrapAttribute).Assembly]) @@ -56,7 +56,7 @@ await host.StartAsync(); var cts = new CancellationTokenSource(); -Console.CancelKeyPress += (_,_) => cts.Cancel(); +Console.CancelKeyPress += (_, _) => cts.Cancel(); while (!cts.IsCancellationRequested) { @@ -101,12 +101,12 @@ public Task MapToRequestAsync(Message message, CancellationToken cance public Message MapToMessage(Greeting request, Publication publication) { return new Message(new MessageHeader - { - MessageId = request.Id, - CorrelationId = Id.Random(), - MessageType = MessageType.MT_EVENT, - Topic = publication.Topic!, - }, + { + MessageId = request.Id, + CorrelationId = Id.Random(), + MessageType = MessageType.MT_EVENT, + Topic = publication.Topic!, + }, new MessageBody(JsonSerializer.SerializeToUtf8Bytes(request, JsonSerialisationOptions.Options))); } diff --git a/samples/WebAPI/WebAPI_Common/DbMaker/InboxFactory.cs b/samples/WebAPI/WebAPI_Common/DbMaker/InboxFactory.cs index 860f179836..959a8a7d51 100644 --- a/samples/WebAPI/WebAPI_Common/DbMaker/InboxFactory.cs +++ b/samples/WebAPI/WebAPI_Common/DbMaker/InboxFactory.cs @@ -19,15 +19,15 @@ public static IAmAnInbox MakeInbox(Rdbms rdbms, IAmARelationalDatabaseConfigurat { return rdbms switch { - Rdbms.Sqlite => new SqliteInbox(configuration), - Rdbms.MySql => new MySqlInbox(configuration), - Rdbms.MsSql => new MsSqlInbox(configuration), - Rdbms.Postgres => new PostgreSqlInbox(configuration), + Rdbms.Sqlite => new SqliteInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), + Rdbms.MySql => new MySqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), + Rdbms.MsSql => new MsSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), + Rdbms.Postgres => new PostgreSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), _ => throw new ArgumentOutOfRangeException(nameof(rdbms), "Database type is not supported") }; } - public static void CreateInbox(IAmazonDynamoDB client, IServiceCollection services) where T : class, IRequest + public static void CreateInbox(IAmazonDynamoDB client, IServiceCollection services) where T : class, IRequest { var tableRequestFactory = new DynamoDbTableFactory(); var dbTableBuilder = new DynamoDbTableBuilder(client); diff --git a/samples/WebAPI/WebAPI_Common/DbMaker/OutboxFactory.cs b/samples/WebAPI/WebAPI_Common/DbMaker/OutboxFactory.cs index ed73fd30a2..6179ee04a4 100644 --- a/samples/WebAPI/WebAPI_Common/DbMaker/OutboxFactory.cs +++ b/samples/WebAPI/WebAPI_Common/DbMaker/OutboxFactory.cs @@ -38,10 +38,10 @@ public static (IAmAnOutbox, Type, Type) MakeDapperOutbox(Rdbms rdbms, Relational public static void MakeDynamoOutbox(IAmazonDynamoDB client) { var dbTableBuilder = new DynamoDbTableBuilder(client); - + var createTableRequest = new DynamoDbTableFactory().GenerateCreateTableRequest( new DynamoDbCreateProvisionedThroughput( - new ProvisionedThroughput{ReadCapacityUnits = 10, WriteCapacityUnits = 10}, + new ProvisionedThroughput { ReadCapacityUnits = 10, WriteCapacityUnits = 10 }, new Dictionary { {"Outstanding", new ProvisionedThroughput{ReadCapacityUnits = 10, WriteCapacityUnits = 10}}, @@ -56,8 +56,8 @@ public static void MakeDynamoOutbox(IAmazonDynamoDB client) dbTableBuilder.EnsureTablesReady([createTableRequest.TableName], TableStatus.ACTIVE).Wait(); } } - - public static (IAmAnOutbox, Type, Type) MakeEfOutbox(Rdbms rdbms, RelationalDatabaseConfiguration configuration) + + public static (IAmAnOutbox, Type, Type) MakeEfOutbox(Rdbms rdbms, RelationalDatabaseConfiguration configuration) where T : DbContext { (IAmAnOutbox, Type, Type) outbox = rdbms switch @@ -74,49 +74,49 @@ public static (IAmAnOutbox, Type, Type) MakeEfOutbox(Rdbms rdbms, Relational private static (IAmAnOutbox, Type, Type) MakeDapperPostgresSqlOutbox(RelationalDatabaseConfiguration configuration) { - return (new PostgreSqlOutbox(configuration), typeof(PostgreSqlConnectionProvider), + return (new PostgreSqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(PostgreSqlConnectionProvider), typeof(PostgreSqlTransactionProvider)); } - + private static (IAmAnOutbox, Type, Type) MakeEfPostgreSqlOutbox(RelationalDatabaseConfiguration configuration) where T : DbContext { - return (new PostgreSqlOutbox(configuration), typeof(PostgreSqlEntityFrameworkTransactionProvider), + return (new PostgreSqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(PostgreSqlEntityFrameworkTransactionProvider), typeof(PostgreSqlConnectionProvider)); } private static (IAmAnOutbox, Type, Type) MakeDapperMsSqlOutbox(RelationalDatabaseConfiguration configuration) { - return new ValueTuple(new MsSqlOutbox(configuration), typeof(MsSqlConnectionProvider), + return new ValueTuple(new MsSqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(MsSqlConnectionProvider), typeof(MsSqlTransactionProvider)); } - + private static (IAmAnOutbox, Type, Type) MakeEfMsSqlOutbox(RelationalDatabaseConfiguration configuration) where T : DbContext { - return new ValueTuple(new MsSqlOutbox(configuration), typeof(MsSqlEntityFrameworkCoreTransactionProvider), + return new ValueTuple(new MsSqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(MsSqlEntityFrameworkCoreTransactionProvider), typeof(MsSqlConnectionProvider)); } private static (IAmAnOutbox, Type, Type) MakeDapperMySqlOutbox(RelationalDatabaseConfiguration configuration) { - return (new MySqlOutbox(configuration), typeof(MySqlConnectionProvider), typeof(MySqlTransactionProvider)); + return (new MySqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(MySqlConnectionProvider), typeof(MySqlTransactionProvider)); } - + private static (IAmAnOutbox, Type, Type) MakeEfMySqlOutbox(RelationalDatabaseConfiguration configuration) where T : DbContext { - return (new MySqlOutbox(configuration),typeof(MySqlEntityFrameworkTransactionProvider), typeof(MySqlConnectionProvider)); + return (new MySqlOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(MySqlEntityFrameworkTransactionProvider), typeof(MySqlConnectionProvider)); } private static (IAmAnOutbox, Type, Type) MakeDapperSqliteOutBox(RelationalDatabaseConfiguration configuration) { - return (new SqliteOutbox(configuration), typeof(SqliteConnectionProvider), typeof(SqliteTransactionProvider)); + return (new SqliteOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(SqliteConnectionProvider), typeof(SqliteTransactionProvider)); } - + private static (IAmAnOutbox, Type, Type) MakeEfSqliteOutBox(RelationalDatabaseConfiguration configuration) where T : DbContext { - return (new SqliteOutbox(configuration), typeof(SqliteEntityFrameworkTransactionProvider), typeof(SqliteConnectionProvider)); + return (new SqliteOutbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), typeof(SqliteEntityFrameworkTransactionProvider), typeof(SqliteConnectionProvider)); } } diff --git a/samples/WebAPI/WebAPI_Common/TransportMaker/ConfigureTransport.cs b/samples/WebAPI/WebAPI_Common/TransportMaker/ConfigureTransport.cs index 3730b9b839..a3c8a429c4 100644 --- a/samples/WebAPI/WebAPI_Common/TransportMaker/ConfigureTransport.cs +++ b/samples/WebAPI/WebAPI_Common/TransportMaker/ConfigureTransport.cs @@ -31,7 +31,7 @@ public static MessagingTransport TransportType(string brighterTransport) "Messaging transport is not supported") }; } - + public static IAmAProducerRegistry MakeProducerRegistry(MessagingTransport messagingTransport) where T : class, IRequest { return messagingTransport switch @@ -43,10 +43,11 @@ public static IAmAProducerRegistry MakeProducerRegistry(MessagingTransport me "Messaging transport is not supported") }; } - + public static void AddSchemaRegistryMaybe(IServiceCollection services, MessagingTransport messagingTransport) { - if (messagingTransport != MessagingTransport.Kafka) return; + if (messagingTransport != MessagingTransport.Kafka) + return; SchemaRegistryConfig schemaRegistryConfig = new SchemaRegistryConfig { Url = "http://localhost:8081" }; CachedSchemaRegistryClient cachedSchemaRegistryClient = new CachedSchemaRegistryClient(schemaRegistryConfig); @@ -61,7 +62,7 @@ public static bool HasBinaryMessagePayload() return TransportType(transport) == MessagingTransport.Kafka; } - + static IAmAProducerRegistry GetRmqProducerRegistry() where T : class, IRequest { IAmAProducerRegistry producerRegistry = new RmqProducerRegistryFactory( @@ -78,19 +79,20 @@ static IAmAProducerRegistry GetRmqProducerRegistry() where T : class, IReques WaitForConfirmsTimeOutInMilliseconds = 1000, MakeChannels = OnMissingChannel.Create } - ] - ) + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); return producerRegistry; } - - public static IAmAProducerRegistry GetKafkaProducerRegistry() where T: class, IRequest + + public static IAmAProducerRegistry GetKafkaProducerRegistry() where T : class, IRequest { IAmAProducerRegistry producerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter.greetingsender", BootStrapServers = new[] { "localhost:9092" } + Name = "paramore.brighter.greetingsender", + BootStrapServers = new[] { "localhost:9092" } }, [ new KafkaPublication @@ -102,12 +104,12 @@ public static IAmAProducerRegistry GetKafkaProducerRegistry() where T: class, MaxInFlightRequestsPerConnection = 1, MakeChannels = OnMissingChannel.Create } - ]) + ], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); return producerRegistry; } - + private static IAmAProducerRegistry GetAsbProducerRegistry() where T : class, IRequest { IAmAProducerRegistry producerRegistry = new AzureServiceBusProducerRegistryFactory( @@ -115,13 +117,13 @@ private static IAmAProducerRegistry GetAsbProducerRegistry() where T : class, new AzureServiceBusPublication[] { new() { Topic = new RoutingKey(typeof(T).Name), RequestType = typeof(T) } - } - ) + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); return producerRegistry; } - + public static IAmAChannelFactory GetChannelFactory(MessagingTransport messagingTransport) { return messagingTransport switch @@ -132,7 +134,7 @@ public static IAmAChannelFactory GetChannelFactory(MessagingTransport messagingT "Messaging transport is not supported") }; } - + static IAmAChannelFactory GetRmqChannelFactory() { return new Paramore.Brighter.MessagingGateway.RMQ.Async.ChannelFactory( @@ -140,7 +142,7 @@ static IAmAChannelFactory GetRmqChannelFactory() { AmpqUri = new AmqpUriSpecification(new Uri("amqp://guest:guest@localhost:5672")), Exchange = new Exchange("paramore.brighter.exchange") - }) + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ); } @@ -150,9 +152,10 @@ static IAmAChannelFactory GetKafkaChannelFactory() new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { - Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } - } - ) + Name = "paramore.brighter", + BootStrapServers = new[] { "localhost:9092" } + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ); } @@ -203,5 +206,5 @@ static Subscription[] GetKafkaSubscriptions() where T : class, IRequest } } - + diff --git a/samples/WebAPI/WebAPI_Dynamo/SalutationAnalytics/Program.cs b/samples/WebAPI/WebAPI_Dynamo/SalutationAnalytics/Program.cs index f9f29d00b7..d076021294 100644 --- a/samples/WebAPI/WebAPI_Dynamo/SalutationAnalytics/Program.cs +++ b/samples/WebAPI/WebAPI_Dynamo/SalutationAnalytics/Program.cs @@ -80,18 +80,18 @@ static void ConfigureBrighter( Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var transport = hostContext.Configuration[MessagingGlobals.BRIGHTER_TRANSPORT]; if (string.IsNullOrWhiteSpace(transport)) throw new InvalidOperationException("Transport is not set"); - + MessagingTransport messagingTransport = ConfigureTransport.TransportType(transport); ConfigureTransport.AddSchemaRegistryMaybe(services, messagingTransport); - - var producerRegistry = ConfigureTransport.MakeProducerRegistry(messagingTransport); + + var producerRegistry = ConfigureTransport.MakeProducerRegistry(messagingTransport); services.AddConsumers(options => { diff --git a/samples/WebAPI/WebAPI_EFCore/SalutationAnalytics/Program.cs b/samples/WebAPI/WebAPI_EFCore/SalutationAnalytics/Program.cs index eebf993675..1b822d28f9 100644 --- a/samples/WebAPI/WebAPI_EFCore/SalutationAnalytics/Program.cs +++ b/samples/WebAPI/WebAPI_EFCore/SalutationAnalytics/Program.cs @@ -27,7 +27,8 @@ static void AddSchemaRegistryMaybe(IServiceCollection services, MessagingTransport messagingTransport) { - if (messagingTransport != MessagingTransport.Kafka) return; + if (messagingTransport != MessagingTransport.Kafka) + return; SchemaRegistryConfig schemaRegistryConfig = new() { Url = "http://localhost:8081" }; CachedSchemaRegistryClient cachedSchemaRegistryClient = new(schemaRegistryConfig); @@ -70,7 +71,7 @@ static void ConfigureBrighter(HostBuilderContext hostContext, IServiceCollection MessagingTransport messagingTransport = ConfigureTransport.TransportType(transport); AddSchemaRegistryMaybe(services, messagingTransport); - + string? dbType = hostContext.Configuration[DatabaseGlobals.DATABASE_TYPE_ENV]; if (string.IsNullOrWhiteSpace(dbType)) throw new InvalidOperationException("DbType is not set"); @@ -88,7 +89,7 @@ static void ConfigureBrighter(HostBuilderContext hostContext, IServiceCollection services.AddSingleton(outboxConfiguration); Rdbms rdbms = DbResolver.GetDatabaseType(dbType); - (IAmAnOutbox outbox, Type transactionProvider, Type connectionProvider) makeOutbox = + (IAmAnOutbox outbox, Type transactionProvider, Type connectionProvider) makeOutbox = OutboxFactory.MakeEfOutbox(rdbms, outboxConfiguration); IAmAProducerRegistry producerRegistry = ConfigureProducerRegistry(); @@ -110,7 +111,7 @@ static void ConfigureBrighter(HostBuilderContext hostContext, IServiceCollection { AmpqUri = new AmqpUriSpecification(new Uri("amqp://guest:guest@localhost:5672")), Exchange = new Exchange("paramore.brighter.exchange"), - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddConsumers(options => { @@ -149,7 +150,7 @@ static void ConfigureBrighter(HostBuilderContext hostContext, IServiceCollection static string GetEnvironment() { //NOTE: Hosting Context will always return Production outside of ASPNET_CORE at this point, so grab it directly - return Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") + return Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? throw new InvalidOperationException(" ASP_NETCORE_ENVIRONMENT is not set "); } @@ -193,8 +194,8 @@ static IAmAProducerRegistry ConfigureProducerRegistry() WaitForConfirmsTimeOutInMilliseconds = 1000, MakeChannels = OnMissingChannel.Create } - ] - ).Create(); + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); return producerRegistry; } diff --git a/src/Paramore.Brighter.Archive.Azure/AzureBlobArchiveProvider.cs b/src/Paramore.Brighter.Archive.Azure/AzureBlobArchiveProvider.cs index 9e08e74590..33253ab153 100644 --- a/src/Paramore.Brighter.Archive.Azure/AzureBlobArchiveProvider.cs +++ b/src/Paramore.Brighter.Archive.Azure/AzureBlobArchiveProvider.cs @@ -1,15 +1,14 @@ -using Azure.Storage; +using Azure.Storage; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Storage.Azure; -public class AzureBlobArchiveProvider(AzureBlobArchiveProviderOptions options) : IAmAnArchiveProvider +public class AzureBlobArchiveProvider(AzureBlobArchiveProviderOptions options, ILoggerFactory loggerFactory) : IAmAnArchiveProvider { private readonly BlobContainerClient _containerClient = new BlobContainerClient(options.BlobContainerUri, options.TokenCredential); - private readonly ILogger _logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// /// Send a Message to the archive provider @@ -27,7 +26,8 @@ public void ArchiveMessage(Message message) return; } - if (message.Body.Memory.IsEmpty) throw new AggregateException("Messages must have a body to be archived"); + if (message.Body.Memory.IsEmpty) + throw new AggregateException("Messages must have a body to be archived"); var opts = GetUploadOptions(message); blobClient.Upload(BinaryData.FromBytes(message.Body.Memory), opts); @@ -48,8 +48,9 @@ public async Task ArchiveMessageAsync(Message message, CancellationToken cancell _logger.LogDebug("Message with Id {MessageId} has already been uploaded", message.Id); return; } - - if (message.Body.Memory.IsEmpty) throw new AggregateException("Messages must have a body to be archived"); + + if (message.Body.Memory.IsEmpty) + throw new AggregateException("Messages must have a body to be archived"); var opts = GetUploadOptions(message); await blobClient.UploadAsync(BinaryData.FromBytes(message.Body.Memory), opts, cancellationToken); @@ -84,7 +85,7 @@ public async Task ArchiveMessagesAsync(Message[] messages, CancellationTok await ArchiveMessageAsync(message, cancellationToken); return message.Id; } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Error archiving message with Id {MessageId}", message.Id); return null; @@ -97,7 +98,7 @@ private BlobClient GetBlobClient(Message message) _logger.LogDebug("Uploading Message with Id {MessageId} to {ArchiveLocation}", message.Id, storageLocation); return _containerClient.GetBlobClient(storageLocation); } - + private BlobUploadOptions GetUploadOptions(Message message) { var opts = new BlobUploadOptions() diff --git a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs index dae702e170..889871d34b 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.MsSql; @@ -61,13 +60,14 @@ public MsSqlBoxMigrationRunner( MsSqlBoxDetectionHelper detectionHelper, IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, IMsSqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, TimeSpan? lockTimeout = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) : base(detectionHelper, catalog, configuration, lockTimeout ?? TimeSpan.FromSeconds(30), - logger ?? ApplicationLogging.CreateLogger(), + logger ?? loggerFactory.CreateLogger(), tracer, scope) { _advisoryLock = advisoryLock ?? new MsSqlAdvisoryLock(); @@ -83,11 +83,12 @@ public MsSqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, + ILoggerFactory loggerFactory, IMsSqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) - : this(new MsSqlBoxDetectionHelper(), catalog, configuration, advisoryLock, logger, lockTimeout, tracer, scope) + : this(new MsSqlBoxDetectionHelper(), catalog, configuration, loggerFactory, advisoryLock, logger, lockTimeout, tracer, scope) { } @@ -425,7 +426,8 @@ await InsertHistoryRowAsync( for (var i = 0; i < migrations.Count; i++) { var migration = migrations[i]; - if (migration.Version <= detected) continue; + if (migration.Version <= detected) + continue; await ExecuteUpScriptAsync(connection, transaction!, migration, cancellationToken); await InsertHistoryRowAsync( @@ -445,7 +447,8 @@ protected override async Task RunNormalPathAsync( foreach (var migration in migrations) { - if (migration.Version <= maxVersion) continue; + if (migration.Version <= maxVersion) + continue; await ExecuteUpScriptAsync(connection, transaction!, migration, cancellationToken); await InsertHistoryRowAsync( diff --git a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxProvisioningExtensions.cs b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxProvisioningExtensions.cs index 2bf4f94355..f56abfc37e 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxProvisioningExtensions.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxProvisioningExtensions.cs @@ -1,7 +1,8 @@ -using System; +using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.MsSql; @@ -30,13 +31,15 @@ public static BoxProvisioningOptions AddMsSqlOutbox( { var catalog = sp.GetRequiredService(); var runner = new MsSqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MsSqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -69,13 +72,15 @@ public static BoxProvisioningOptions AddMsSqlOutbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new MsSqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MsSqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -96,13 +101,15 @@ public static BoxProvisioningOptions AddMsSqlInbox( { var catalog = sp.GetRequiredService(); var runner = new MsSqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MsSqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -135,13 +142,15 @@ public static BoxProvisioningOptions AddMsSqlInbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new MsSqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MsSqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; diff --git a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlInboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlInboxProvisioner.cs index 1c802e5016..1e65427974 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlInboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlInboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.MsSql; @@ -37,8 +38,9 @@ public MsSqlInboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlOutboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlOutboxProvisioner.cs index 9277f5d7fc..3ae124f17c 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlOutboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlOutboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.MsSql; @@ -37,8 +38,9 @@ public MsSqlOutboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs index bcf12e5999..ec64b88a9a 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MySqlConnector; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.MySql; @@ -61,13 +60,14 @@ public MySqlBoxMigrationRunner( MySqlBoxDetectionHelper detectionHelper, IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, IMySqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, TimeSpan? lockTimeout = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) : base(detectionHelper, catalog, configuration, lockTimeout ?? TimeSpan.FromSeconds(30), - logger ?? ApplicationLogging.CreateLogger(), + logger ?? loggerFactory.CreateLogger(), tracer, scope) { _advisoryLock = advisoryLock ?? new MySqlAdvisoryLock(); @@ -83,11 +83,12 @@ public MySqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, + ILoggerFactory loggerFactory, IMySqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) - : this(new MySqlBoxDetectionHelper(), catalog, configuration, advisoryLock, logger, lockTimeout, tracer, scope) + : this(new MySqlBoxDetectionHelper(), catalog, configuration, loggerFactory, advisoryLock, logger, lockTimeout, tracer, scope) { } @@ -205,7 +206,8 @@ await InsertHistoryRowAsync( for (var i = 0; i < migrations.Count; i++) { var migration = migrations[i]; - if (migration.Version <= detected) continue; + if (migration.Version <= detected) + continue; await ExecuteUpScriptAsync(connection, migration, cancellationToken); await InsertHistoryRowAsync( @@ -224,7 +226,8 @@ protected override async Task RunNormalPathAsync( foreach (var migration in migrations) { - if (migration.Version <= maxVersion) continue; + if (migration.Version <= maxVersion) + continue; await ExecuteUpScriptAsync(connection, migration, cancellationToken); await InsertHistoryRowAsync( @@ -284,7 +287,8 @@ private string DatabaseName() private string EnsureAllowUserVariables(string connectionString) { var builder = new MySqlConnectionStringBuilder(connectionString); - if (builder.AllowUserVariables) return builder.ConnectionString; + if (builder.AllowUserVariables) + return builder.ConnectionString; Logger.LogInformation( "MySQL box-migration runner: enabling AllowUserVariables=true on the migration connection (caller's connection string had it disabled). Required by the V2..V7 prepared-statement idempotency pattern per ADR 0057 §5a; the mutation is scoped to the runner's own MySqlConnection and does not affect the caller-supplied connection string instance."); diff --git a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxProvisioningExtensions.cs b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxProvisioningExtensions.cs index d3e8374d8e..70093879e3 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxProvisioningExtensions.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxProvisioningExtensions.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -25,6 +25,7 @@ THE SOFTWARE. */ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.MySql; @@ -53,13 +54,15 @@ public static BoxProvisioningOptions AddMySqlOutbox( { var catalog = sp.GetRequiredService(); var runner = new MySqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MySqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -92,13 +95,15 @@ public static BoxProvisioningOptions AddMySqlOutbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new MySqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MySqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -119,13 +124,15 @@ public static BoxProvisioningOptions AddMySqlInbox( { var catalog = sp.GetRequiredService(); var runner = new MySqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MySqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -158,13 +165,15 @@ public static BoxProvisioningOptions AddMySqlInbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new MySqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new MySqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; diff --git a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlInboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlInboxProvisioner.cs index ae0c38dff7..c29782598d 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlInboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlInboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using MySqlConnector; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.MySql; @@ -37,8 +38,9 @@ public MySqlInboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlOutboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlOutboxProvisioner.cs index bbd6fb79fd..7e708ccba0 100644 --- a/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlOutboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.MySql/MySqlOutboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using MySqlConnector; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.MySql; @@ -37,8 +38,9 @@ public MySqlOutboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs index fb824d08a5..de526bb929 100644 --- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs +++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -26,9 +26,7 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; using Npgsql; -using Paramore.Brighter.Logging; using Paramore.Brighter.PostgreSql; namespace Paramore.Brighter.BoxProvisioning.PostgreSql; @@ -71,15 +69,13 @@ private static string QuotedHistorySchema(string? historySchema) } /// - /// Initialises the detection helper with an optional logger. When unspecified, falls back - /// to . Existing callers that use the - /// parameterless form continue to work — the logger is currently only consumed for the + /// Initialises the detection helper with a logger. The logger is currently only consumed for the /// rare UndefinedTable-swallow Debug emission in /// ; the helper remains a safe DI singleton. /// - public PostgreSqlBoxDetectionHelper(ILogger? logger = null) + public PostgreSqlBoxDetectionHelper(ILogger logger) { - _logger = logger ?? ApplicationLogging.CreateLogger(); + _logger = logger; } /// @@ -92,7 +88,8 @@ public async Task DoesTableExistAsync( NpgsqlTransaction? transaction = null) { using var command = connection.CreateCommand(); - if (transaction != null) command.Transaction = transaction; + if (transaction != null) + command.Transaction = transaction; command.CommandText = @" SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @TableName)"; @@ -142,7 +139,8 @@ public async Task DoesHistoryExistAsync( // parameterising only the (folded) schema. using (var existsCmd = connection.CreateCommand()) { - if (transaction != null) existsCmd.Transaction = transaction; + if (transaction != null) + existsCmd.Transaction = transaction; existsCmd.CommandText = @" SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @HistorySchema AND TABLE_NAME = '__BrighterMigrationHistory')"; @@ -154,7 +152,8 @@ SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES } using var command = connection.CreateCommand(); - if (transaction != null) command.Transaction = transaction; + if (transaction != null) + command.Transaction = transaction; command.CommandText = $@" SELECT COUNT(1) FROM {quotedHistorySchema}.""__BrighterMigrationHistory"" WHERE ""BoxTableName"" = @BoxTableName AND ""SchemaName"" = @SchemaName"; @@ -210,7 +209,8 @@ public async Task GetMaxVersionAsync( // "public"; PerSchema → the configured SchemaName, folded identically via PgIdentifier.Quote. var quotedHistorySchema = QuotedHistorySchema(historySchema); using var command = connection.CreateCommand(); - if (transaction != null) command.Transaction = transaction; + if (transaction != null) + command.Transaction = transaction; command.CommandText = $@" SELECT COALESCE(MAX(""MigrationVersion""), 0) FROM {quotedHistorySchema}.""__BrighterMigrationHistory"" WHERE ""BoxTableName"" = @BoxTableName AND ""SchemaName"" = @SchemaName"; @@ -292,7 +292,8 @@ internal async Task> GetTableColumnsAsHashSetAsync( NpgsqlTransaction? transaction = null) { using var command = connection.CreateCommand(); - if (transaction != null) command.Transaction = transaction; + if (transaction != null) + command.Transaction = transaction; command.CommandText = @" SELECT column_name FROM information_schema.columns WHERE table_schema = @SchemaName AND table_name = @TableName"; diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs index 2a2fa11d28..e7a23159fe 100644 --- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Npgsql; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.PostgreSql; @@ -61,13 +60,14 @@ public PostgreSqlBoxMigrationRunner( PostgreSqlBoxDetectionHelper detectionHelper, IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, IPostgreSqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, TimeSpan? lockTimeout = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) : base(detectionHelper, catalog, configuration, lockTimeout ?? TimeSpan.FromSeconds(30), - logger ?? ApplicationLogging.CreateLogger(), + logger ?? loggerFactory.CreateLogger(), tracer, scope) { _advisoryLock = advisoryLock ?? new PostgreSqlAdvisoryLock(); @@ -83,11 +83,21 @@ public PostgreSqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, + ILoggerFactory loggerFactory, IPostgreSqlAdvisoryLock? advisoryLock = null, ILogger? logger = null, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) - : this(new PostgreSqlBoxDetectionHelper(), catalog, configuration, advisoryLock, logger, lockTimeout, tracer, scope) + : this( + new PostgreSqlBoxDetectionHelper(loggerFactory.CreateLogger()), + catalog, + configuration, + loggerFactory, + advisoryLock, + logger, + lockTimeout, + tracer, + scope) { } @@ -457,7 +467,8 @@ await InsertHistoryRowAsync( for (var i = 0; i < migrations.Count; i++) { var migration = migrations[i]; - if (migration.Version <= detected) continue; + if (migration.Version <= detected) + continue; await ExecuteUpScriptAsync(connection, transaction!, migration, cancellationToken); await InsertHistoryRowAsync( @@ -477,7 +488,8 @@ protected override async Task RunNormalPathAsync( foreach (var migration in migrations) { - if (migration.Version <= maxVersion) continue; + if (migration.Version <= maxVersion) + continue; await ExecuteUpScriptAsync(connection, transaction!, migration, cancellationToken); await InsertHistoryRowAsync( diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxProvisioningExtensions.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxProvisioningExtensions.cs index 69aeec08fb..53454cdaf4 100644 --- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxProvisioningExtensions.cs +++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxProvisioningExtensions.cs @@ -1,7 +1,8 @@ -using System; +using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.PostgreSql; @@ -30,13 +31,15 @@ public static BoxProvisioningOptions AddPostgreSqlOutbox( { var catalog = sp.GetRequiredService(); var runner = new PostgreSqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new PostgreSqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -69,13 +72,15 @@ public static BoxProvisioningOptions AddPostgreSqlOutbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new PostgreSqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new PostgreSqlOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -96,13 +101,15 @@ public static BoxProvisioningOptions AddPostgreSqlInbox( { var catalog = sp.GetRequiredService(); var runner = new PostgreSqlBoxMigrationRunner(catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new PostgreSqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -135,13 +142,15 @@ public static BoxProvisioningOptions AddPostgreSqlInbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new PostgreSqlBoxMigrationRunner(catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new PostgreSqlInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlInboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlInboxProvisioner.cs index df73fd3564..3f3d543588 100644 --- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlInboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlInboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Npgsql; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.PostgreSql; @@ -38,8 +39,9 @@ public PostgreSqlInboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlOutboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlOutboxProvisioner.cs index 4412f8ac2c..a6e27820bd 100644 --- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlOutboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlOutboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Npgsql; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.PostgreSql; @@ -38,8 +39,9 @@ public PostgreSqlOutboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs index 7cbc2049fc..3121a2d60e 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -29,9 +29,7 @@ THE SOFTWARE. */ using Google.Cloud.Spanner.Data; using Grpc.Core; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; using Paramore.Brighter.Inbox.Spanner; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Outbox.Spanner; @@ -85,13 +83,14 @@ public class SpannerBoxMigrationRunner : IAmABoxMigrationRunner public SpannerBoxMigrationRunner( IAmABoxMigrationDetectionHelper detectionHelper, IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, IAmABrighterTracer? tracer = null, ILogger? logger = null) { _detectionHelper = detectionHelper; _configuration = configuration; _tracer = tracer; - _logger = logger ?? ApplicationLogging.CreateLogger(); + _logger = logger ?? loggerFactory.CreateLogger(); } /// @@ -101,9 +100,10 @@ public SpannerBoxMigrationRunner( /// public SpannerBoxMigrationRunner( IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, IAmABrighterTracer? tracer = null, ILogger? logger = null) - : this(new SpannerBoxDetectionHelper(), configuration, tracer, logger) + : this(new SpannerBoxDetectionHelper(), configuration, loggerFactory, tracer, logger) { } @@ -205,7 +205,8 @@ public async Task MigrateAsync( var activity = _tracer?.ActivitySource.StartActivity( $"{BrighterSemanticConventions.BoxMigration} {tableName}", ActivityKind.Internal); - if (activity is null) return null; + if (activity is null) + return null; activity.SetTag(BrighterSemanticConventions.DbSystem, DbSystem.Spanner.ToDbName()); activity.SetTag(BrighterSemanticConventions.DbTable, tableName); if (schemaName is not null) @@ -281,7 +282,8 @@ await InsertHistoryRowToleratingDuplicateAsync( // history-divergence case Spanner has no in-place migration path to fix. private static void VerifyAtLatestVersionOrThrow(string tableName, int vLatest, int currentVersion) { - if (currentVersion == vLatest) return; + if (currentVersion == vLatest) + return; // Per ADR 0057 §6: Spanner has no advisory-lock concept and no in-place migration // chain — fresh-install is the only forward path, and the relational backends' diff --git a/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxProvisioningExtensions.cs b/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxProvisioningExtensions.cs index 1b56742779..2c80d5eec1 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxProvisioningExtensions.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxProvisioningExtensions.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -25,6 +25,7 @@ THE SOFTWARE. */ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.Spanner; @@ -48,6 +49,7 @@ public static BoxProvisioningOptions AddSpannerOutbox( { var detectionHelper = sp.GetRequiredService(); var runner = new SpannerBoxMigrationRunner(detectionHelper, configuration, + sp.GetRequiredService(), tracer: sp.GetService()); return new SpannerOutboxProvisioner( detectionHelper, @@ -83,6 +85,7 @@ public static BoxProvisioningOptions AddSpannerOutbox( binaryMessagePayload: binaryMessagePayload); var detectionHelper = sp.GetRequiredService(); var runner = new SpannerBoxMigrationRunner(detectionHelper, dbConfig, + sp.GetRequiredService(), tracer: sp.GetService()); return new SpannerOutboxProvisioner( detectionHelper, @@ -108,6 +111,7 @@ public static BoxProvisioningOptions AddSpannerInbox( { var detectionHelper = sp.GetRequiredService(); var runner = new SpannerBoxMigrationRunner(detectionHelper, configuration, + sp.GetRequiredService(), tracer: sp.GetService()); return new SpannerInboxProvisioner( detectionHelper, @@ -143,6 +147,7 @@ public static BoxProvisioningOptions AddSpannerInbox( binaryMessagePayload: binaryMessagePayload); var detectionHelper = sp.GetRequiredService(); var runner = new SpannerBoxMigrationRunner(detectionHelper, dbConfig, + sp.GetRequiredService(), tracer: sp.GetService()); return new SpannerInboxProvisioner( detectionHelper, diff --git a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs index b8f1650531..6460143d8a 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.Sqlite; @@ -92,13 +91,14 @@ public SqliteBoxMigrationRunner( SqliteBoxDetectionHelper detectionHelper, IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory, ILogger? logger = null, TimeSpan? lockTimeout = null, bool enableWalMode = true, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) : base(detectionHelper, catalog, configuration, lockTimeout ?? TimeSpan.FromSeconds(30), - logger ?? ApplicationLogging.CreateLogger(), + logger ?? loggerFactory.CreateLogger(), tracer, scope) { _enableWalMode = enableWalMode; @@ -115,10 +115,11 @@ public SqliteBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, + ILoggerFactory loggerFactory, bool enableWalMode = true, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) - : this(new SqliteBoxDetectionHelper(), catalog, configuration, logger: null, lockTimeout: lockTimeout, enableWalMode: enableWalMode, tracer: tracer, scope: scope) + : this(new SqliteBoxDetectionHelper(), catalog, configuration, loggerFactory, logger: null, lockTimeout: lockTimeout, enableWalMode: enableWalMode, tracer: tracer, scope: scope) { } @@ -129,8 +130,9 @@ public SqliteBoxMigrationRunner( /// public SqliteBoxMigrationRunner( IAmABoxMigrationCatalog catalog, - IAmARelationalDatabaseConfiguration configuration) - : this(catalog, configuration, TimeSpan.FromSeconds(30)) + IAmARelationalDatabaseConfiguration configuration, + ILoggerFactory loggerFactory) + : this(catalog, configuration, TimeSpan.FromSeconds(30), loggerFactory) { } @@ -251,7 +253,8 @@ await InsertHistoryRowAsync( for (var i = 0; i < migrations.Count; i++) { var migration = migrations[i]; - if (migration.Version <= detected) continue; + if (migration.Version <= detected) + continue; await ApplyOrSkipAsync(connection, transaction!, tableName, migration, cancellationToken); } @@ -268,7 +271,8 @@ protected override async Task RunNormalPathAsync( foreach (var migration in migrations) { - if (migration.Version <= maxVersion) continue; + if (migration.Version <= maxVersion) + continue; await ApplyOrSkipAsync(connection, transaction!, tableName, migration, cancellationToken); } diff --git a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxProvisioningExtensions.cs b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxProvisioningExtensions.cs index 8c75a66f84..feed893ef4 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxProvisioningExtensions.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxProvisioningExtensions.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -25,6 +25,7 @@ THE SOFTWARE. */ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning.Sqlite; @@ -58,14 +59,16 @@ public static BoxProvisioningOptions AddSqliteOutbox( { var catalog = sp.GetRequiredService(); var runner = new SqliteBoxMigrationRunner( - catalog, configuration, options.MigrationLockTimeout, enableWalMode, + catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), enableWalMode, tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new SqliteOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -102,14 +105,16 @@ public static BoxProvisioningOptions AddSqliteOutbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new SqliteBoxMigrationRunner( - catalog, dbConfig, options.MigrationLockTimeout, enableWalMode, + catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), enableWalMode, tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new SqliteOutboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -136,14 +141,16 @@ public static BoxProvisioningOptions AddSqliteInbox( { var catalog = sp.GetRequiredService(); var runner = new SqliteBoxMigrationRunner( - catalog, configuration, options.MigrationLockTimeout, enableWalMode, + catalog, configuration, options.MigrationLockTimeout, + sp.GetRequiredService(), enableWalMode, tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new SqliteInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), configuration, - runner); + runner, + sp.GetRequiredService()); }); }); return options; @@ -180,14 +187,16 @@ public static BoxProvisioningOptions AddSqliteInbox( binaryMessagePayload: binaryMessagePayload); var catalog = sp.GetRequiredService(); var runner = new SqliteBoxMigrationRunner( - catalog, dbConfig, options.MigrationLockTimeout, enableWalMode, + catalog, dbConfig, options.MigrationLockTimeout, + sp.GetRequiredService(), enableWalMode, tracer: sp.GetService(), scope: options.MigrationHistoryScope); return new SqliteInboxProvisioner( sp.GetRequiredService(), catalog, sp.GetRequiredService(), dbConfig, - runner); + runner, + sp.GetRequiredService()); }); }); return options; diff --git a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteInboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteInboxProvisioner.cs index 7eeaa8a9ab..a981dfbdcb 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteInboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteInboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.Sqlite; @@ -39,8 +40,9 @@ public SqliteInboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Inbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteOutboxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteOutboxProvisioner.cs index 7fff16ec26..79a8fb266c 100644 --- a/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteOutboxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteOutboxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,7 @@ THE SOFTWARE. */ #endregion using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.BoxProvisioning.Sqlite; @@ -39,8 +40,9 @@ public SqliteOutboxProvisioner( IAmABoxMigrationCatalog catalog, IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, - IAmABoxMigrationRunner migrationRunner) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox) + IAmABoxMigrationRunner migrationRunner, + ILoggerFactory loggerFactory) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, BoxType.Outbox, loggerFactory) { } diff --git a/src/Paramore.Brighter.BoxProvisioning/BoxTableName.cs b/src/Paramore.Brighter.BoxProvisioning/BoxTableName.cs index fecc726e9b..7fdcaea694 100644 --- a/src/Paramore.Brighter.BoxProvisioning/BoxTableName.cs +++ b/src/Paramore.Brighter.BoxProvisioning/BoxTableName.cs @@ -62,7 +62,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] BoxTableName? value) /// /// The to convert. /// The underlying string, or if is . - public static implicit operator string?(BoxTableName value) => value?.Value; + public static implicit operator string?(BoxTableName? value) => value?.Value; /// /// Implicitly converts a to a . diff --git a/src/Paramore.Brighter.BoxProvisioning/MigrationDescription.cs b/src/Paramore.Brighter.BoxProvisioning/MigrationDescription.cs index 805d21ff1c..526813e4a7 100644 --- a/src/Paramore.Brighter.BoxProvisioning/MigrationDescription.cs +++ b/src/Paramore.Brighter.BoxProvisioning/MigrationDescription.cs @@ -62,7 +62,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] MigrationDescription? valu /// /// The to convert. /// The underlying string, or if is . - public static implicit operator string?(MigrationDescription value) => value?.Value; + public static implicit operator string?(MigrationDescription? value) => value?.Value; /// /// Implicitly converts a to a . diff --git a/src/Paramore.Brighter.BoxProvisioning/SchemaName.cs b/src/Paramore.Brighter.BoxProvisioning/SchemaName.cs index f2aaba139a..57c8e5829f 100644 --- a/src/Paramore.Brighter.BoxProvisioning/SchemaName.cs +++ b/src/Paramore.Brighter.BoxProvisioning/SchemaName.cs @@ -70,7 +70,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] SchemaName? value) /// /// The to convert. /// The underlying string, or if is . - public static implicit operator string?(SchemaName value) => value?.Value; + public static implicit operator string?(SchemaName? value) => value?.Value; /// /// Implicitly converts a to a . diff --git a/src/Paramore.Brighter.BoxProvisioning/SourceReference.cs b/src/Paramore.Brighter.BoxProvisioning/SourceReference.cs index 7af8ffd1be..5ebe72b4cb 100644 --- a/src/Paramore.Brighter.BoxProvisioning/SourceReference.cs +++ b/src/Paramore.Brighter.BoxProvisioning/SourceReference.cs @@ -66,7 +66,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] SourceReference? value) /// /// The to convert. /// The underlying string, or if is . - public static implicit operator string?(SourceReference value) => value?.Value; + public static implicit operator string?(SourceReference? value) => value?.Value; /// /// Implicitly converts a to a . diff --git a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs index 0f69d84cae..89db9202ad 100644 --- a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs +++ b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; using Paramore.Brighter.Observability; namespace Paramore.Brighter.BoxProvisioning; @@ -114,7 +113,7 @@ public abstract class SqlBoxMigrationRunner /// chain and fresh-install DDL on each call. /// How long the per-backend UoW waits for the advisory lock /// before throwing. - /// Optional logger. Defaults to . + /// The logger. /// Optional . When supplied, /// emits a migration span on the tracer's /// . Defaults to null (no instrumentation). @@ -126,7 +125,7 @@ protected SqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, - ILogger? logger = null, + ILogger logger, IAmABrighterTracer? tracer = null, MigrationHistoryScope scope = MigrationHistoryScope.Global) { @@ -135,7 +134,7 @@ protected SqlBoxMigrationRunner( _configuration = configuration; _lockTimeout = lockTimeout; _scope = scope; - Logger = logger ?? NullLogger.Instance; + Logger = logger; Tracer = tracer; } @@ -366,7 +365,8 @@ await RunNormalPathAsync( var activity = Tracer?.ActivitySource.StartActivity( $"{BrighterSemanticConventions.BoxMigration} {tableName}", ActivityKind.Internal); - if (activity is null) return null; + if (activity is null) + return null; activity.SetTag(BrighterSemanticConventions.DbSystem, DbSystem.ToDbName()); activity.SetTag(BrighterSemanticConventions.DbTable, tableName); if (schemaName is not null) diff --git a/src/Paramore.Brighter.BoxProvisioning/SqlBoxProvisioner.cs b/src/Paramore.Brighter.BoxProvisioning/SqlBoxProvisioner.cs index 7783d2fedd..a99db26280 100644 --- a/src/Paramore.Brighter.BoxProvisioning/SqlBoxProvisioner.cs +++ b/src/Paramore.Brighter.BoxProvisioning/SqlBoxProvisioner.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.BoxProvisioning; @@ -52,10 +51,8 @@ public abstract class SqlBoxProvisioner where TConnection : DbConnection where TTransaction : DbTransaction { - // Static logger keeps the ctor surface unchanged across the 8 concrete provisioners; only - // exercised by the pre-lock-hint failure swallow below (Spec 0029 T-PERM). - private static readonly ILogger s_logger = - ApplicationLogging.CreateLogger>(); + // Logger is only exercised by the pre-lock-hint failure swallow below (Spec 0029 T-PERM). + private readonly ILogger _logger; private readonly IAmAVersionDetectingMigrationHelper _detectionHelper; private readonly IAmABoxMigrationCatalog _catalog; @@ -73,7 +70,8 @@ protected SqlBoxProvisioner( IAmABoxPayloadModeValidator payloadValidator, IAmARelationalDatabaseConfiguration configuration, IAmABoxMigrationRunner migrationRunner, - BoxType boxType) + BoxType boxType, + ILoggerFactory loggerFactory) { _detectionHelper = detectionHelper; _catalog = catalog; @@ -81,6 +79,8 @@ protected SqlBoxProvisioner( _configuration = configuration; _migrationRunner = migrationRunner; BoxType = boxType; + _logger = (loggerFactory) + .CreateLogger>(); } /// @@ -173,7 +173,7 @@ private async Task DetectTableStateAsync( } catch (DbException ex) { - s_logger.LogDebug(ex, + _logger.LogDebug(ex, "Pre-lock historyExists hint for '{Schema}.{Table}' unavailable; deferring to the runner's under-lock authoritative detection.", EffectiveSchemaName, BoxTableName); historyExists = false; @@ -202,7 +202,7 @@ private async Task DetectTableStateAsync( } catch (DbException ex) { - s_logger.LogDebug(ex, + _logger.LogDebug(ex, "Pre-lock maxVersion hint for '{Schema}.{Table}' unavailable; deferring to the runner's under-lock authoritative detection.", EffectiveSchemaName, BoxTableName); maxVersion = 0; diff --git a/src/Paramore.Brighter.BoxProvisioning/SqlScript.cs b/src/Paramore.Brighter.BoxProvisioning/SqlScript.cs index 9d2341e607..4fdd07c122 100644 --- a/src/Paramore.Brighter.BoxProvisioning/SqlScript.cs +++ b/src/Paramore.Brighter.BoxProvisioning/SqlScript.cs @@ -66,7 +66,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] SqlScript? value) /// /// The to convert. /// The underlying SQL text, or if is . - public static implicit operator string?(SqlScript value) => value?.Value; + public static implicit operator string?(SqlScript? value) => value?.Value; /// /// Implicitly converts a to a . diff --git a/src/Paramore.Brighter.Extensions.DependencyInjection/BrighterPipelineValidationExtensions.cs b/src/Paramore.Brighter.Extensions.DependencyInjection/BrighterPipelineValidationExtensions.cs index 339ca4fd2b..8fcb7a4d13 100644 --- a/src/Paramore.Brighter.Extensions.DependencyInjection/BrighterPipelineValidationExtensions.cs +++ b/src/Paramore.Brighter.Extensions.DependencyInjection/BrighterPipelineValidationExtensions.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -57,7 +57,8 @@ public static class BrighterPipelineValidationExtensions /// The builder, for fluent chaining. public static IBrighterBuilder ValidatePipelines(this IBrighterBuilder builder, bool enabled = true, bool throwOnError = true) { - if (!enabled) return builder; + if (!enabled) + return builder; builder.Services.Configure(o => o.ThrowOnError = throwOnError); @@ -72,7 +73,10 @@ public static IBrighterBuilder ValidatePipelines(this IBrighterBuilder builder, { var subscriberRegistry = sp.GetService() ?? (IAmASubscriberRegistryInspector)sp.GetRequiredService(); - var pipelineBuilder = new PipelineBuilder(subscriberRegistry, ResolveInboxConfiguration(sp)); + var pipelineBuilder = new PipelineBuilder( + subscriberRegistry, + sp.GetRequiredService(), + ResolveInboxConfiguration(sp)); var publications = ResolvePublications(sp); var subscriptions = ResolveSubscriptions(sp); @@ -81,7 +85,7 @@ public static IBrighterBuilder ValidatePipelines(this IBrighterBuilder builder, var inbox = ResolveInboxConfiguration(sp)?.Inbox; var outbox = sp.GetService()?.Outbox; - + var mapperRegistryBuilder = sp.GetService(); Func? mapperRegistryFactory = mapperRegistryBuilder != null ? () => ServiceCollectionExtensions.MessageMapperRegistry(sp) @@ -108,12 +112,16 @@ public static IBrighterBuilder ValidatePipelines(this IBrighterBuilder builder, /// The builder, for fluent chaining. public static IBrighterBuilder DescribePipelines(this IBrighterBuilder builder, bool enabled = true) { - if (!enabled) return builder; + if (!enabled) + return builder; builder.Services.TryAddSingleton(sp => { var subscriberRegistry = sp.GetService() ?? (IAmASubscriberRegistryInspector)sp.GetRequiredService(); - var pipelineBuilder = new PipelineBuilder(subscriberRegistry, ResolveInboxConfiguration(sp)); + var pipelineBuilder = new PipelineBuilder( + subscriberRegistry, + sp.GetRequiredService(), + ResolveInboxConfiguration(sp)); var logger = sp.GetRequiredService().CreateLogger(); var publications = ResolvePublications(sp); diff --git a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceCollectionExtensions.cs b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceCollectionExtensions.cs index f246f97c50..e1a32e3c1b 100644 --- a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceCollectionExtensions.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Paramore.Brighter.FeatureSwitch; -using Paramore.Brighter.Logging; using System.Text.Json; using Paramore.Brighter.CircuitBreaker; using Paramore.Brighter.JsonConverters; @@ -172,7 +171,7 @@ public static IBrighterBuilder BrighterHandlerBuilder( services.TryAdd(new ServiceDescriptor(typeof(IAmACommandProcessor), BuildCommandProcessor, ServiceLifetime.Singleton)); - var builder = new ServiceCollectionBrighterBuilder( + var builder = new ServiceCollectionBrighterBuilder( services, subscriberRegistry, mapperRegistry, @@ -195,9 +194,9 @@ public static IBrighterBuilder BrighterHandlerBuilder( // Register InMemorySchedulerFactory as the default using TryAddSingleton. // TryAddSingleton ensures these are only registered if no scheduler has been // explicitly configured via UseScheduler/UseMessageScheduler (which use AddSingleton). - var defaultSchedulerFactory = new InMemorySchedulerFactory(); - services.TryAddSingleton(defaultSchedulerFactory); - services.TryAddSingleton(defaultSchedulerFactory); + services.TryAddSingleton(); + services.TryAddSingleton(provider => provider.GetRequiredService()); + services.TryAddSingleton(provider => provider.GetRequiredService()); services.TryAddSingleton(provider => { var messageSchedulerFactory = provider.GetRequiredService(); @@ -246,7 +245,7 @@ public static IBrighterBuilder BrighterHandlerBuilder( /// The Brighter builder to allow chaining of requests public static IBrighterBuilder AddProducers( this IBrighterBuilder brighterBuilder, - Action configure, + Action? configure, ServiceLifetime serviceLifetime = ServiceLifetime.Transient) { if (brighterBuilder is null) @@ -260,8 +259,8 @@ public static IBrighterBuilder AddProducers( if (busConfiguration.UseRpc && busConfiguration.ReplyQueueSubscriptions == null) throw new ConfigurationException("If the you configure RPC, you must configure the ReplyQueueSubscriptions"); - - brighterBuilder.Services.TryAddSingleton(); + + brighterBuilder.Services.TryAddSingleton(); brighterBuilder.Services.TryAddSingleton(busConfiguration.ProducerRegistry); //default to using System Transactions if nothing provided, so we always technically can share the outbox transaction @@ -291,7 +290,7 @@ public static IBrighterBuilder AddProducers( if (busConfiguration.ConnectionProvider != null) RegisterConnectionAndTransactionProvider(brighterBuilder, busConfiguration.ConnectionProvider, transactionProvider, serviceLifetime); - + //we always need an outbox in case of producer callbacks var outbox = busConfiguration.Outbox ?? CreateDefaultOutbox(busConfiguration); @@ -341,10 +340,10 @@ public static IBrighterBuilder AddProducers( if (busConfiguration.UseRpc) brighterBuilder.Services.TryAddSingleton(new UseRpc(busConfiguration.UseRpc, busConfiguration.ReplyQueueSubscriptions!)); - + brighterBuilder.Services.TryAddSingleton(busConfiguration); brighterBuilder.ResiliencePolicyRegistry ??= new ResiliencePipelineRegistry().AddBrighterDefault(); - + brighterBuilder.Services.TryAdd(new ServiceDescriptor(typeof(IAmAnOutboxProducerMediator), (serviceProvider) => BuildOutBoxProducerMediator( serviceProvider, transactionType, busConfiguration, brighterBuilder.ResiliencePolicyRegistry, outbox @@ -404,7 +403,7 @@ public static IBrighterBuilder AddProducers( return busConfiguration; }); - brighterBuilder.Services.TryAddSingleton(); + brighterBuilder.Services.TryAddSingleton(); // Register producer registry with deferred resolution brighterBuilder.Services.TryAddSingleton(sp => @@ -516,7 +515,7 @@ public static IBrighterBuilder UsePublicationFinder(this IBrighterBuilder bui builder.Services.Add(new ServiceDescriptor(typeof(IAmAPublicationFinder), typeof(T), lifetime)); return builder; } - + /// /// Set a default /// @@ -530,37 +529,37 @@ public static IBrighterBuilder UsePublicationFinder(this IBrighterBuilder bui builder.Services.AddSingleton(instance); return builder; } - - /// - /// An external request scheduler factory - /// - /// The builder. - /// The message scheduler factory - /// - public static IBrighterBuilder UseScheduler(this IBrighterBuilder builder, T factory) - where T : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory - { - builder - .UseRequestScheduler(factory) - .UseMessageScheduler(factory); - return builder; - } - - /// - /// An external request scheduler factory - /// - /// The builder. - /// The message scheduler factory - /// - public static IBrighterBuilder UseScheduler(this IBrighterBuilder builder, Func factory) - where T : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory - { - builder - .UseRequestScheduler(provider => factory(provider)) - .UseMessageScheduler(provider => factory(provider)); - return builder; - } - + + /// + /// An external request scheduler factory + /// + /// The builder. + /// The message scheduler factory + /// + public static IBrighterBuilder UseScheduler(this IBrighterBuilder builder, T factory) + where T : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory + { + builder + .UseRequestScheduler(factory) + .UseMessageScheduler(factory); + return builder; + } + + /// + /// An external request scheduler factory + /// + /// The builder. + /// The message scheduler factory + /// + public static IBrighterBuilder UseScheduler(this IBrighterBuilder builder, Func factory) + where T : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory + { + builder + .UseRequestScheduler(provider => factory(provider)) + .UseMessageScheduler(provider => factory(provider)); + return builder; + } + /// /// An external request scheduler factory /// @@ -584,7 +583,7 @@ public static IBrighterBuilder UseRequestScheduler(this IBrighterBuilder builder }); return builder; } - + /// /// An external request scheduler factory /// @@ -596,7 +595,7 @@ public static IBrighterBuilder UseRequestScheduler(this IBrighterBuilder builder builder.Services.AddSingleton(factory); return builder; } - + /// /// An external message scheduler factory /// @@ -616,7 +615,7 @@ public static IBrighterBuilder UseMessageScheduler(this IBrighterBuilder builder builder.Services.TryAddSingleton(provide => (IAmAMessageSchedulerSync)provide.GetRequiredService()); return builder; } - + /// /// An external message scheduler factory /// @@ -628,7 +627,7 @@ public static IBrighterBuilder UseMessageScheduler(this IBrighterBuilder builder builder.Services.AddSingleton(factory); return builder; } - + private static INeedInstrumentation AddEventBus( IServiceProvider provider, INeedMessaging messagingBuilder, @@ -636,7 +635,7 @@ private static INeedInstrumentation AddEventBus( { var eventBus = provider.GetService(); var hasEventBus = eventBus != null; - + var eventBusConfiguration = provider.GetService(); var serviceActivatorOptions = provider.GetService(); @@ -652,7 +651,8 @@ private static INeedInstrumentation AddEventBus( INeedInstrumentation? instrumentationBuilder = null; bool useRpc = useRequestResponse != null && useRequestResponse.RPC; - if (!hasEventBus) instrumentationBuilder = messagingBuilder.NoExternalBus(); + if (!hasEventBus) + instrumentationBuilder = messagingBuilder.NoExternalBus(); if (hasEventBus && !useRpc) { @@ -683,7 +683,7 @@ private static INeedInstrumentation AddEventBus( { if (policyRegistry == null) throw new ConfigurationException("You must add a policy registry, to which defaults can be added"); - + #pragma warning disable CS0618 // Type or member is obsolete if (!policyRegistry.ContainsKey(CommandProcessor.RETRYPOLICY)) throw new ConfigurationException( @@ -699,11 +699,9 @@ private static INeedInstrumentation AddEventBus( private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider provider) { - var loggerFactory = provider.GetService(); - //if not supplied, use the default logger factory, which has no providers - if (loggerFactory != null) - ApplicationLogging.LoggerFactory = loggerFactory; - + //Resolve the container's logger factory and flow it through the builder as an instance, + //rather than copying it into a process-wide static (which would be disposed with the container). + var loggerFactory = provider.GetRequiredService(); var options = provider.GetRequiredService(); var subscriberRegistry = provider.GetRequiredService(); @@ -718,7 +716,7 @@ private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider provi if (featureSwitchRegistry != null) handlerBuilder = handlerBuilder.ConfigureFeatureSwitches(featureSwitchRegistry); - + var pollyBuilder = handlerBuilder.Handlers(handlerConfiguration); options.ResiliencePipelineRegistry ??= new ResiliencePipelineRegistry().AddBrighterDefault(); @@ -726,13 +724,14 @@ private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider provi var messagingBuilder = pollyBuilder.Resilience(options.ResiliencePipelineRegistry, options.PolicyRegistry); #pragma warning restore CS0618 // Type or member is obsolete - + var command = AddEventBus(provider, messagingBuilder, useRequestResponse) .ConfigureInstrumentation(provider.GetService(), options.InstrumentationOptions) .RequestContextFactory(provider.GetRequiredService()) .RequestSchedulerFactory(provider.GetRequiredService()) + .ConfigureLogging(loggerFactory) .Build(); - + var eventBusConfiguration = provider.GetService(); var producerRegistry = provider.GetService(); var messageSchedulerFactory = eventBusConfiguration?.MessageSchedulerFactory ?? provider.GetRequiredService(); @@ -741,13 +740,13 @@ private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider provi return command; } - + private static IAmAnOutboxProducerMediator? BuildOutBoxProducerMediator( IServiceProvider serviceProvider, Type transactionType, ProducersConfiguration busConfiguration, ResiliencePipelineRegistry? resiliencePipelineRegistry, - IAmAnOutbox outbox) + IAmAnOutbox outbox) { //Because the bus has specialized types as members, we need to create the bus type dynamically //again to prevent someone configuring Brighter from having to pass generic types @@ -766,6 +765,7 @@ private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider provi TransformFactoryAsync(serviceProvider), Tracer(serviceProvider), PublicationFinder(serviceProvider), + serviceProvider.GetRequiredService(), outbox, OutboxCircuitBreaker(serviceProvider), RequestContextFactory(serviceProvider), @@ -819,23 +819,23 @@ public static MessageMapperRegistry MessageMapperRegistry(IServiceProvider provi { messageMapperRegistry.RegisterAsync(messageMapper.Key, messageMapper.Value); } - + return messageMapperRegistry; } - private static void RegisterConnectionAndTransactionProvider(IBrighterBuilder brighterBuilder, + private static void RegisterConnectionAndTransactionProvider(IBrighterBuilder brighterBuilder, Type connectionProvider, Type transactionProvider, ServiceLifetime serviceLifetime) { var connectionProviderInterface = GetConnectionProviderInterface(connectionProvider); - if(connectionProviderInterface != null) + if (connectionProviderInterface != null) { brighterBuilder.Services.TryAdd(new ServiceDescriptor(connectionProviderInterface, connectionProvider, serviceLifetime)); - - var transactionProviderInterface = GetTransactionInterface(transactionProvider, connectionProviderInterface ); - if(transactionProviderInterface != null) + + var transactionProviderInterface = GetTransactionInterface(transactionProvider, connectionProviderInterface); + if (transactionProviderInterface != null) { brighterBuilder.Services.TryAdd(new ServiceDescriptor(transactionProviderInterface, transactionProvider, serviceLifetime)); } @@ -848,32 +848,32 @@ private static void RegisterConnectionAndTransactionProvider(IBrighterBuilder br var interfaces = GetInterfaces(type); foreach (var @interface in interfaces) { - if (typeof(IAmAConnectionProvider).IsAssignableFrom(@interface) - && !typeof(IAmABoxTransactionProvider).IsAssignableFrom(@interface)) + if (typeof(IAmAConnectionProvider).IsAssignableFrom(@interface) + && !typeof(IAmABoxTransactionProvider).IsAssignableFrom(@interface)) { return @interface; } } - + return null; } - + static Type? GetTransactionInterface(Type type, Type connectionProvider) { // All Brighter transaction provider interface must be extended from connection provider and IAmABoxTransactionProvider var interfaces = GetInterfaces(type); foreach (var @interface in interfaces) { - if (connectionProvider.IsAssignableFrom(@interface) - && typeof(IAmABoxTransactionProvider).IsAssignableFrom(@interface)) + if (connectionProvider.IsAssignableFrom(@interface) + && typeof(IAmABoxTransactionProvider).IsAssignableFrom(@interface)) { return @interface; } } - + return null; } - + static IEnumerable GetInterfaces(Type type) { var interfaces = type.GetInterfaces().AsEnumerable(); @@ -901,7 +901,7 @@ public static IAmAPublicationFinder PublicationFinder(IServiceProvider provider) { return provider.GetRequiredService(); } - + /// /// Creates the default when no explicit outbox is provided. /// Uses when set; @@ -927,7 +927,7 @@ private static InMemoryOutbox CreateDefaultOutbox(IAmProducersConfiguration busC { return serviceProvider.GetService(); } - + private static IAmAnOutboxCircuitBreaker? OutboxCircuitBreaker(IServiceProvider serviceProvider) { return serviceProvider.GetService(); @@ -956,7 +956,7 @@ public static ServiceProviderTransformerFactoryAsync TransformFactoryAsync(IServ { return new ServiceProviderTransformerFactoryAsync(provider); } - + /// /// Adds a singleton instance of an external luggage (claim check) store provider to the Brighter framework. /// This method is used when you have a pre-initialized instance of your storage provider. @@ -975,7 +975,7 @@ public static IBrighterBuilder UseExternalLuggageStore(this IBri return builder; } - + /// /// Adds a singleton instance of an external luggage (claim check) store provider to the Brighter framework. /// This method is used when you have a pre-initialized instance of your storage provider. @@ -995,7 +995,7 @@ public static IBrighterBuilder UseExternalLuggageStore(this IBri return builder; } - + /// /// Adds a singleton instance of a luggage (claim check) store provider to the Brighter framework, /// resolved via a factory function. This method is used when the storage provider @@ -1013,7 +1013,7 @@ public static IBrighterBuilder UseExternalLuggageStore(this IBri { builder.Services.AddSingleton(storeProvider) .RegisterLuggageStore(); - + return builder; } diff --git a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderLifetimeScope.cs b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderLifetimeScope.cs index 8b05deda7a..a104d859fb 100644 --- a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderLifetimeScope.cs +++ b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderLifetimeScope.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2022 Ian Cooper @@ -30,7 +30,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Extensions.DependencyInjection { @@ -41,7 +40,7 @@ namespace Paramore.Brighter.Extensions.DependencyInjection /// internal sealed partial class ServiceProviderLifetimeScope : IDisposable { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; private readonly ServiceLifetime _lifetime; @@ -81,6 +80,7 @@ internal sealed partial class ServiceProviderLifetimeScope : IDisposable public ServiceProviderLifetimeScope(IServiceProvider serviceProvider, ServiceLifetime lifetime, bool isolateTransientScopes = true) { _serviceProvider = serviceProvider; + _logger = serviceProvider.GetRequiredService().CreateLogger(); _lifetime = lifetime; _isolateTransientScopes = isolateTransientScopes; } @@ -465,7 +465,8 @@ public void Dispose() //The exchange also publishes _disposed before we drain, so a concurrent GetOrCreate either //fails its guard or, if it slipped past, sees it on its post-add re-check and cleans up the //scope it just tracked. - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; try { @@ -481,8 +482,9 @@ public void Dispose() //best-effort cleanup: a throw must not skip the remaining scopes, but it is logged //(a repeated failure on this terminal teardown path means an unbounded leak) rather //than swallowed silently, matching the other release paths in this change. - try { DisposeScope(scope); } - catch (Exception e) { Log.FailedToDisposeScope(s_logger, e); } + try + { DisposeScope(scope); } + catch (Exception e) { Log.FailedToDisposeScope(_logger, e); } } } finally @@ -494,8 +496,9 @@ public void Dispose() if (rootScope != null) { //logged for the same reason as the transient drain above — best-effort, but not silent - try { DisposeScope(rootScope); } - catch (Exception e) { Log.FailedToDisposeScope(s_logger, e); } + try + { DisposeScope(rootScope); } + catch (Exception e) { Log.FailedToDisposeScope(_logger, e); } } _scopedInstances.Clear(); } diff --git a/src/Paramore.Brighter.Inbox.MsSql/MsSqlInbox.cs b/src/Paramore.Brighter.Inbox.MsSql/MsSqlInbox.cs index ba36d9163d..3be34295bc 100644 --- a/src/Paramore.Brighter.Inbox.MsSql/MsSqlInbox.cs +++ b/src/Paramore.Brighter.Inbox.MsSql/MsSqlInbox.cs @@ -26,7 +26,7 @@ THE SOFTWARE. */ using System; using System.Data; using Microsoft.Data.SqlClient; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MsSql; using Paramore.Brighter.Observability; @@ -45,9 +45,10 @@ public class MsSqlInbox : RelationalDatabaseInbox /// /// The configuration. /// The Connection Provider. - public MsSqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) + /// The logger to use. + public MsSqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILogger logger) : base(DbSystem.MsSql, configuration, connectionProvider, - new MsSqlQueries(), ApplicationLogging.CreateLogger()) + new MsSqlQueries(), logger) { } @@ -55,8 +56,9 @@ public MsSqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelatio /// Initializes a new instance of the class. /// /// The configuration. - public MsSqlInbox(IAmARelationalDatabaseConfiguration configuration) : this(configuration, - new MsSqlConnectionProvider(configuration)) + /// The logger to use. + public MsSqlInbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) : this(configuration, + new MsSqlConnectionProvider(configuration), logger) { } diff --git a/src/Paramore.Brighter.Inbox.MySql/MySqlInbox.cs b/src/Paramore.Brighter.Inbox.MySql/MySqlInbox.cs index 4fda383eb8..fbf0c22c32 100644 --- a/src/Paramore.Brighter.Inbox.MySql/MySqlInbox.cs +++ b/src/Paramore.Brighter.Inbox.MySql/MySqlInbox.cs @@ -25,8 +25,8 @@ THE SOFTWARE. */ using System; using System.Data; +using Microsoft.Extensions.Logging; using MySqlConnector; -using Paramore.Brighter.Logging; using Paramore.Brighter.MySql; using Paramore.Brighter.Observability; @@ -44,9 +44,10 @@ public class MySqlInbox : RelationalDatabaseInbox /// /// The configuration. /// The Connection Provider. - public MySqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) - : base(DbSystem.MySql, configuration, connectionProvider, - new MySqlQueries(), ApplicationLogging.CreateLogger()) + /// The logger to use. + public MySqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILogger logger) + : base(DbSystem.MySql, configuration, connectionProvider, + new MySqlQueries(), logger) { } @@ -54,8 +55,9 @@ public MySqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelatio /// Initializes a new instance of the class. /// /// The configuration. - public MySqlInbox(IAmARelationalDatabaseConfiguration configuration) : this(configuration, - new MySqlConnectionProvider(configuration)) + /// The logger to use. + public MySqlInbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) : this(configuration, + new MySqlConnectionProvider(configuration), logger) { } @@ -73,7 +75,7 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, obj protected override IDbDataParameter CreateJsonSqlParameter(string parameterName, object? value) { - return new MySqlParameter{ParameterName = parameterName, MySqlDbType = MySqlDbType.JSON, Value = value ?? DBNull.Value }; + return new MySqlParameter { ParameterName = parameterName, MySqlDbType = MySqlDbType.JSON, Value = value ?? DBNull.Value }; } } diff --git a/src/Paramore.Brighter.Inbox.Postgres/PostgreSqlInbox.cs b/src/Paramore.Brighter.Inbox.Postgres/PostgreSqlInbox.cs index 3c01e7e163..447d9faaad 100644 --- a/src/Paramore.Brighter.Inbox.Postgres/PostgreSqlInbox.cs +++ b/src/Paramore.Brighter.Inbox.Postgres/PostgreSqlInbox.cs @@ -26,9 +26,9 @@ THE SOFTWARE. */ using System; using System.Data; using System.Linq; +using Microsoft.Extensions.Logging; using Npgsql; using NpgsqlTypes; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.PostgreSql; @@ -36,14 +36,14 @@ namespace Paramore.Brighter.Inbox.Postgres; public class PostgreSqlInbox : RelationalDatabaseInbox { - public PostgreSqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) - : base(DbSystem.Postgresql, configuration, connectionProvider, - new PostgreSqlQueries(), ApplicationLogging.CreateLogger()) + public PostgreSqlInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILogger logger) + : base(DbSystem.Postgresql, configuration, connectionProvider, + new PostgreSqlQueries(), logger) { } - public PostgreSqlInbox(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new PostgreSqlConnectionProvider(configuration)) + public PostgreSqlInbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new PostgreSqlConnectionProvider(configuration), logger) { } @@ -62,7 +62,7 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, obj protected override IDbDataParameter CreateJsonSqlParameter(string parameterName, object? value) { - return new NpgsqlParameter { ParameterName = parameterName, NpgsqlDbType = DatabaseConfiguration.BinaryMessagePayload ? NpgsqlDbType.Jsonb : NpgsqlDbType.Json,Value = value ?? DBNull.Value }; + return new NpgsqlParameter { ParameterName = parameterName, NpgsqlDbType = DatabaseConfiguration.BinaryMessagePayload ? NpgsqlDbType.Jsonb : NpgsqlDbType.Json, Value = value ?? DBNull.Value }; } /// diff --git a/src/Paramore.Brighter.Inbox.Spanner/SpannerInboxAsync.cs b/src/Paramore.Brighter.Inbox.Spanner/SpannerInboxAsync.cs index 888d183027..5a05bdedca 100644 --- a/src/Paramore.Brighter.Inbox.Spanner/SpannerInboxAsync.cs +++ b/src/Paramore.Brighter.Inbox.Spanner/SpannerInboxAsync.cs @@ -3,7 +3,7 @@ using System.Data.Common; using Google.Cloud.Spanner.Data; using Grpc.Core; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Spanner; @@ -29,16 +29,17 @@ namespace Paramore.Brighter.Inbox.Spanner; /// public class SpannerInboxAsync( IAmARelationalDatabaseConfiguration configuration, - IAmARelationalDbConnectionProvider connectionProvider) + IAmARelationalDbConnectionProvider connectionProvider, + ILogger logger) : RelationalDatabaseInbox(DbSystem.Spanner, configuration, connectionProvider, - new SpannerSqlQueries(), ApplicationLogging.CreateLogger()) + new SpannerSqlQueries(), logger) { - public SpannerInboxAsync(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new SpannerConnectionProvider(configuration)) + public SpannerInboxAsync(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new SpannerConnectionProvider(configuration), logger) { - + } - + /// protected override DbCommand CreateCommand(DbConnection connection, string sqlText, int outBoxTimeout, params IDbDataParameter[] parameters) @@ -88,11 +89,11 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, obj protected override IDbDataParameter CreateJsonSqlParameter(string parameterName, object? value) { - return new SpannerParameter + return new SpannerParameter { - ParameterName = parameterName, + ParameterName = parameterName, SpannerDbType = SpannerDbType.Json, - Value = value ?? DBNull.Value + Value = value ?? DBNull.Value }; } diff --git a/src/Paramore.Brighter.Inbox.Sqlite/SqliteInbox.cs b/src/Paramore.Brighter.Inbox.Sqlite/SqliteInbox.cs index 28b177925f..b84d05e919 100644 --- a/src/Paramore.Brighter.Inbox.Sqlite/SqliteInbox.cs +++ b/src/Paramore.Brighter.Inbox.Sqlite/SqliteInbox.cs @@ -26,7 +26,7 @@ THE SOFTWARE. */ using System; using System.Data; using Microsoft.Data.Sqlite; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Sqlite; @@ -45,9 +45,10 @@ public class SqliteInbox : RelationalDatabaseInbox /// /// The connection provider for the database. /// The configuration for the database. - public SqliteInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) - : base(DbSystem.Sqlite, configuration, connectionProvider, - new SqliteQueries(), ApplicationLogging.CreateLogger()) + /// The logger to use. + public SqliteInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILogger logger) + : base(DbSystem.Sqlite, configuration, connectionProvider, + new SqliteQueries(), logger) { } @@ -55,8 +56,9 @@ public SqliteInbox(IAmARelationalDatabaseConfiguration configuration, IAmARelati /// Initializes a new instance of the class. /// /// The configuration for the database. - public SqliteInbox(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new SqliteConnectionProvider(configuration)) + /// The logger to use. + public SqliteInbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new SqliteConnectionProvider(configuration), logger) { } diff --git a/src/Paramore.Brighter.Locking.Azure/AzureBlobLockingProvider.cs b/src/Paramore.Brighter.Locking.Azure/AzureBlobLockingProvider.cs index 30031251f4..305b4ecf84 100644 --- a/src/Paramore.Brighter.Locking.Azure/AzureBlobLockingProvider.cs +++ b/src/Paramore.Brighter.Locking.Azure/AzureBlobLockingProvider.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2024 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using Azure.Storage.Blobs; using Azure.Storage.Blobs.Specialized; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Locking.Azure; @@ -35,12 +34,13 @@ namespace Paramore.Brighter.Locking.Azure; /// The Azure Blob provider for distributed locks /// /// -public class AzureBlobLockingProvider(AzureBlobLockingProviderOptions options) : IDistributedLock +/// +public class AzureBlobLockingProvider(AzureBlobLockingProviderOptions options, ILoggerFactory loggerFactory) : IDistributedLock { private readonly BlobContainerClient _containerClient = new BlobContainerClient(options.BlobContainerUri, options.TokenCredential); - private readonly ILogger _logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// /// Attempt to obtain a lock on a resource diff --git a/src/Paramore.Brighter.Locking.DynamoDB.V4/DynamoDbLockingProvider.cs b/src/Paramore.Brighter.Locking.DynamoDB.V4/DynamoDbLockingProvider.cs index 4ba0e47da8..ba2aa5a59e 100644 --- a/src/Paramore.Brighter.Locking.DynamoDB.V4/DynamoDbLockingProvider.cs +++ b/src/Paramore.Brighter.Locking.DynamoDB.V4/DynamoDbLockingProvider.cs @@ -24,7 +24,6 @@ THE SOFTWARE. */ using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Locking.DynamoDB.V4; @@ -34,18 +33,19 @@ public partial class DynamoDbLockingProvider : IDistributedLock private readonly DynamoDbLockingProviderOptions _options; private readonly TimeProvider _timeProvider; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; - public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options) - :this(dynamoDb, options, TimeProvider.System) + public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, ILoggerFactory loggerFactory) + : this(dynamoDb, options, TimeProvider.System, loggerFactory) { } - public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, TimeProvider timeProvider) + public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, TimeProvider timeProvider, ILoggerFactory loggerFactory) { _dynamoDb = dynamoDb; _options = options; _timeProvider = timeProvider; + _logger = loggerFactory.CreateLogger(); } /// @@ -64,11 +64,11 @@ public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProvider } catch (ConditionalCheckFailedException) { - Log.UnableToObtainLockForResource(s_logger, resource); + Log.UnableToObtainLockForResource(_logger, resource); return null; } - Log.ObtainedLockForResource(s_logger, lockId, resource); + Log.ObtainedLockForResource(_logger, lockId, resource); return lockId; } @@ -89,7 +89,7 @@ public async Task ReleaseLockAsync(string resource, string lockId, CancellationT } catch (ConditionalCheckFailedException) { - Log.UnableToReleaseLockForResource(s_logger, lockId, resource); + Log.UnableToReleaseLockForResource(_logger, lockId, resource); } } } diff --git a/src/Paramore.Brighter.Locking.DynamoDB/DynamoDbLockingProvider.cs b/src/Paramore.Brighter.Locking.DynamoDB/DynamoDbLockingProvider.cs index 4ee1080d4c..53f0a9db28 100644 --- a/src/Paramore.Brighter.Locking.DynamoDB/DynamoDbLockingProvider.cs +++ b/src/Paramore.Brighter.Locking.DynamoDB/DynamoDbLockingProvider.cs @@ -23,7 +23,6 @@ THE SOFTWARE. */ using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Locking.DynamoDb { @@ -33,18 +32,19 @@ public partial class DynamoDbLockingProvider : IDistributedLock private readonly DynamoDbLockingProviderOptions _options; private readonly TimeProvider _timeProvider; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; - public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options) - :this(dynamoDb, options, TimeProvider.System) + public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, ILoggerFactory loggerFactory) + : this(dynamoDb, options, TimeProvider.System, loggerFactory) { } - public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, TimeProvider timeProvider) + public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, TimeProvider timeProvider, ILoggerFactory loggerFactory) { _dynamoDb = dynamoDb; _options = options; _timeProvider = timeProvider; + _logger = loggerFactory.CreateLogger(); } /// @@ -63,11 +63,11 @@ public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProvider } catch (ConditionalCheckFailedException) { - Log.UnableToObtainLockForResource(s_logger, resource); + Log.UnableToObtainLockForResource(_logger, resource); return null; } - Log.ObtainedLockForResource(s_logger, lockId, resource); + Log.ObtainedLockForResource(_logger, lockId, resource); return lockId; } @@ -88,7 +88,7 @@ public async Task ReleaseLockAsync(string resource, string lockId, CancellationT } catch (ConditionalCheckFailedException) { - Log.UnableToReleaseLockForResource(s_logger, lockId, resource); + Log.UnableToReleaseLockForResource(_logger, lockId, resource); } } } diff --git a/src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs b/src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs index 175ca9f14f..fed97972f0 100644 --- a/src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs +++ b/src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Data.Common; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MsSql; namespace Paramore.Brighter.Locking.MsSql; @@ -37,12 +36,13 @@ namespace Paramore.Brighter.Locking.MsSql; /// The Microsoft Sql Server Locking Provider /// /// The Sql Server connection Provider -public class MsSqlLockingProvider(MsSqlConnectionProvider connectionProvider) +/// The factory used to create the logger for this provider +public class MsSqlLockingProvider(MsSqlConnectionProvider connectionProvider, ILoggerFactory loggerFactory) : IDistributedLock, IAsyncDisposable, IDisposable { private readonly ConcurrentDictionary _connections = new(); - private readonly ILogger _logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// /// Attempt to obtain a lock on a resource diff --git a/src/Paramore.Brighter.Locking.MySql/MySqlLockingProvider.cs b/src/Paramore.Brighter.Locking.MySql/MySqlLockingProvider.cs index ad9a902327..acc4955be8 100644 --- a/src/Paramore.Brighter.Locking.MySql/MySqlLockingProvider.cs +++ b/src/Paramore.Brighter.Locking.MySql/MySqlLockingProvider.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MySqlConnector; -using Paramore.Brighter.Logging; using Paramore.Brighter.MySql; namespace Paramore.Brighter.Locking.MySql; @@ -17,9 +16,10 @@ namespace Paramore.Brighter.Locking.MySql; /// The MySQL Locking Provider /// /// The MySQL connection Provider. -public class MySqlLockingProvider(MySqlConnectionProvider connectionProvider) : IDistributedLock, IAsyncDisposable +/// The factory used to create the logger for this provider. +public class MySqlLockingProvider(MySqlConnectionProvider connectionProvider, ILoggerFactory loggerFactory) : IDistributedLock, IAsyncDisposable { - private readonly ILogger _logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private readonly ConcurrentDictionary _connections = new(); /// @@ -49,7 +49,7 @@ public class MySqlLockingProvider(MySqlConnectionProvider connectionProvider) : command.Parameters.Add(new MySqlParameter("@TIMEOUT", MySqlDbType.UInt32) { - Value = 1 + Value = 1 }); var result = await command.ExecuteScalarAsync(cancellationToken) ?? -1; @@ -88,7 +88,7 @@ public async Task ReleaseLockAsync(string resource, string lockId, CancellationT await command.ExecuteNonQueryAsync(cancellationToken); - + #if NETSTANDARD2_0 connection.Close(); connection.Dispose(); @@ -137,7 +137,8 @@ private static string GetSafeName(string name) => MaxNameLength, convertToValidName: s => { - if (s.Length == 0) { return "__empty__"; } + if (s.Length == 0) + { return "__empty__"; } return s.ToLowerInvariant(); }, diff --git a/src/Paramore.Brighter.Mediator/InMemoryJobChannel.cs b/src/Paramore.Brighter.Mediator/InMemoryJobChannel.cs index 4b3314ab2b..7f2448644b 100644 --- a/src/Paramore.Brighter.Mediator/InMemoryJobChannel.cs +++ b/src/Paramore.Brighter.Mediator/InMemoryJobChannel.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Mediator; @@ -41,7 +40,7 @@ public enum FullChannelStrategy /// Wait for space to become available in the channel. /// Wait, - + /// /// Drop the oldest item in the channel to make space. /// @@ -55,17 +54,20 @@ public enum FullChannelStrategy public class InMemoryJobChannel : IAmAJobChannel { private readonly Channel> _channel; - - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + + private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// The maximum number of jobs the channel can hold. /// The strategy to use when the channel is full. + /// The factory used to create the logger for this channel. /// Thrown when the bounded capacity is less than or equal to 0. - public InMemoryJobChannel(int boundedCapacity = 100, FullChannelStrategy fullChannelStrategy = FullChannelStrategy.Wait) + public InMemoryJobChannel(ILoggerFactory loggerFactory, int boundedCapacity = 100, FullChannelStrategy fullChannelStrategy = FullChannelStrategy.Wait) { + _logger = loggerFactory.CreateLogger>(); + if (boundedCapacity <= 0) throw new System.ArgumentOutOfRangeException(nameof(boundedCapacity), "Bounded capacity must be greater than 0"); @@ -86,10 +88,10 @@ public InMemoryJobChannel(int boundedCapacity = 100, FullChannelStrategy fullCha /// A token to monitor for cancellation requests. /// A task that represents the asynchronous dequeue operation. The task result contains the dequeued job. public async Task?> DequeueJobAsync(CancellationToken cancellationToken = default(CancellationToken)) - { + { Job? item = null; while (await _channel.Reader.WaitToReadAsync(cancellationToken)) - while (_channel.Reader.TryRead(out item)) + while (_channel.Reader.TryRead(out item)) return item; return item; @@ -114,7 +116,7 @@ public bool IsClosed() { return _channel.Reader.Completion.IsCompleted; } - + /// /// This is mainly useful for help with testing, to stop the channel /// diff --git a/src/Paramore.Brighter.Mediator/InMemoryStateStoreAsync.cs b/src/Paramore.Brighter.Mediator/InMemoryStateStoreAsync.cs index 91ea05ae1e..5eef633dfd 100644 --- a/src/Paramore.Brighter.Mediator/InMemoryStateStoreAsync.cs +++ b/src/Paramore.Brighter.Mediator/InMemoryStateStoreAsync.cs @@ -29,7 +29,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Mediator; @@ -41,15 +40,16 @@ public class InMemoryStateStoreAsync : IAmAStateStoreAsync private readonly ConcurrentDictionary _jobs = new(); private readonly TimeProvider _timeProvider; private DateTimeOffset _sinceTime; - - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + + private readonly ILogger _logger; /// /// Represents an in-memory store for jobs. /// - public InMemoryStateStoreAsync(TimeProvider? timeProvider = null) + public InMemoryStateStoreAsync(ILoggerFactory loggerFactory, TimeProvider? timeProvider = null) { - _timeProvider = timeProvider ?? TimeProvider.System; + _timeProvider = timeProvider ?? TimeProvider.System; + _logger = loggerFactory.CreateLogger(); } /// @@ -63,9 +63,10 @@ public InMemoryStateStoreAsync(TimeProvider? timeProvider = null) var dueJobs = _jobs.Values .Where(job => { - if (job is null || !job.IsScheduled) return false; + if (job is null || !job.IsScheduled) + return false; _sinceTime = _timeProvider.GetUtcNow().Subtract(jobAge); - return job.DueTime > _sinceTime; + return job.DueTime > _sinceTime; }) .ToList(); @@ -90,7 +91,7 @@ public InMemoryStateStoreAsync(TimeProvider? timeProvider = null) tcs.SetResult(job); return tcs.Task; } - + /// /// Saves the job asynchronously. /// @@ -100,9 +101,11 @@ public InMemoryStateStoreAsync(TimeProvider? timeProvider = null) /// A task that represents the asynchronous save operation. public Task SaveJobAsync(Job? job, CancellationToken cancellationToken = default(CancellationToken)) { - if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled(cancellationToken); - if (job is null) return Task.CompletedTask; + if (job is null) + return Task.CompletedTask; try { @@ -111,7 +114,7 @@ public InMemoryStateStoreAsync(TimeProvider? timeProvider = null) } catch (Exception e) { - s_logger.LogError($"Error saving job {job.Id} to in-memory store: {e.Message}"); + _logger.LogError($"Error saving job {job.Id} to in-memory store: {e.Message}"); return Task.FromException(e); } } diff --git a/src/Paramore.Brighter.Mediator/Runner.cs b/src/Paramore.Brighter.Mediator/Runner.cs index c5e9a41df3..65e7a76857 100644 --- a/src/Paramore.Brighter.Mediator/Runner.cs +++ b/src/Paramore.Brighter.Mediator/Runner.cs @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Mediator; @@ -43,7 +42,7 @@ public class Runner private readonly Scheduler _scheduler; private readonly string _runnerName = Uuid.New().ToString("N"); - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -52,12 +51,14 @@ public class Runner /// The job store to save job states. /// The command processor to handle commands. /// The scheduler which allows us to queue work that should be deferred - public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAmACommandProcessor commandProcessor, Scheduler scheduler) + /// The factory used to create the logger for this runner. + public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAmACommandProcessor commandProcessor, Scheduler scheduler, ILoggerFactory loggerFactory) { _channel = channel; _stateStore = stateStore; _commandProcessor = commandProcessor; _scheduler = scheduler; + _logger = loggerFactory.CreateLogger>(); } /// @@ -67,7 +68,7 @@ public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAm /// A task that completes when the job processing loop exits (via cancellation or channel closure). public async Task RunAsync(CancellationToken cancellationToken = default(CancellationToken)) { - s_logger.LogInformation("Starting runner {RunnerName}", _runnerName); + _logger.LogInformation("Starting runner {RunnerName}", _runnerName); try { @@ -75,7 +76,7 @@ public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAm } finally { - s_logger.LogInformation("Finished runner {RunnerName}", _runnerName); + _logger.LogInformation("Finished runner {RunnerName}", _runnerName); } } @@ -83,16 +84,16 @@ public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAm { if (job is null) return; - - s_logger.LogInformation("Executing job {JobId} on runner {RunnerName}", job.Id, _runnerName); - + + _logger.LogInformation("Executing job {JobId} on runner {RunnerName}", job.Id, _runnerName); + job.State = JobState.Running; await _stateStore.SaveJobAsync(job, cancellationToken); var step = job.CurrentStep(); while (step is not null) { - s_logger.LogInformation("Step is {StepName} with state {StepStste}", step.Name, step.State); + _logger.LogInformation("Step is {StepName} with state {StepStste}", step.Name, step.State); if (step.State == StepState.Queued) { await step.ExecuteAsync(_stateStore, _commandProcessor, _scheduler, cancellationToken); @@ -101,19 +102,19 @@ public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAm //if the job has a pending step, finish execution of this job. if (job.State == JobState.Waiting) break; - + //assume execute has advanced he step, if you your step loops endlessly it has not advanced the step!! step = job.CurrentStep(); - s_logger.LogInformation( - "Next step is {StepName} with state {StepState}", - step is not null ? step.Name : "flow ends", + _logger.LogInformation( + "Next step is {StepName} with state {StepState}", + step is not null ? step.Name : "flow ends", step is not null ? step.State : StepState.Done); } - - if (job.State != JobState.Waiting) + + if (job.State != JobState.Waiting) job.State = JobState.Done; - - s_logger.LogInformation("Finished executing job {JobId} on {RunnerName}", job.Id, _runnerName); + + _logger.LogInformation("Finished executing job {JobId} on {RunnerName}", job.Id, _runnerName); } private async Task ProcessJobs(CancellationToken cancellationToken = default(CancellationToken)) @@ -122,18 +123,18 @@ public Runner(IAmAJobChannel channel, IAmAStateStoreAsync stateStore, IAm { if (cancellationToken.IsCancellationRequested) break; - + if (_channel.IsClosed()) break; - s_logger.LogInformation("Looking for jobs on {RunnerName}", _runnerName); + _logger.LogInformation("Looking for jobs on {RunnerName}", _runnerName); var job = await _channel.DequeueJobAsync(cancellationToken); if (job is null) continue; - - s_logger.LogInformation("Executing job {JobId} on {RunnerName}", job.Id, _runnerName); + + _logger.LogInformation("Executing job {JobId} on {RunnerName}", job.Id, _runnerName); await Execute(job, cancellationToken); - s_logger.LogInformation("Finished job {JobId} on {RunnerName}", job.Id, _runnerName); + _logger.LogInformation("Finished job {JobId} on {RunnerName}", job.Id, _runnerName); } } } diff --git a/src/Paramore.Brighter.Mediator/Steps.cs b/src/Paramore.Brighter.Mediator/Steps.cs index cdbc00fd95..356784aff4 100644 --- a/src/Paramore.Brighter.Mediator/Steps.cs +++ b/src/Paramore.Brighter.Mediator/Steps.cs @@ -28,14 +28,13 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Mediator; public enum StepState { Queued, - Running, + Running, Done, Faulted } @@ -51,27 +50,28 @@ public enum StepState public abstract class Step( string name, Sequential? next, + ILoggerFactory loggerFactory, IStepTask? stepTask = null, - Action? onCompletion = null) + Action? onCompletion = null) { /// Which job is being executed by the step. - protected Job? Job ; + protected Job? Job; /// The logger for the step. - protected static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - + protected readonly ILogger _logger = loggerFactory.CreateLogger>(); + /// The name of the step, used for tracing execution public string Name { get; init; } = name; - + /// The next step in the sequence, null if this is the last step protected internal Step? Next { get; } = next; /// An optional callback to be run, following completion of the step. protected internal Action? OnCompletion { get; } = onCompletion; - + /// The action to be taken with the step. protected readonly IStepTask? StepTask = stepTask; - + public StepState? State { get; set; } /// @@ -85,12 +85,12 @@ public abstract class Step( /// The cancellation token, to end this workflow /// public abstract Task ExecuteAsync( - IAmAStateStoreAsync stateStore, - IAmACommandProcessor? commandProcessor = null, + IAmAStateStoreAsync stateStore, + IAmACommandProcessor? commandProcessor = null, Scheduler? scheduler = null, CancellationToken cancellationToken = default(CancellationToken) ); - + /// /// Sets the job that is executing us /// @@ -116,9 +116,10 @@ public class ExclusiveChoice( ISpecification predicate, Action? onCompletion, Sequential? nextTrue, - Sequential? nextFalse + Sequential? nextFalse, + ILoggerFactory loggerFactory ) - : Step(name, null, null, onCompletion) + : Step(name, null, loggerFactory, null, onCompletion) { /// /// The work of the step is done here. Note that this is an abstract method, so it must be implemented by the derived class. @@ -131,35 +132,36 @@ public class ExclusiveChoice( /// The cancellation token, to end this workflow /// public override async Task ExecuteAsync( - IAmAStateStoreAsync stateStore, - IAmACommandProcessor? commandProcessor = null, + IAmAStateStoreAsync stateStore, + IAmACommandProcessor? commandProcessor = null, Scheduler? scheduler = null, CancellationToken cancellationToken = default(CancellationToken) - ) + ) { if (Job is null) throw new InvalidOperationException("Job is null"); - + State = StepState.Running; - + var step = predicate.IsSatisfiedBy(Job.Data) ? nextTrue : nextFalse; State = StepState.Done; - + if (step != null) step.State = StepState.Queued; - + Job.NextStep(step); OnCompletion?.Invoke(); await stateStore.SaveJobAsync(Job, cancellationToken); - + } } public class ParallelSplit( string name, - Func>>? onMap) - : Step(name, null) + Func>>? onMap, + ILoggerFactory loggerFactory) + : Step(name, null, loggerFactory: loggerFactory) { /// /// The work of the step is done here. Note that this is an abstract method, so it must be implemented by the derived class. @@ -172,39 +174,39 @@ public class ParallelSplit( /// The cancellation token, to end this workflow /// public override async Task ExecuteAsync( - IAmAStateStoreAsync stateStore, - IAmACommandProcessor? commandProcessor = null, + IAmAStateStoreAsync stateStore, + IAmACommandProcessor? commandProcessor = null, Scheduler? scheduler = null, CancellationToken cancellationToken = default(CancellationToken) - ) + ) { if (Job is null) throw new InvalidOperationException("Job is null"); - + if (onMap is null) - throw new InvalidOperationException("onMap is null; a ParallelSplit Step must have a mapping function to map to multiple branches"); - + throw new InvalidOperationException("onMap is null; a ParallelSplit Step must have a mapping function to map to multiple branches"); + if (scheduler is null) throw new InvalidOperationException("Scheduler is null; a ParallelSplit Step must have a scheduler to schedule the next step"); - + State = StepState.Running; - + //Map to multiple branches var branches = onMap?.Invoke(Job.Data); - + if (branches is null) return; - + foreach (Step branch in branches) { var childJob = new Job(Job.Data); childJob.AddChildJob(Job); childJob.InitSteps(branch); - await scheduler.ScheduleAsync(childJob, cancellationToken); + await scheduler.ScheduleAsync(childJob, cancellationToken); } - + State = StepState.Done; - + //NOTE: parallel split is a final step - this might change when we bring in merge Job.NextStep(null); await stateStore.SaveJobAsync(Job, cancellationToken); @@ -223,14 +225,15 @@ public override async Task ExecuteAsync( /// The next step in the sequence, following a faulted execution of the step /// The data that the step operates over public class Sequential( - string name, - IStepTask stepTask, - Action? onCompletion, - Sequential? next, - Action? onFaulted = null, + string name, + IStepTask stepTask, + Action? onCompletion, + Sequential? next, + ILoggerFactory loggerFactory, + Action? onFaulted = null, Sequential? faultNext = null -) - : Step(name, next, stepTask, onCompletion) +) + : Step(name, next, loggerFactory, stepTask, onCompletion) { /// /// The work of the step is done here. Note that this is an abstract method, so it must be implemented by the derived class. @@ -243,23 +246,23 @@ public class Sequential( /// The cancellation token, to end this workflow /// public override async Task ExecuteAsync( - IAmAStateStoreAsync stateStore, - IAmACommandProcessor? commandProcessor = null, + IAmAStateStoreAsync stateStore, + IAmACommandProcessor? commandProcessor = null, Scheduler? scheduler = null, CancellationToken cancellationToken = default(CancellationToken) - ) + ) { if (Job is null) throw new InvalidOperationException("Job is null"); - + if (StepTask is null) { - s_logger.LogWarning("No task to execute for {Name}", Name); + _logger.LogWarning("No task to execute for {Name}", Name); State = StepState.Done; await stateStore.SaveJobAsync(Job, cancellationToken); return; } - + State = StepState.Running; try @@ -267,10 +270,10 @@ public override async Task ExecuteAsync( await StepTask.HandleAsync(Job, commandProcessor, stateStore, cancellationToken); OnCompletion?.Invoke(); State = StepState.Done; - - if(Next != null) + + if (Next != null) Next.State = StepState.Queued; - + Job.NextStep(Next); await stateStore.SaveJobAsync(Job, cancellationToken); } @@ -278,11 +281,11 @@ public override async Task ExecuteAsync( { Job.State = JobState.Faulted; onFaulted?.Invoke(); - + if (faultNext != null) faultNext.State = StepState.Queued; - - Job.NextStep(faultNext); + + Job.NextStep(faultNext); State = StepState.Faulted; await stateStore.SaveJobAsync(Job, cancellationToken); } @@ -303,9 +306,10 @@ public class Wait : Step /// The name of the step, used for tracing execution /// The period for which we pause /// The next step in the sequence, null if this is the last step. + /// The factory used to create the logger for this step. /// The data that the step operates over - public Wait(string name, TimeSpan duration, Sequential? next) - : base(name, next) + public Wait(string name, TimeSpan duration, Sequential? next, ILoggerFactory loggerFactory) + : base(name, next, loggerFactory: loggerFactory) { _duration = duration; } @@ -321,33 +325,33 @@ public Wait(string name, TimeSpan duration, Sequential? next) /// The cancellation token, to end this workflow /// public override async Task ExecuteAsync( - IAmAStateStoreAsync stateStore, - IAmACommandProcessor? commandProcessor = null, + IAmAStateStoreAsync stateStore, + IAmACommandProcessor? commandProcessor = null, Scheduler? scheduler = null, CancellationToken cancellationToken = default(CancellationToken) - ) + ) { if (Job is null) throw new InvalidOperationException("Job is null"); - + if (scheduler is null) throw new InvalidOperationException("Scheduler is null; a Wait Step must have a scheduler to schedule the next step"); if (Next == null) throw new InvalidOperationException("Next step is empty; wait schedule the next step, so it cannot be empty"); - + State = StepState.Running; - + Job.DueTime = DateTime.UtcNow.Add(_duration); - + State = StepState.Done; - + Next.State = StepState.Queued; - + Job.NextStep(Next); - + Job.State = JobState.Waiting; - + //this call will save the state of the Job, so no need to do it twice await scheduler.ScheduleAtAsync(Job, _duration, cancellationToken); } diff --git a/src/Paramore.Brighter.Mediator/Waker.cs b/src/Paramore.Brighter.Mediator/Waker.cs index ebe0af0629..4447d7a859 100644 --- a/src/Paramore.Brighter.Mediator/Waker.cs +++ b/src/Paramore.Brighter.Mediator/Waker.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Mediator; @@ -39,18 +38,20 @@ public class Waker private readonly TimeSpan _jobAge; private readonly Scheduler _scheduler; private readonly string _wakerName = Uuid.New().ToString("N"); - - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + + private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// The age of the job to determine if it is due. /// The scheduler to trigger due jobs. - public Waker(TimeSpan jobAge, Scheduler scheduler) + /// The factory used to create the logger for this waker. + public Waker(TimeSpan jobAge, Scheduler scheduler, ILoggerFactory loggerFactory) { _jobAge = jobAge; _scheduler = scheduler; + _logger = loggerFactory.CreateLogger>(); } /// @@ -61,7 +62,7 @@ public Waker(TimeSpan jobAge, Scheduler scheduler) /// A task that completes when the wake loop exits (via cancellation). public async Task RunAsync(CancellationToken cancellationToken = default(CancellationToken)) { - s_logger.LogInformation("Starting waker {WakerName}", _wakerName); + _logger.LogInformation("Starting waker {WakerName}", _wakerName); try { @@ -69,7 +70,7 @@ public Waker(TimeSpan jobAge, Scheduler scheduler) } finally { - s_logger.LogInformation("Finished waker {WakerName}", _wakerName); + _logger.LogInformation("Finished waker {WakerName}", _wakerName); } } @@ -79,7 +80,7 @@ public Waker(TimeSpan jobAge, Scheduler scheduler) { if (cancellationToken.IsCancellationRequested) break; - + await _scheduler.TriggerDueJobsAsync(_jobAge, cancellationToken); await Task.Delay(_jobAge, cancellationToken); } diff --git a/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusScheduler.cs b/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusScheduler.cs index 8a7bb6a2d0..b315535bbb 100644 --- a/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusScheduler.cs +++ b/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusScheduler.cs @@ -3,7 +3,6 @@ using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessageScheduler.Azure; @@ -14,13 +13,15 @@ namespace Paramore.Brighter.MessageScheduler.Azure; /// The . /// The scheduler topic or queue /// The . +/// The used to create the logger. public class AzureServiceBusScheduler( ServiceBusSender sender, RoutingKey schedulerTopic, - TimeProvider timeProvider) + TimeProvider timeProvider, + ILoggerFactory loggerFactory) : IAmAMessageSchedulerAsync, IAmAMessageSchedulerSync, IAmARequestSchedulerAsync, IAmARequestSchedulerSync { - private static readonly ILogger Logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// public async Task ScheduleAsync(Message message, DateTimeOffset at, @@ -118,7 +119,7 @@ public async Task CancelAsync(string id, CancellationToken cancellationToken = d } else { - Logger.LogWarning("Could not cancel message as schedulerId is not a sequence number"); + _logger.LogWarning("Could not cancel message as schedulerId is not a sequence number"); } } @@ -144,7 +145,7 @@ private static ServiceBusMessage ConvertToServiceBusMessage(Message message) } var contentType = message.Header.ContentType ?? new ContentType(MediaTypeNames.Text.Plain); - + azureServiceBusMessage.ContentType = contentType.ToString(); azureServiceBusMessage.MessageId = message.Header.MessageId; if (message.Header.Bag.TryGetValue(ASBConstants.SessionIdKey, out object? value)) diff --git a/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusSchedulerFactory.cs b/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusSchedulerFactory.cs index e3b0fae9f5..b889faccc5 100644 --- a/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusSchedulerFactory.cs +++ b/src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusSchedulerFactory.cs @@ -1,4 +1,5 @@ -using Azure.Messaging.ServiceBus; +using Azure.Messaging.ServiceBus; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; namespace Paramore.Brighter.MessageScheduler.Azure; @@ -8,7 +9,7 @@ namespace Paramore.Brighter.MessageScheduler.Azure; /// /// /// -public class AzureServiceBusSchedulerFactory(IServiceBusClientProvider client, RoutingKey topic) +public class AzureServiceBusSchedulerFactory(IServiceBusClientProvider client, RoutingKey topic, ILoggerFactory loggerFactory) : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory { private readonly object _lock = new(); @@ -43,7 +44,7 @@ public IAmARequestSchedulerSync CreateSync(IAmACommandProcessor processor) => Create(); /// - public IAmARequestSchedulerAsync CreateAsync(IAmACommandProcessor processor) + public IAmARequestSchedulerAsync CreateAsync(IAmACommandProcessor processor) => Create(); private AzureServiceBusScheduler Create() @@ -56,7 +57,7 @@ private AzureServiceBusScheduler Create() .CreateSender(Topic, SenderOptions); } } - - return new AzureServiceBusScheduler(_sender, Topic, TimeProvider); + + return new AzureServiceBusScheduler(_sender, Topic, TimeProvider, loggerFactory); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/AWSMessagingGateway.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/AWSMessagingGateway.cs index 4d56dfb47a..27effa9bbc 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/AWSMessagingGateway.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/AWSMessagingGateway.cs @@ -37,19 +37,25 @@ THE SOFTWARE. */ using Amazon.SQS.Model; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AWSSQS.V4.Extensions; using Paramore.Brighter.Tasks; using InvalidOperationException = System.InvalidOperationException; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; -public class AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection) +public class AwsMessagingGateway { - protected static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + protected readonly ILogger _logger; - private readonly AWSClientFactory _awsClientFactory = new(awsConnection); - protected readonly AWSMessagingGatewayConnection AwsConnection = awsConnection; + private readonly AWSClientFactory _awsClientFactory; + protected readonly AWSMessagingGatewayConnection AwsConnection; + + public AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + _awsClientFactory = new AWSClientFactory(awsConnection); + AwsConnection = awsConnection; + } /// /// The Channel Address @@ -87,16 +93,16 @@ public class AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection) ChannelQueueUrl = makeChannel switch { //on validate or assume, turn a routing key into a queueUrl - OnMissingChannel.Assume or OnMissingChannel.Validate => + OnMissingChannel.Assume or OnMissingChannel.Validate => await ValidateQueueAsync(queue, findQueueBy, sqsAttributes.Type, makeChannel, cancellationToken), - OnMissingChannel.Create => + OnMissingChannel.Create => await CreateQueueAsync(queue, sqsAttributes, cancellationToken), _ => ChannelQueueUrl }; return ChannelQueueUrl; } - + protected RoutingKey EnsureSubscription( bool isFifo, string queueUrl, @@ -106,7 +112,7 @@ protected RoutingKey EnsureSubscription( SqsAttributes? sqsAttributes, OnMissingChannel makeChannels = OnMissingChannel.Create) => BrighterAsyncContext.Run(() => EnsureSubscriptionAsync(isFifo, queueUrl, routingKey, findTopicBy, snsAttributes, sqsAttributes, makeChannels)); - + protected async Task EnsureSubscriptionAsync( bool isFifo, @@ -149,7 +155,7 @@ await CheckQueueSubscribedAsync( ChannelTopicArn = makeTopic switch { //on validate or assume, turn a routing key into a topicARN - OnMissingChannel.Assume or OnMissingChannel.Validate => + OnMissingChannel.Assume or OnMissingChannel.Validate => await ValidateTopicAsync(topic, topicFindBy, type, cancellationToken), OnMissingChannel.Create => await CreateTopicAsync(topic, attributes), @@ -158,7 +164,7 @@ await CreateTopicAsync(topic, attributes), return ChannelTopicArn; } - + private async Task CheckQueueSubscribedAsync( string queueUrl, SqsAttributes? sqsAttributes, @@ -200,11 +206,11 @@ private async Task CheckSubscriptionAsync(OnMissingChannel makeSubscriptions, private async Task CreateTopicAsync(RoutingKey topic, SnsAttributes? snsAttributes) { snsAttributes ??= SnsAttributes.Empty; - + using var snsClient = _awsClientFactory.CreateSnsClient(); var topicName = topic.Value; - + if (snsAttributes.Type == SqsType.Fifo) { topicName = topic.ToValidSNSTopicName(true); @@ -314,7 +320,8 @@ private async Task CreateDeadLetterQueueAsync( CreateCommonQueueAttributes(sqsAttributes, isDLQ, attributes); - if (sqsAttributes.Type != SqsType.Fifo) return attributes; + if (sqsAttributes.Type != SqsType.Fifo) + return attributes; CreateFifoQueueAttributes(sqsAttributes, attributes); @@ -330,8 +337,8 @@ private static void CreateFifoQueueAttributes(SqsAttributes sqsAttributes, Dicti } if (sqsAttributes.DeduplicationScope == null || sqsAttributes.FifoThroughputLimit == null) - return ; - + return; + attributes.Add(QueueAttributeName.FifoThroughputLimit, Convert.ToString(sqsAttributes.FifoThroughputLimit.Value.AsString())); attributes.Add(QueueAttributeName.DeduplicationScope, sqsAttributes.DeduplicationScope switch { @@ -346,7 +353,7 @@ private void CreateCommonQueueAttributes(SqsAttributes sqsAttributes, bool isDLQ { var policy = new { - maxReceiveCount = sqsAttributes.RedrivePolicy.MaxReceiveCount, + maxReceiveCount = sqsAttributes.RedrivePolicy.MaxReceiveCount, deadLetterTargetArn = ChannelDeadLetterQueueArn }; @@ -404,8 +411,9 @@ private static List CreateTopicTags(SnsAttributes? snsAttributes) if (!string.IsNullOrEmpty(snsAttributes.Policy)) attributes.Add("Policy", snsAttributes.Policy); - if (snsAttributes.Type != SqsType.Fifo) return attributes; - + if (snsAttributes.Type != SqsType.Fifo) + return attributes; + attributes.Add("FifoTopic", "true"); if (snsAttributes.ContentBasedDeduplication) { diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/ChannelFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/ChannelFactory.cs index 798607dddd..4220341e97 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/ChannelFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/ChannelFactory.cs @@ -51,10 +51,10 @@ public partial class ChannelFactory : AwsMessagingGateway, IAmAChannelFactory /// Initializes a new instance of the class. /// /// The details of the subscription to AWS. - public ChannelFactory(AWSMessagingGatewayConnection awsConnection) - : base(awsConnection) + public ChannelFactory(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) + : base(awsConnection, loggerFactory) { - _messageConsumerFactory = new SqsMessageConsumerFactory(awsConnection); + _messageConsumerFactory = new SqsMessageConsumerFactory(awsConnection, loggerFactory); _retryPolicy = Policy .Handle() .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10)]); @@ -169,7 +169,7 @@ await QueueExistsAsync(sqsClient, } catch (Exception) { - Log.CouldNotDeleteQueue(s_logger, queueExists.queueUrl); + Log.CouldNotDeleteQueue(_logger, queueExists.queueUrl); } } } @@ -196,7 +196,7 @@ public async Task DeleteTopicAsync() } catch (Exception) { - Log.CouldNotDeleteTopic(s_logger, ChannelTopicArn); + Log.CouldNotDeleteTopic(_logger, ChannelTopicArn); } } } @@ -311,7 +311,7 @@ private async Task UnsubscribeFromTopicAsync(AmazonSimpleNotificationServiceClie await snsClient.UnsubscribeAsync(new UnsubscribeRequest { SubscriptionArn = sub.SubscriptionArn }); if (unsubscribe.HttpStatusCode != HttpStatusCode.OK) { - Log.ErrorUnsubscribingFromTopic(s_logger, ChannelAddress, sub.SubscriptionArn); + Log.ErrorUnsubscribingFromTopic(_logger, ChannelAddress, sub.SubscriptionArn); } } } while (response.NextToken != null); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducer.cs index b37b60652d..32cf189aab 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducer.cs @@ -65,10 +65,11 @@ public Publication Publication /// How do we connect to AWS in order to manage middleware /// Configuration of a producer /// - public SnsMessageProducer(AWSMessagingGatewayConnection connection, + public SnsMessageProducer(AWSMessagingGatewayConnection connection, SnsPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) - : base(connection) + : base(connection, loggerFactory) { _publication = publication; _clientFactory = new AWSClientFactory(connection); @@ -179,7 +180,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use } BrighterTracer.WriteProducerEvent(Span, "aws_sns", message, _options); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); await ConfirmTopicExistsAsync(message.Header.Topic, cancellationToken); @@ -195,7 +196,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use throw new InvalidOperationException( $"Failed to publish message with topic {message.Header.Topic} and id {message.Id} and message: {message.Body}"); - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, messageId); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, messageId); } private static partial class Log diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducerFactory.cs index e3a7789ac2..11ac12c97f 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducerFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -33,18 +34,22 @@ public class SnsMessageProducerFactory : IAmAMessageProducerFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Creates a collection of SNS message producers from the SNS publication information /// /// The Connection to use to connect to AWS /// The publications describing the SNS topics that we want to use + /// The factory used to create loggers for the producers. public SnsMessageProducerFactory( AWSMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { _connection = connection; _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -60,9 +65,9 @@ public Dictionary Create() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SnsMessageProducer(_connection, publication); + var producer = new SnsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); producer.Publication = publication; - + if (producer.ConfirmTopicExists()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); @@ -92,9 +97,9 @@ public async Task> CreateAsync() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SnsMessageProducer(_connection, publication); + var producer = new SnsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); producer.Publication = publication; - + if (await producer.ConfirmTopicExistsAsync()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsProducerRegistryFactory.cs index 8f726eab47..ca9377967e 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsProducerRegistryFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -36,18 +37,22 @@ public class SnsProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _snsPublications; + private readonly ILoggerFactory _loggerFactory; /// /// Create a collection of producers from the publication information /// /// The Connection to use to connect to AWS /// The publication describing the SNS topic that we want to use + /// The factory used to create loggers for the producers. public SnsProducerRegistryFactory( AWSMessagingGatewayConnection connection, - IEnumerable snsPublications) + IEnumerable snsPublications, + ILoggerFactory loggerFactory) { _connection = connection; _snsPublications = snsPublications; + _loggerFactory = loggerFactory; } /// @@ -56,7 +61,7 @@ public SnsProducerRegistryFactory( /// The with . public IAmAProducerRegistry Create() { - var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications); + var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -67,7 +72,7 @@ public IAmAProducerRegistry Create() /// The with . public async Task CreateAsync(CancellationToken ct = default) { - var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications); + var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications, _loggerFactory); return new ProducerRegistry(await producerFactory.CreateAsync()); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs index fbe7107db9..c278360bf6 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs @@ -31,17 +31,21 @@ THE SOFTWARE. */ using Amazon.SQS; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; internal sealed partial class SqsInlineMessageCreator : SqsMessageCreatorBase, ISqsMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private Dictionary _messageAttributes = new(); + public SqsInlineMessageCreator(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } + public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) { var topic = HeaderResult.Empty(); @@ -54,7 +58,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) topic = ReadTopic(); messageId = ReadMessageId(); - var cloudEvents = ReadMessageCloudEvents(); + var cloudEvents = ReadMessageCloudEvents(); var contentType = ReadContentType(cloudEvents); var correlationId = ReadCorrelationId(); var handledCount = ReadHandledCount(); @@ -72,11 +76,11 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) var traceParent = ReadCloudEventsTraceParent(cloudEvents); var traceState = ReadCloudEventsTraceState(cloudEvents); var baggage = ReadCloudEventsBaggage(cloudEvents); - + var bag = ReadMessageBag(); if (deduplicationId.Success) { - bag[HeaderNames.DeduplicationId] = deduplicationId.Result; + bag[HeaderNames.DeduplicationId] = deduplicationId.Result; } if (receiptHandle.Success) @@ -112,12 +116,12 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) } catch (Exception e) { - Log.FailedToCreateMessageFromAwsSqsMessage(s_logger, e); + Log.FailedToCreateMessageFromAwsSqsMessage(_logger, e); return Message.FailureMessage(topic.Result, messageId.Result); } } - private static Dictionary ReadMessageAttributes(JsonDocument jsonDocument) + private Dictionary ReadMessageAttributes(JsonDocument jsonDocument) { var messageAttributes = new Dictionary(); @@ -132,7 +136,7 @@ private static Dictionary ReadMessageAttributes(JsonDocumen } catch (Exception ex) { - Log.FailedWhileDeserializingSqsMessageBody(s_logger, ex); + Log.FailedWhileDeserializingSqsMessageBody(_logger, ex); } return messageAttributes ?? new Dictionary(); @@ -145,13 +149,13 @@ private HeaderResult ReadContentType(Dictionary hea var result = contentType.GetValueInString(); return new HeaderResult(result is not null ? new ContentType(result) : new ContentType(MediaTypeNames.Text.Plain), true); } - + if (_messageAttributes.TryGetValue(HeaderNames.ContentType, out contentType)) { var result = contentType.GetValueInString() ?? MediaTypeNames.Text.Plain; return new HeaderResult(new ContentType(result), true); } - + if (headers.TryGetValue(HeaderNames.DataContentType, out var val)) { return new HeaderResult(new ContentType(val), true); @@ -215,7 +219,7 @@ private HeaderResult ReadSpecVersion(Dictionary headers) { return new HeaderResult(specVersion.GetValueInString(), true); } - + if (headers.TryGetValue(HeaderNames.SpecVersion, out var val)) { return new HeaderResult(val, true); @@ -232,10 +236,11 @@ private HeaderResult ReadType(Dictionary header if (!string.IsNullOrEmpty(val)) { return new HeaderResult(new CloudEventsType(val!), true); - }; + } + ; } - - if (headers.TryGetValue(HeaderNames.Type, out var cloudEventType) + + if (headers.TryGetValue(HeaderNames.Type, out var cloudEventType) && !string.IsNullOrEmpty(cloudEventType)) { return new HeaderResult(new CloudEventsType(cloudEventType), true); @@ -243,15 +248,15 @@ private HeaderResult ReadType(Dictionary header return new HeaderResult(CloudEventsType.Empty, true); } - + private HeaderResult ReadSource(Dictionary headers) { - if (_messageAttributes.TryGetValue(HeaderNames.Source, out var source) - && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) + if (_messageAttributes.TryGetValue(HeaderNames.Source, out var source) + && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) { return new HeaderResult(uri, true); } - + if (headers.TryGetValue(HeaderNames.Source, out var val) && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) { @@ -260,45 +265,45 @@ private HeaderResult ReadSource(Dictionary headers) return new HeaderResult(new Uri(MessageHeader.DefaultSource), true); } - - private HeaderResult ReadDataSchema(Dictionary headers) - { - if (_messageAttributes.TryGetValue(HeaderNames.DataSchema, out var source) - && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) - { - return new HeaderResult(uri, true); - } - - if (headers.TryGetValue(HeaderNames.DataSchema, out var val) - && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) - { - return new HeaderResult(uri, true); - } - - return new HeaderResult(null, true); - } + + private HeaderResult ReadDataSchema(Dictionary headers) + { + if (_messageAttributes.TryGetValue(HeaderNames.DataSchema, out var source) + && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) + { + return new HeaderResult(uri, true); + } + + if (headers.TryGetValue(HeaderNames.DataSchema, out var val) + && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) + { + return new HeaderResult(uri, true); + } + + return new HeaderResult(null, true); + } private HeaderResult ReadTimestamp(Dictionary headers) { - if (headers.TryGetValue(HeaderNames.Timestamp, out var val) - && DateTimeOffset.TryParse(val, out var value)) - { - return new HeaderResult(value, true); - } - - if (_messageAttributes.TryGetValue(HeaderNames.Time, out var timeStamp) - && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) - { - return new HeaderResult(value, true); - } - - if (_messageAttributes.TryGetValue(HeaderNames.Timestamp, out timeStamp) - && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) - { - return new HeaderResult(value, true); - } - - return new HeaderResult(DateTimeOffset.UtcNow, true); + if (headers.TryGetValue(HeaderNames.Timestamp, out var val) + && DateTimeOffset.TryParse(val, out var value)) + { + return new HeaderResult(value, true); + } + + if (_messageAttributes.TryGetValue(HeaderNames.Time, out var timeStamp) + && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) + { + return new HeaderResult(value, true); + } + + if (_messageAttributes.TryGetValue(HeaderNames.Timestamp, out timeStamp) + && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) + { + return new HeaderResult(value, true); + } + + return new HeaderResult(DateTimeOffset.UtcNow, true); } private HeaderResult ReadMessageType() @@ -374,32 +379,32 @@ private HeaderResult ReadTopic() private HeaderResult ReadMessageSubject(JsonDocument jsonDocument, Dictionary headers) { - if (_messageAttributes.TryGetValue(HeaderNames.Subject, out var messageId)) - { - return new HeaderResult(messageId.GetValueInString(), true); - } - - try - { - if (jsonDocument.RootElement.TryGetProperty("Subject", out var value)) - { - return new HeaderResult(value.GetString(), true); - } - - if (headers.TryGetValue(HeaderNames.Subject, out var subject)) - { - return new HeaderResult(subject, true); - } - } - catch (Exception ex) - { - Log.FailedToParseSqsMessageBodyToValidJsonDocument(s_logger, ex); - } - - return new HeaderResult(null, true); + if (_messageAttributes.TryGetValue(HeaderNames.Subject, out var messageId)) + { + return new HeaderResult(messageId.GetValueInString(), true); + } + + try + { + if (jsonDocument.RootElement.TryGetProperty("Subject", out var value)) + { + return new HeaderResult(value.GetString(), true); + } + + if (headers.TryGetValue(HeaderNames.Subject, out var subject)) + { + return new HeaderResult(subject, true); + } + } + catch (Exception ex) + { + Log.FailedToParseSqsMessageBodyToValidJsonDocument(_logger, ex); + } + + return new HeaderResult(null, true); } - private static MessageBody ReadMessageBody(JsonDocument jsonDocument) + private MessageBody ReadMessageBody(JsonDocument jsonDocument) { try { @@ -410,7 +415,7 @@ private static MessageBody ReadMessageBody(JsonDocument jsonDocument) } catch (Exception ex) { - Log.FailedToParseSqsMessageBodyToValidJsonDocument(s_logger, ex); + Log.FailedToParseSqsMessageBodyToValidJsonDocument(_logger, ex); } return new MessageBody(string.Empty); @@ -439,7 +444,7 @@ private static HeaderResult ReadDeduplicationId(Amazon.SQS.Model.Message return new HeaderResult(string.Empty, false); } - + private Dictionary ReadMessageCloudEvents() { if (_messageAttributes.TryGetValue(HeaderNames.CloudEventHeaders, out var headerBag)) @@ -465,34 +470,34 @@ private Dictionary ReadMessageCloudEvents() return new Dictionary(); } - - private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceParent, out var value)) { return new HeaderResult(new TraceParent(value), true); } - + return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceState, out var value)) { return new HeaderResult(new TraceState(value), true); - } + } return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) { var baggage = new Baggage(); if (cloudEventHeaders.TryGetValue(HeaderNames.Baggage, out var value)) { baggage.LoadBaggage(value); - } - + } + return new HeaderResult(baggage, true); } @@ -503,7 +508,7 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Failed while deserializing Sqs Message body")] public static partial void FailedWhileDeserializingSqsMessageBody(ILogger logger, Exception ex); - + [LoggerMessage(LogLevel.Warning, "Failed to parse Sqs Message Body to valid Json Document")] public static partial void FailedToParseSqsMessageBodyToValidJsonDocument(ILogger logger, Exception ex); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumer.cs index a115df23c3..5979e956a1 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumer.cs @@ -31,7 +31,6 @@ THE SOFTWARE. */ using Amazon.SQS.Model; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -41,9 +40,10 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; /// public partial class SqsMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly AWSMessagingGatewayConnection _connection; + private readonly ILoggerFactory _loggerFactory; private readonly AWSClientFactory _clientFactory; private readonly string _queueName; private readonly int _batchSize; @@ -69,20 +69,24 @@ public partial class SqsMessageConsumer : IAmAMessageConsumerSync, IAmAMessageCo /// Is the queue name a queue url? /// Do we have Raw Message Delivery enabled? /// The for the queue (used by DLQ producers for FIFO support) + /// The factory used to create a logger for this consumer public SqsMessageConsumer( - AWSMessagingGatewayConnection awsConnection, - string? queueName, - int batchSize = 1, + AWSMessagingGatewayConnection awsConnection, + string? queueName, + ILoggerFactory loggerFactory, + int batchSize = 1, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null, OnMissingChannel makeChannels = OnMissingChannel.Create, bool isQueueUrl = false, bool rawMessageDelivery = true, - SqsAttributes? queueAttributes = null) + SqsAttributes? queueAttributes = null) { if (string.IsNullOrEmpty(queueName)) throw new ConfigurationException("QueueName is mandatory"); + _logger = loggerFactory.CreateLogger(); + _loggerFactory = loggerFactory; _connection = awsConnection; _clientFactory = new AWSClientFactory(awsConnection); _queueName = queueName!; @@ -155,14 +159,14 @@ public SqsMessageConsumer( var reasonString = reason is null ? nameof(RejectionReason.DeliveryError) : reason.RejectionReason.ToString(); var description = reason is null ? "unknown" : reason.Description ?? "unknown"; - Log.RejectingMessage(s_logger, message.Id.Value, receiptHandle, _queueName, reasonString, description); + Log.RejectingMessage(_logger, message.Id.Value, receiptHandle, _queueName, reasonString, description); // If no channels configured, just delete the original message if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); } await AcknowledgeAsync(message, cancellationToken); @@ -183,7 +187,7 @@ public SqsMessageConsumer( { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -194,18 +198,18 @@ public SqsMessageConsumer( if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // Sending to DLQ failed — delete the original to prevent infinite // reprocessing. The message is lost rather than stuck in a retry loop. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); await DeleteSourceMessageAsync(receiptHandle!, message.Id.Value, cancellationToken); return true; } @@ -228,16 +232,16 @@ public SqsMessageConsumer( try { using var client = _clientFactory.CreateSqsClient(); - Log.PurgingQueue(s_logger, _queueName); + Log.PurgingQueue(_logger, _queueName); await EnsureChannelUrl(client, cancellationToken); await client.PurgeQueueAsync(_channelUrl, cancellationToken); - Log.PurgedQueue(s_logger, _queueName); + Log.PurgedQueue(_logger, _queueName); } catch (Exception exception) { - Log.ErrorPurgingQueue(s_logger, exception, _queueName); + Log.ErrorPurgingQueue(_logger, exception, _queueName); throw; } } @@ -266,7 +270,7 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, await EnsureChannelUrl(client, cancellationToken); timeOut ??= TimeSpan.Zero; - Log.RetrievingNextMessage(s_logger,_channelUrl!); + Log.RetrievingNextMessage(_logger, _channelUrl!); var request = new ReceiveMessageRequest(_channelUrl) { @@ -282,17 +286,17 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, } catch (InvalidOperationException ioe) { - Log.CouldNotDetermineNumberOfMessagesToRetrieve(s_logger); + Log.CouldNotDetermineNumberOfMessagesToRetrieve(_logger); throw new ChannelFailureException("Error connecting to SQS, see inner exception for details", ioe); } catch (OperationCanceledException oce) { - Log.CouldNotFindMessagesToRetrieve(s_logger); + Log.CouldNotFindMessagesToRetrieve(_logger); throw new ChannelFailureException("Error connecting to SQS, see inner exception for details", oce); } catch (Exception e) { - Log.ErrorListeningToQueue(s_logger, e, _queueName); + Log.ErrorListeningToQueue(_logger, e, _queueName); throw; } finally @@ -308,8 +312,8 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, var messages = new Message[sqsMessages.Length]; for (int i = 0; i < sqsMessages.Length; i++) { - var message = SqsMessageCreatorFactory.Create(_rawMessageDelivery).CreateMessage(sqsMessages[i]); - Log.ReceivedMessageFromQueue(s_logger, _queueName, Environment.NewLine, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); + var message = SqsMessageCreatorFactory.Create(_rawMessageDelivery, _loggerFactory).CreateMessage(sqsMessages[i]); + Log.ReceivedMessageFromQueue(_logger, _queueName, Environment.NewLine, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); messages[i] = message; } @@ -339,7 +343,7 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken try { - Log.NackingMessage(s_logger, message.Id.Value, receiptHandle, _queueName); + Log.NackingMessage(_logger, message.Id.Value, receiptHandle, _queueName); using var client = _clientFactory.CreateSqsClient(); await EnsureChannelUrl(client, cancellationToken); @@ -348,7 +352,7 @@ await client.ChangeMessageVisibilityAsync( cancellationToken ); - Log.NackedMessage(s_logger, message.Id.Value, receiptHandle, _channelUrl!); + Log.NackedMessage(_logger, message.Id.Value, receiptHandle, _channelUrl!); } catch (ReceiptHandleIsInvalidException ex) { @@ -356,11 +360,11 @@ await client.ChangeMessageVisibilityAsync( // SQS has already made the message visible again for redelivery by another consumer. // Nack sets visibility to zero for immediate redelivery — but the message is already // visible again, so the net effect is the same. Log a warning and continue. - Log.NackFailedReceiptHandleExpired(s_logger, ex, message.Id.Value, receiptHandle, _queueName); + Log.NackFailedReceiptHandleExpired(_logger, ex, message.Id.Value, receiptHandle, _queueName); } catch (Exception exception) { - Log.ErrorNackingMessage(s_logger, exception, message.Id.Value, receiptHandle, _queueName); + Log.ErrorNackingMessage(_logger, exception, message.Id.Value, receiptHandle, _queueName); throw; } } @@ -386,7 +390,7 @@ public async Task RequeueAsync(Message message, TimeSpan? delay = null, try { - Log.RequeueingMessage(s_logger, message.Id.Value); + Log.RequeueingMessage(_logger, message.Id.Value); using (var client = _clientFactory.CreateSqsClient()) { @@ -397,7 +401,7 @@ await client.ChangeMessageVisibilityAsync( ); } - Log.RequeuedMessage(s_logger, message.Id.Value); + Log.RequeuedMessage(_logger, message.Id.Value); return true; } @@ -406,12 +410,12 @@ await client.ChangeMessageVisibilityAsync( // Receipt handle is invalid (most likely because the visibility timeout elapsed). // SQS has already made the message visible again for redelivery by another consumer, // but without the intended delay. Log a warning so operators are aware. - Log.RequeueFailedReceiptHandleExpired(s_logger, ex, message.Id.Value, receiptHandle, _queueName, delay.Value); + Log.RequeueFailedReceiptHandleExpired(_logger, ex, message.Id.Value, receiptHandle, _queueName, delay.Value); return false; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value, receiptHandle, _queueName); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value, receiptHandle, _queueName); return false; } } @@ -458,11 +462,11 @@ public async ValueTask DisposeAsync() // We must NOT call the sync ConfirmQueueExists here because the lazy is resolved // inside RejectAsync, which may already be running inside BrighterAsyncContext.Run // from the sync Reject path — nesting would deadlock. - return new SqsMessageProducer(_connection, publication); + return new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingDlqProducerException(s_logger, e, _deadLetterRoutingKey.Value); + Log.ErrorCreatingDlqProducerException(_logger, e, _deadLetterRoutingKey.Value); return null; } } @@ -477,11 +481,11 @@ public async ValueTask DisposeAsync() try { // Queue existence is confirmed on first SendAsync via ConfirmQueueExistsAsync. - return new SqsMessageProducer(_connection, publication); + return new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingInvalidMessageProducerException(s_logger, e, _invalidMessageRoutingKey.Value); + Log.ErrorCreatingInvalidMessageProducerException(_logger, e, _invalidMessageRoutingKey.Value); return null; } } @@ -496,7 +500,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea // Remove SQS-specific headers that will be reset when sent to the DLQ message.Header.Bag.Remove("ReceiptHandle"); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -514,7 +519,7 @@ private async Task DeleteSourceMessageAsync(string receiptHandle, string message await client.DeleteMessageAsync(new DeleteMessageRequest(_channelUrl, receiptHandle), cancellationToken); - Log.DeletedMessage(s_logger, messageId, receiptHandle, _channelUrl!); + Log.DeletedMessage(_logger, messageId, receiptHandle, _channelUrl!); } catch (ReceiptHandleIsInvalidException ex) { @@ -522,11 +527,11 @@ await client.DeleteMessageAsync(new DeleteMessageRequest(_channelUrl, receiptHan // SQS has already made the message visible again for redelivery by another consumer. // This is an error because the message was not deleted and may be processed again; // handlers should be idempotent, but an operator may need to investigate. - Log.DeleteFailedReceiptHandleExpired(s_logger, ex, messageId, receiptHandle, _queueName); + Log.DeleteFailedReceiptHandleExpired(_logger, ex, messageId, receiptHandle, _queueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, messageId, receiptHandle, _queueName); + Log.ErrorDeletingMessage(_logger, exception, messageId, receiptHandle, _queueName); throw; } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumerFactory.cs index 1fa55c63ce..8ce7efc981 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumerFactory.cs @@ -21,6 +21,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; /// @@ -29,13 +31,15 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; public class SqsMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly AWSMessagingGatewayConnection _awsConnection; + private readonly ILoggerFactory _loggerFactory; /// /// Initializes a new instance of the class. /// - public SqsMessageConsumerFactory(AWSMessagingGatewayConnection awsConnection) + public SqsMessageConsumerFactory(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) { _awsConnection = awsConnection; + _loggerFactory = loggerFactory; } /// @@ -57,12 +61,13 @@ public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) private SqsMessageConsumer CreateImpl(Subscription subscription) { SqsSubscription? sqsSubscription = subscription as SqsSubscription; - if (sqsSubscription == null) throw new ConfigurationException("We expect an SqsSubscription or SqsSubscription as a parameter"); + if (sqsSubscription == null) + throw new ConfigurationException("We expect an SqsSubscription or SqsSubscription as a parameter"); //if it is a url, don't alter; if it is just a name, ensure it is valid ChannelName queueName = subscription.ChannelName; if (sqsSubscription.FindQueueBy == QueueFindBy.Name) - queueName =queueName.ToValidSQSQueueName(sqsSubscription.QueueAttributes.Type == SqsType.Fifo); + queueName = queueName.ToValidSQSQueueName(sqsSubscription.QueueAttributes.Type == SqsType.Fifo); // Extract DLQ and invalid message routing keys if subscription supports them RoutingKey? deadLetterRoutingKey = null; @@ -87,7 +92,8 @@ private SqsMessageConsumer CreateImpl(Subscription subscription) makeChannels: sqsSubscription.MakeChannels, isQueueUrl: (sqsSubscription.FindQueueBy == QueueFindBy.Url), rawMessageDelivery: sqsSubscription.QueueAttributes.RawMessageDelivery, - queueAttributes: sqsSubscription.QueueAttributes + queueAttributes: sqsSubscription.QueueAttributes, + loggerFactory: _loggerFactory ); } -} \ No newline at end of file +} diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs index 7d81fcd440..776f9204f8 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs @@ -31,7 +31,6 @@ THE SOFTWARE. */ using Amazon.SQS.Model; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Transforms.Transformers; @@ -52,7 +51,12 @@ internal enum ARNAmazonSNS internal sealed partial class SqsMessageCreator : SqsMessageCreatorBase, ISqsMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + + public SqsMessageCreator(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) { @@ -89,7 +93,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) messageId: messageId.Result ?? Id.Empty, topic: topic.Result ?? RoutingKey.Empty, messageType.Result, - source: source.Result, + source: source.Result, type: type.Result, timeStamp: timeStamp.Result, correlationId: correlationId.Success ? correlationId.Result : Id.Empty, @@ -114,7 +118,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) } catch (Exception e) { - Log.FailedToCreateMessageFromAmqpMessage(s_logger, e); + Log.FailedToCreateMessageFromAmqpMessage(_logger, e); return Message.FailureMessage(topic.Result, messageId.Success ? messageId.Result : Id.Empty); } } @@ -144,7 +148,7 @@ private static void PopulateBag(Dictionary bag, HeaderResult(null, false); } - + private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model.Message sqsMessage) { if (sqsMessage.MessageAttributes is not null @@ -160,11 +164,12 @@ private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model catch (Exception) { //we weill just suppress conversion errors, and return an empty bag - } } + } + } return new Dictionary(); } - + private static HeaderResult ReadCloudEventSource(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.Source, out var value)) @@ -177,13 +182,13 @@ private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model return new HeaderResult(null, false); } - - private static HeaderResult ReadCloudEventsSpecVersion(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsSpecVersion(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.SpecVersion, out var value)) { return new HeaderResult(value, true); - } + } return new HeaderResult(MessageHeader.DefaultSpecVersion, true); } @@ -196,34 +201,34 @@ private static HeaderResult ReadCloudEventsSpecVersion(Dictionary(CloudEventsType.Empty, false); } - - private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceParent, out var value)) { return new HeaderResult(new TraceParent(value), true); } - + return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceState, out var value)) { return new HeaderResult(new TraceState(value), true); - } + } return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) { var baggage = new Baggage(); if (cloudEventHeaders.TryGetValue(HeaderNames.Baggage, out var value)) { baggage.LoadBaggage(value); - } - + } + return new HeaderResult(baggage, true); } @@ -436,7 +441,7 @@ private static HeaderResult ReadDeduplicationId(Amazon.SQS.Model.Message return new HeaderResult(null, false); } - + private static HeaderResult ReadSubject(Amazon.SQS.Model.Message sqsMessage, Dictionary headers) { if (sqsMessage.MessageAttributes is not null @@ -444,15 +449,15 @@ private static HeaderResult ReadSubject(Amazon.SQS.Model.Message sqsMess { return new HeaderResult(value.StringValue, true); } - + if (headers.TryGetValue(HeaderNames.Subject, out var subject)) { return new HeaderResult(subject, true); } - + return new HeaderResult(null, false); } - + private static partial class Log { [LoggerMessage(LogLevel.Warning, "Failed to create message from amqp message")] diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreatorFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreatorFactory.cs index a316431fcb..4080d741b6 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreatorFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreatorFactory.cs @@ -21,17 +21,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; internal sealed class SqsMessageCreatorFactory { - public static ISqsMessageCreator Create(bool rawMessageDelivery) + public static ISqsMessageCreator Create(bool rawMessageDelivery, ILoggerFactory loggerFactory) { if (rawMessageDelivery) { - return new SqsMessageCreator(); + return new SqsMessageCreator(loggerFactory); } - return new SqsInlineMessageCreator(); + return new SqsInlineMessageCreator(loggerFactory); } } \ No newline at end of file diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducer.cs index 0b88586c06..36936fd7e9 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducer.cs @@ -41,6 +41,7 @@ public partial class SqsMessageProducer : AwsMessagingGateway, IAmAMessageProduc private readonly SqsPublication _publication; private readonly AWSClientFactory _clientFactory; private readonly InstrumentationOptions _instrumentation; + private readonly ILoggerFactory _loggerFactory; /// /// The publication configuration for this producer @@ -61,16 +62,18 @@ public partial class SqsMessageProducer : AwsMessagingGateway, IAmAMessageProduc /// How do we connect to AWS in order to manage middleware /// Configuration of a producer. Required. /// - public SqsMessageProducer(AWSMessagingGatewayConnection connection, + public SqsMessageProducer(AWSMessagingGatewayConnection connection, SqsPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) - : base(connection) + : base(connection, loggerFactory) { _publication = publication ?? throw new ArgumentNullException(nameof(publication)); - if (_publication.ChannelName is null) + if (_publication.ChannelName is null) throw new InvalidOperationException($"We must have a valid Channel Name on the Publication, either a queue name or a Url"); _clientFactory = new AWSClientFactory(connection); _instrumentation = instrumentation; + _loggerFactory = loggerFactory; if (publication.FindQueueBy == QueueFindBy.Url) { @@ -107,10 +110,10 @@ public async Task ConfirmQueueExistsAsync(CancellationToken cancellationTo //Only do this on first send for a queue for efficiency; won't auto-recreate when goes missing at runtime as a result if (!string.IsNullOrEmpty(ChannelQueueUrl)) return true; - + if (_publication is null) throw new ConfigurationException("No publication specified for producer"); - + if (_publication.ChannelName is null) throw new ConfigurationException("No channel name specified for publication"); @@ -121,7 +124,7 @@ public async Task ConfirmQueueExistsAsync(CancellationToken cancellationTo _publication.QueueAttributes, _publication.MakeChannels, cancellationToken); - + ChannelQueueUrl = queueUrl; return !string.IsNullOrEmpty(queueUrl); @@ -134,13 +137,13 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken /// public async Task SendWithDelayAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken = default) => await SendWithDelayAsync(message, delay, true, cancellationToken); - - + + private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool useAsyncScheduler, CancellationToken cancellationToken = default) { if (_publication is null) throw new ConfigurationException("No publication specified for producer"); - + delay ??= TimeSpan.Zero; // SQS support delay until 15min, more than that we are going to use scheduler if (delay > TimeSpan.FromMinutes(15) && _publication.QueueAttributes.Type == SqsType.Standard) @@ -156,14 +159,14 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use schedulerSync.Schedule(message, delay.Value); return; } - + BrighterTracer.WriteProducerEvent(Span, MessagingSystem.AWSSQS, message, _instrumentation); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); await ConfirmQueueExistsAsync(cancellationToken); using var client = _clientFactory.CreateSqsClient(); - var sender = new SqsMessageSender(ChannelQueueUrl!, client); + var sender = new SqsMessageSender(ChannelQueueUrl!, client, _loggerFactory); var messageId = await sender.SendAsync(message, delay, cancellationToken); if (messageId == null) @@ -172,7 +175,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use $"Failed to publish message with topic {message.Header.Topic} and id {message.Id} and message: {message.Body}"); } - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, messageId); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, messageId); } public void Send(Message message) => SendWithDelay(message, null); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducerFactory.cs index 15e868033c..2bbfb6700a 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducerFactory.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -11,17 +12,21 @@ public class SqsMessageProducerFactory : IAmAMessageProducerFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Initialize new instance of . /// /// The . /// The collection of . + /// The factory used to create loggers for the producers. public SqsMessageProducerFactory(AWSMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { _connection = connection; _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -37,7 +42,7 @@ public Dictionary Create() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SqsMessageProducer(_connection, publication); + var producer = new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); if (producer.ConfirmQueueExists()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); @@ -68,7 +73,7 @@ public async Task> CreateAsync() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SqsMessageProducer(_connection, publication); + var producer = new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); if (await producer.ConfirmQueueExistsAsync()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageSender.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageSender.cs index 2506f2171d..a1404dea9c 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageSender.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageSender.cs @@ -10,7 +10,6 @@ using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -19,9 +18,9 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; /// public partial class SqsMessageSender { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); private static readonly TimeSpan s_maxDelay = TimeSpan.FromSeconds(900); - + + private readonly ILogger _logger; private readonly string _queueUrl; private readonly AmazonSQSClient _client; @@ -30,12 +29,14 @@ public partial class SqsMessageSender /// /// The queue ARN /// The SQS Client - public SqsMessageSender(string queueUrl, AmazonSQSClient client) + /// The factory used to create a logger for this sender + public SqsMessageSender(string queueUrl, AmazonSQSClient client, ILoggerFactory loggerFactory) { + _logger = loggerFactory.CreateLogger(); _queueUrl = queueUrl; _client = client; } - + /// /// Sending message via SQS /// @@ -72,7 +73,7 @@ private SendMessageRequest CreateSendMessageRequest(Message message, TimeSpan? d return request; } - private static void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) + private void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) { delay ??= TimeSpan.Zero; if (delay > TimeSpan.Zero) @@ -80,7 +81,7 @@ private static void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) if (delay.Value > s_maxDelay) { delay = s_maxDelay; - Log.DelaySetToMaximum(s_logger, delay); + Log.DelaySetToMaximum(_logger, delay); } request.DelaySeconds = (int)delay.Value.TotalSeconds; @@ -93,7 +94,7 @@ private static void SetFifoQueueProperties(SendMessageRequest request, Message m { return; } - + request.MessageGroupId = message.Header.PartitionKey; if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId)) { @@ -155,7 +156,7 @@ private static string CreateCloudEventHeadersJson(Message message) if (message.Header.DataRef != null) cloudEventHeaders[HeaderNames.DataRef] = message.Header.DataRef; - + if (message.Header.TraceParent != null) cloudEventHeaders[HeaderNames.TraceParent] = message.Header.TraceParent.Value; diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsProducerRegistryFactory.cs index 7a63463a4c..86ef37395e 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsProducerRegistryFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS.V4; @@ -36,18 +37,22 @@ public class SqsProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _sqsPublications; + private readonly ILoggerFactory _loggerFactory; /// /// Create a collection of producers from the publication information /// /// The Connection to use to connect to AWS /// The publication describing the SNS topic that we want to use + /// The factory used to create loggers for the producers. public SqsProducerRegistryFactory( AWSMessagingGatewayConnection connection, - IEnumerable sqsPublications) + IEnumerable sqsPublications, + ILoggerFactory loggerFactory) { _connection = connection; _sqsPublications = sqsPublications; + _loggerFactory = loggerFactory; } /// @@ -56,7 +61,7 @@ public SqsProducerRegistryFactory( /// The with . public IAmAProducerRegistry Create() { - var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications); + var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -67,7 +72,7 @@ public IAmAProducerRegistry Create() /// The with . public async Task CreateAsync(CancellationToken ct = default) { - var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications); + var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications, _loggerFactory); return new ProducerRegistry(await producerFactory.CreateAsync()); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/AWSMessagingGateway.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/AWSMessagingGateway.cs index 56075ca433..fe7f6e08d7 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/AWSMessagingGateway.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/AWSMessagingGateway.cs @@ -37,19 +37,25 @@ THE SOFTWARE. */ using Amazon.SQS.Model; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AWSSQS.Extensions; using Paramore.Brighter.Tasks; using InvalidOperationException = System.InvalidOperationException; namespace Paramore.Brighter.MessagingGateway.AWSSQS; -public class AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection) +public class AwsMessagingGateway { - protected static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + protected readonly ILogger _logger; - private readonly AWSClientFactory _awsClientFactory = new(awsConnection); - protected readonly AWSMessagingGatewayConnection AwsConnection = awsConnection; + private readonly AWSClientFactory _awsClientFactory; + protected readonly AWSMessagingGatewayConnection AwsConnection; + + public AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + _awsClientFactory = new AWSClientFactory(awsConnection); + AwsConnection = awsConnection; + } /// /// The Channel Address @@ -87,16 +93,16 @@ public class AwsMessagingGateway(AWSMessagingGatewayConnection awsConnection) ChannelQueueUrl = makeChannel switch { //on validate or assume, turn a routing key into a queueUrl - OnMissingChannel.Assume or OnMissingChannel.Validate => + OnMissingChannel.Assume or OnMissingChannel.Validate => await ValidateQueueAsync(queue, findQueueBy, sqsAttributes.Type, makeChannel, cancellationToken), - OnMissingChannel.Create => + OnMissingChannel.Create => await CreateQueueAsync(queue, sqsAttributes, cancellationToken), _ => ChannelQueueUrl }; return ChannelQueueUrl; } - + protected RoutingKey EnsureSubscription( bool isFifo, string queueUrl, @@ -106,7 +112,7 @@ protected RoutingKey EnsureSubscription( SqsAttributes? sqsAttributes, OnMissingChannel makeChannels = OnMissingChannel.Create) => BrighterAsyncContext.Run(() => EnsureSubscriptionAsync(isFifo, queueUrl, routingKey, findTopicBy, snsAttributes, sqsAttributes, makeChannels)); - + protected async Task EnsureSubscriptionAsync( bool isFifo, @@ -149,7 +155,7 @@ await CheckQueueSubscribedAsync( ChannelTopicArn = makeTopic switch { //on validate or assume, turn a routing key into a topicARN - OnMissingChannel.Assume or OnMissingChannel.Validate => + OnMissingChannel.Assume or OnMissingChannel.Validate => await ValidateTopicAsync(topic, topicFindBy, type, cancellationToken), OnMissingChannel.Create => await CreateTopicAsync(topic, attributes), @@ -158,7 +164,7 @@ await CreateTopicAsync(topic, attributes), return ChannelTopicArn; } - + private async Task CheckQueueSubscribedAsync( string queueUrl, SqsAttributes? sqsAttributes, @@ -200,11 +206,11 @@ private async Task CheckSubscriptionAsync(OnMissingChannel makeSubscriptions, private async Task CreateTopicAsync(RoutingKey topic, SnsAttributes? snsAttributes) { snsAttributes ??= SnsAttributes.Empty; - + using var snsClient = _awsClientFactory.CreateSnsClient(); var topicName = topic.Value; - + if (snsAttributes.Type == SqsType.Fifo) { topicName = topic.ToValidSNSTopicName(true); @@ -320,7 +326,8 @@ private async Task CreateDeadLetterQueueAsync( CreateCommonQueueAttributes(sqsAttributes, isDLQ, attributes); - if (sqsAttributes.Type != SqsType.Fifo) return attributes; + if (sqsAttributes.Type != SqsType.Fifo) + return attributes; CreateFifoQueueAttributes(sqsAttributes, attributes); @@ -336,8 +343,8 @@ private static void CreateFifoQueueAttributes(SqsAttributes sqsAttributes, Dicti } if (sqsAttributes.DeduplicationScope == null || sqsAttributes.FifoThroughputLimit == null) - return ; - + return; + attributes.Add(QueueAttributeName.FifoThroughputLimit, Convert.ToString(sqsAttributes.FifoThroughputLimit.Value.AsString())); attributes.Add(QueueAttributeName.DeduplicationScope, sqsAttributes.DeduplicationScope switch { @@ -352,7 +359,7 @@ private void CreateCommonQueueAttributes(SqsAttributes sqsAttributes, bool isDLQ { var policy = new { - maxReceiveCount = sqsAttributes.RedrivePolicy.MaxReceiveCount, + maxReceiveCount = sqsAttributes.RedrivePolicy.MaxReceiveCount, deadLetterTargetArn = ChannelDeadLetterQueueArn }; @@ -410,8 +417,9 @@ private static List CreateTopicTags(SnsAttributes? snsAttributes) if (!string.IsNullOrEmpty(snsAttributes.Policy)) attributes.Add("Policy", snsAttributes.Policy); - if (snsAttributes.Type != SqsType.Fifo) return attributes; - + if (snsAttributes.Type != SqsType.Fifo) + return attributes; + attributes.Add("FifoTopic", "true"); if (snsAttributes.ContentBasedDeduplication) { diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/ChannelFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/ChannelFactory.cs index b8ba6a853e..bd289266f8 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/ChannelFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/ChannelFactory.cs @@ -51,10 +51,10 @@ public partial class ChannelFactory : AwsMessagingGateway, IAmAChannelFactory /// Initializes a new instance of the class. /// /// The details of the subscription to AWS. - public ChannelFactory(AWSMessagingGatewayConnection awsConnection) - : base(awsConnection) + public ChannelFactory(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) + : base(awsConnection, loggerFactory) { - _messageConsumerFactory = new SqsMessageConsumerFactory(awsConnection); + _messageConsumerFactory = new SqsMessageConsumerFactory(awsConnection, loggerFactory); _retryPolicy = Policy .Handle() .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10)]); @@ -169,7 +169,7 @@ await QueueExistsAsync(sqsClient, } catch (Exception) { - Log.CouldNotDeleteQueue(s_logger, queueExists.queueUrl); + Log.CouldNotDeleteQueue(_logger, queueExists.queueUrl); } } } @@ -196,7 +196,7 @@ public async Task DeleteTopicAsync() } catch (Exception) { - Log.CouldNotDeleteTopic(s_logger, ChannelTopicArn); + Log.CouldNotDeleteTopic(_logger, ChannelTopicArn); } } } @@ -311,7 +311,7 @@ private async Task UnsubscribeFromTopicAsync(AmazonSimpleNotificationServiceClie await snsClient.UnsubscribeAsync(new UnsubscribeRequest { SubscriptionArn = sub.SubscriptionArn }); if (unsubscribe.HttpStatusCode != HttpStatusCode.OK) { - Log.ErrorUnsubscribingFromTopic(s_logger, ChannelAddress, sub.SubscriptionArn); + Log.ErrorUnsubscribingFromTopic(_logger, ChannelAddress, sub.SubscriptionArn); } } } while (response.NextToken != null); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducer.cs index 11ca22270c..1a74965a05 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducer.cs @@ -65,10 +65,11 @@ public Publication Publication /// How do we connect to AWS in order to manage middleware /// Configuration of a producer /// - public SnsMessageProducer(AWSMessagingGatewayConnection connection, - SnsPublication publication, + public SnsMessageProducer(AWSMessagingGatewayConnection connection, + SnsPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) - : base(connection) + : base(connection, loggerFactory) { _publication = publication; _clientFactory = new AWSClientFactory(connection); @@ -179,7 +180,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use } BrighterTracer.WriteProducerEvent(Span, "aws_sns", message, _options); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); await ConfirmTopicExistsAsync(message.Header.Topic, cancellationToken); @@ -195,7 +196,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use throw new InvalidOperationException( $"Failed to publish message with topic {message.Header.Topic} and id {message.Id} and message: {message.Body}"); - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, messageId); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, messageId); } private static partial class Log diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducerFactory.cs index 213354fec5..954ff52578 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducerFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS; @@ -33,18 +34,22 @@ public class SnsMessageProducerFactory : IAmAMessageProducerFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Creates a collection of SNS message producers from the SNS publication information /// /// The Connection to use to connect to AWS /// The publications describing the SNS topics that we want to use + /// The factory used to create loggers for the producers. public SnsMessageProducerFactory( AWSMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { _connection = connection; _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -60,9 +65,9 @@ public Dictionary Create() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SnsMessageProducer(_connection, publication); + var producer = new SnsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); producer.Publication = publication; - + if (producer.ConfirmTopicExists()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); @@ -92,9 +97,9 @@ public async Task> CreateAsync() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SnsMessageProducer(_connection, publication); + var producer = new SnsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); producer.Publication = publication; - + if (await producer.ConfirmTopicExistsAsync()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsProducerRegistryFactory.cs index 7f7a2f1179..e1fb2563dd 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsProducerRegistryFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS; @@ -36,18 +37,22 @@ public class SnsProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _snsPublications; + private readonly ILoggerFactory _loggerFactory; /// /// Create a collection of producers from the publication information /// /// The Connection to use to connect to AWS /// The publication describing the SNS topic that we want to use + /// The factory used to create loggers for the producers. public SnsProducerRegistryFactory( AWSMessagingGatewayConnection connection, - IEnumerable snsPublications) + IEnumerable snsPublications, + ILoggerFactory loggerFactory) { _connection = connection; _snsPublications = snsPublications; + _loggerFactory = loggerFactory; } /// @@ -56,7 +61,7 @@ public SnsProducerRegistryFactory( /// The with . public IAmAProducerRegistry Create() { - var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications); + var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -67,7 +72,7 @@ public IAmAProducerRegistry Create() /// The with . public async Task CreateAsync(CancellationToken ct = default) { - var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications); + var producerFactory = new SnsMessageProducerFactory(_connection, _snsPublications, _loggerFactory); return new ProducerRegistry(await producerFactory.CreateAsync()); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsInlineMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsInlineMessageCreator.cs index 1d95465400..164cf5334e 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsInlineMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsInlineMessageCreator.cs @@ -31,17 +31,21 @@ THE SOFTWARE. */ using Amazon.SQS; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.MessagingGateway.AWSSQS; internal sealed partial class SqsInlineMessageCreator : SqsMessageCreatorBase, ISqsMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private Dictionary _messageAttributes = new(); + public SqsInlineMessageCreator(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } + public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) { var topic = HeaderResult.Empty(); @@ -54,7 +58,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) topic = ReadTopic(); messageId = ReadMessageId(); - var cloudEvents = ReadMessageCloudEvents(); + var cloudEvents = ReadMessageCloudEvents(); var contentType = ReadContentType(cloudEvents); var correlationId = ReadCorrelationId(); var handledCount = ReadHandledCount(); @@ -72,11 +76,11 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) var traceParent = ReadCloudEventsTraceParent(cloudEvents); var traceState = ReadCloudEventsTraceState(cloudEvents); var baggage = ReadCloudEventsBaggage(cloudEvents); - + var bag = ReadMessageBag(); if (deduplicationId.Success) { - bag[HeaderNames.DeduplicationId] = deduplicationId.Result; + bag[HeaderNames.DeduplicationId] = deduplicationId.Result; } if (receiptHandle.Success) @@ -112,12 +116,12 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) } catch (Exception e) { - Log.FailedToCreateMessageFromAwsSqsMessage(s_logger, e); + Log.FailedToCreateMessageFromAwsSqsMessage(_logger, e); return Message.FailureMessage(topic.Result, messageId.Result); } } - private static Dictionary ReadMessageAttributes(JsonDocument jsonDocument) + private Dictionary ReadMessageAttributes(JsonDocument jsonDocument) { var messageAttributes = new Dictionary(); @@ -132,7 +136,7 @@ private static Dictionary ReadMessageAttributes(JsonDocumen } catch (Exception ex) { - Log.FailedWhileDeserializingSqsMessageBody(s_logger, ex); + Log.FailedWhileDeserializingSqsMessageBody(_logger, ex); } return messageAttributes ?? new Dictionary(); @@ -148,7 +152,7 @@ private HeaderResult ReadContentType(Dictionary hea return new HeaderResult(new ContentType(result), true); } } - + if (_messageAttributes.TryGetValue(HeaderNames.ContentType, out contentType)) { var result = contentType.GetValueInString(); @@ -157,7 +161,7 @@ private HeaderResult ReadContentType(Dictionary hea return new HeaderResult(new ContentType(result), true); } } - + if (headers.TryGetValue(HeaderNames.DataContentType, out var val)) { return new HeaderResult(new ContentType(val), true); @@ -203,7 +207,7 @@ private Dictionary ReadMessageBag() return bag; } - + private Dictionary ReadMessageCloudEvents() { if (_messageAttributes.TryGetValue(HeaderNames.CloudEventHeaders, out var headerBag)) @@ -247,7 +251,7 @@ private HeaderResult ReadSpecVersion(Dictionary headers) { return new HeaderResult(specVersion.GetValueInString(), true); } - + if (headers.TryGetValue(HeaderNames.SpecVersion, out var val)) { return new HeaderResult(val, true); @@ -264,10 +268,11 @@ private HeaderResult ReadType(Dictionary header if (!string.IsNullOrEmpty(val)) { return new HeaderResult(new CloudEventsType(val!), true); - }; + } + ; } - - if (headers.TryGetValue(HeaderNames.Type, out var cloudEventType) + + if (headers.TryGetValue(HeaderNames.Type, out var cloudEventType) && !string.IsNullOrEmpty(cloudEventType)) { return new HeaderResult(new CloudEventsType(cloudEventType), true); @@ -275,7 +280,7 @@ private HeaderResult ReadType(Dictionary header return new HeaderResult(CloudEventsType.Empty, true); } - + private HeaderResult ReadSource(Dictionary headers) { if (_messageAttributes.TryGetValue(HeaderNames.Source, out var source) @@ -283,7 +288,7 @@ private HeaderResult ReadSource(Dictionary headers) { return new HeaderResult(uri, true); } - + if (headers.TryGetValue(HeaderNames.Source, out var val) && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) { @@ -292,46 +297,46 @@ private HeaderResult ReadSource(Dictionary headers) return new HeaderResult(new Uri(MessageHeader.DefaultSource), true); } - - private HeaderResult ReadDataSchema(Dictionary headers) - { - if (_messageAttributes.TryGetValue(HeaderNames.DataSchema, out var source) - && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) - - { - return new HeaderResult(uri, true); - } - - if (headers.TryGetValue(HeaderNames.DataSchema, out var val) - && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) - { - return new HeaderResult(uri, true); - } - - return new HeaderResult(null, true); - } + + private HeaderResult ReadDataSchema(Dictionary headers) + { + if (_messageAttributes.TryGetValue(HeaderNames.DataSchema, out var source) + && Uri.TryCreate(source.GetValueInString(), UriKind.RelativeOrAbsolute, out var uri)) + + { + return new HeaderResult(uri, true); + } + + if (headers.TryGetValue(HeaderNames.DataSchema, out var val) + && Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out uri)) + { + return new HeaderResult(uri, true); + } + + return new HeaderResult(null, true); + } private HeaderResult ReadTimestamp(Dictionary headers) { - if (headers.TryGetValue(HeaderNames.Timestamp, out var val) - && DateTimeOffset.TryParse(val, out var value)) - { - return new HeaderResult(value, true); - } - - if (_messageAttributes.TryGetValue(HeaderNames.Time, out var timeStamp) - && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) - { - return new HeaderResult(value, true); - } - - if (_messageAttributes.TryGetValue(HeaderNames.Timestamp, out timeStamp) - && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) - { - return new HeaderResult(value, true); - } - - return new HeaderResult(DateTimeOffset.UtcNow, true); + if (headers.TryGetValue(HeaderNames.Timestamp, out var val) + && DateTimeOffset.TryParse(val, out var value)) + { + return new HeaderResult(value, true); + } + + if (_messageAttributes.TryGetValue(HeaderNames.Time, out var timeStamp) + && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) + { + return new HeaderResult(value, true); + } + + if (_messageAttributes.TryGetValue(HeaderNames.Timestamp, out timeStamp) + && DateTimeOffset.TryParse(timeStamp.GetValueInString(), out value)) + { + return new HeaderResult(value, true); + } + + return new HeaderResult(DateTimeOffset.UtcNow, true); } private HeaderResult ReadMessageType() @@ -410,32 +415,32 @@ private HeaderResult ReadTopic() private HeaderResult ReadMessageSubject(JsonDocument jsonDocument, Dictionary headers) { - if (_messageAttributes.TryGetValue(HeaderNames.Subject, out var messageId)) - { - return new HeaderResult(messageId.GetValueInString(), true); - } - - try - { - if (jsonDocument.RootElement.TryGetProperty("Subject", out var value)) - { - return new HeaderResult(value.GetString(), true); - } - - if (headers.TryGetValue(HeaderNames.Subject, out var subject)) - { - return new HeaderResult(subject, true); - } - } - catch (Exception ex) - { - Log.FailedToParseSqsMessageBodyToValidJsonDocument(s_logger, ex); - } - - return new HeaderResult(null, true); + if (_messageAttributes.TryGetValue(HeaderNames.Subject, out var messageId)) + { + return new HeaderResult(messageId.GetValueInString(), true); + } + + try + { + if (jsonDocument.RootElement.TryGetProperty("Subject", out var value)) + { + return new HeaderResult(value.GetString(), true); + } + + if (headers.TryGetValue(HeaderNames.Subject, out var subject)) + { + return new HeaderResult(subject, true); + } + } + catch (Exception ex) + { + Log.FailedToParseSqsMessageBodyToValidJsonDocument(_logger, ex); + } + + return new HeaderResult(null, true); } - private static MessageBody ReadMessageBody(JsonDocument jsonDocument) + private MessageBody ReadMessageBody(JsonDocument jsonDocument) { try { @@ -446,7 +451,7 @@ private static MessageBody ReadMessageBody(JsonDocument jsonDocument) } catch (Exception ex) { - Log.FailedToParseSqsMessageBodyToValidJsonDocument(s_logger, ex); + Log.FailedToParseSqsMessageBodyToValidJsonDocument(_logger, ex); } return new MessageBody(string.Empty); @@ -473,34 +478,34 @@ private static HeaderResult ReadDeduplicationId(Amazon.SQS.Model.Message return new HeaderResult(string.Empty, false); } - - private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceParent, out var value)) { return new HeaderResult(new TraceParent(value), true); } - + return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceState, out var value)) { return new HeaderResult(new TraceState(value), true); - } + } return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) { var baggage = new Baggage(); if (cloudEventHeaders.TryGetValue(HeaderNames.Baggage, out var value)) { baggage.LoadBaggage(value); - } - + } + return new HeaderResult(baggage, true); } @@ -511,7 +516,7 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Failed while deserializing Sqs Message body")] public static partial void FailedWhileDeserializingSqsMessageBody(ILogger logger, Exception ex); - + [LoggerMessage(LogLevel.Warning, "Failed to parse Sqs Message Body to valid Json Document")] public static partial void FailedToParseSqsMessageBodyToValidJsonDocument(ILogger logger, Exception ex); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumer.cs index 339242f936..ed1d6e6acf 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumer.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using Amazon.SQS.Model; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.AWSSQS @@ -42,9 +41,10 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS /// public partial class SqsMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly AWSMessagingGatewayConnection _connection; + private readonly ILoggerFactory _loggerFactory; private readonly AWSClientFactory _clientFactory; private readonly string _queueName; private readonly int _batchSize; @@ -70,9 +70,11 @@ public partial class SqsMessageConsumer : IAmAMessageConsumerSync, IAmAMessageCo /// Is the queue name a queue url? /// Do we have Raw Message Delivery enabled? /// The for the queue (used by DLQ producers for FIFO support) + /// The factory used to create a logger for this consumer public SqsMessageConsumer( AWSMessagingGatewayConnection awsConnection, string? queueName, + ILoggerFactory loggerFactory, int batchSize = 1, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null, @@ -84,6 +86,8 @@ public SqsMessageConsumer( if (string.IsNullOrEmpty(queueName)) throw new ConfigurationException("QueueName is mandatory"); + _logger = loggerFactory.CreateLogger(); + _loggerFactory = loggerFactory; _connection = awsConnection; _clientFactory = new AWSClientFactory(awsConnection); _queueName = queueName!; @@ -131,12 +135,12 @@ public SqsMessageConsumer( await DeleteSourceMessageAsync(receiptHandle!, message.Id.Value, cancellationToken); } - /// + /// /// Purges the specified queue name. /// Sync over Async /// public void Purge() => BrighterAsyncContext.Run(() => PurgeAsync()); - + /// /// Purges the specified queue name. /// @@ -145,21 +149,21 @@ public SqsMessageConsumer( try { using var client = _clientFactory.CreateSqsClient(); - Log.PurgingQueue(s_logger, _queueName); + Log.PurgingQueue(_logger, _queueName); await EnsureChannelUrl(client, cancellationToken); await client.PurgeQueueAsync(_channelUrl, cancellationToken); - Log.PurgedQueue(s_logger, _queueName); + Log.PurgedQueue(_logger, _queueName); } catch (Exception exception) { - Log.ErrorPurgingQueue(s_logger, exception, _queueName); + Log.ErrorPurgingQueue(_logger, exception, _queueName); throw; } } - - /// + + /// /// Receives the specified queue name. /// Sync over async /// @@ -179,11 +183,11 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, try { client = _clientFactory.CreateSqsClient(); - + await EnsureChannelUrl(client, cancellationToken); timeOut ??= TimeSpan.Zero; - Log.RetrievingNextMessage(s_logger,_channelUrl!); + Log.RetrievingNextMessage(_logger, _channelUrl!); var request = new ReceiveMessageRequest(_channelUrl) { @@ -199,17 +203,17 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, } catch (InvalidOperationException ioe) { - Log.CouldNotDetermineNumberOfMessagesToRetrieve(s_logger); + Log.CouldNotDetermineNumberOfMessagesToRetrieve(_logger); throw new ChannelFailureException("Error connecting to SQS, see inner exception for details", ioe); } catch (OperationCanceledException oce) { - Log.CouldNotFindMessagesToRetrieve(s_logger); + Log.CouldNotFindMessagesToRetrieve(_logger); throw new ChannelFailureException("Error connecting to SQS, see inner exception for details", oce); } catch (Exception e) { - Log.ErrorListeningToQueue(s_logger, e, _queueName); + Log.ErrorListeningToQueue(_logger, e, _queueName); throw; } finally @@ -225,14 +229,14 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, var messages = new Message[sqsMessages.Length]; for (int i = 0; i < sqsMessages.Length; i++) { - var message = SqsMessageCreatorFactory.Create(_rawMessageDelivery).CreateMessage(sqsMessages[i]); - Log.ReceivedMessageFromQueue(s_logger, _queueName, Environment.NewLine, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); + var message = SqsMessageCreatorFactory.Create(_rawMessageDelivery, _loggerFactory).CreateMessage(sqsMessages[i]); + Log.ReceivedMessageFromQueue(_logger, _queueName, Environment.NewLine, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); messages[i] = message; } return messages; } - + /// /// Rejects the specified message. /// Sync over async @@ -258,14 +262,14 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, var reasonString = reason is null ? nameof(RejectionReason.DeliveryError) : reason.RejectionReason.ToString(); var description = reason is null ? "unknown" : reason.Description ?? "unknown"; - Log.RejectingMessage(s_logger, message.Id.Value, receiptHandle, _queueName, reasonString, description); + Log.RejectingMessage(_logger, message.Id.Value, receiptHandle, _queueName, reasonString, description); // If no channels configured, just delete the original message if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); } await AcknowledgeAsync(message, cancellationToken); @@ -286,7 +290,7 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -297,18 +301,18 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // Sending to DLQ failed — delete the original to prevent infinite // reprocessing. The message is lost rather than stuck in a retry loop. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); await DeleteSourceMessageAsync(receiptHandle!, message.Id.Value, cancellationToken); return true; } @@ -340,7 +344,7 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken try { - Log.NackingMessage(s_logger, message.Id.Value, receiptHandle, _queueName); + Log.NackingMessage(_logger, message.Id.Value, receiptHandle, _queueName); using var client = _clientFactory.CreateSqsClient(); await EnsureChannelUrl(client, cancellationToken); @@ -349,7 +353,7 @@ await client.ChangeMessageVisibilityAsync( cancellationToken ); - Log.NackedMessage(s_logger, message.Id.Value, receiptHandle, _channelUrl!); + Log.NackedMessage(_logger, message.Id.Value, receiptHandle, _channelUrl!); } catch (ReceiptHandleIsInvalidException ex) { @@ -357,11 +361,11 @@ await client.ChangeMessageVisibilityAsync( // SQS has already made the message visible again for redelivery by another consumer. // Nack sets visibility to zero for immediate redelivery — but the message is already // visible again, so the net effect is the same. Log a warning and continue. - Log.NackFailedReceiptHandleExpired(s_logger, ex, message.Id.Value, receiptHandle, _queueName); + Log.NackFailedReceiptHandleExpired(_logger, ex, message.Id.Value, receiptHandle, _queueName); } catch (Exception exception) { - Log.ErrorNackingMessage(s_logger, exception, message.Id.Value, receiptHandle, _queueName); + Log.ErrorNackingMessage(_logger, exception, message.Id.Value, receiptHandle, _queueName); throw; } } @@ -393,7 +397,7 @@ public async Task RequeueAsync(Message message, TimeSpan? delay = null, try { - Log.RequeueingMessage(s_logger, message.Id.Value); + Log.RequeueingMessage(_logger, message.Id.Value); using (var client = _clientFactory.CreateSqsClient()) { @@ -404,7 +408,7 @@ await client.ChangeMessageVisibilityAsync( ); } - Log.RequeuedMessage(s_logger, message.Id.Value); + Log.RequeuedMessage(_logger, message.Id.Value); return true; } @@ -413,12 +417,12 @@ await client.ChangeMessageVisibilityAsync( // Receipt handle is invalid (most likely because the visibility timeout elapsed). // SQS has already made the message visible again for redelivery by another consumer, // but without the intended delay. Log a warning so operators are aware. - Log.RequeueFailedReceiptHandleExpired(s_logger, ex, message.Id.Value, receiptHandle, _queueName, delay.Value); + Log.RequeueFailedReceiptHandleExpired(_logger, ex, message.Id.Value, receiptHandle, _queueName, delay.Value); return false; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value, receiptHandle, _queueName); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value, receiptHandle, _queueName); return false; } } @@ -451,7 +455,7 @@ public async ValueTask DisposeAsync() GC.SuppressFinalize(this); } - + private SqsMessageProducer? CreateDeadLetterProducer() { var publication = new SqsPublication( @@ -465,11 +469,11 @@ public async ValueTask DisposeAsync() // We must NOT call the sync ConfirmQueueExists here because the lazy is resolved // inside RejectAsync, which may already be running inside BrighterAsyncContext.Run // from the sync Reject path — nesting would deadlock. - return new SqsMessageProducer(_connection, publication); + return new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingDlqProducerException(s_logger, e, _deadLetterRoutingKey.Value); + Log.ErrorCreatingDlqProducerException(_logger, e, _deadLetterRoutingKey.Value); return null; } } @@ -484,11 +488,11 @@ public async ValueTask DisposeAsync() try { // Queue existence is confirmed on first SendAsync via ConfirmQueueExistsAsync. - return new SqsMessageProducer(_connection, publication); + return new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingInvalidMessageProducerException(s_logger, e, _invalidMessageRoutingKey.Value); + Log.ErrorCreatingInvalidMessageProducerException(_logger, e, _invalidMessageRoutingKey.Value); return null; } } @@ -503,7 +507,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea // Remove SQS-specific headers that will be reset when sent to the DLQ message.Header.Bag.Remove("ReceiptHandle"); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -521,7 +526,7 @@ private async Task DeleteSourceMessageAsync(string receiptHandle, string message await client.DeleteMessageAsync(new DeleteMessageRequest(_channelUrl, receiptHandle), cancellationToken); - Log.DeletedMessage(s_logger, messageId, receiptHandle, _channelUrl!); + Log.DeletedMessage(_logger, messageId, receiptHandle, _channelUrl!); } catch (ReceiptHandleIsInvalidException ex) { @@ -529,11 +534,11 @@ await client.DeleteMessageAsync(new DeleteMessageRequest(_channelUrl, receiptHan // SQS has already made the message visible again for redelivery by another consumer. // This is an error because the message was not deleted and may be processed again; // handlers should be idempotent, but an operator may need to investigate. - Log.DeleteFailedReceiptHandleExpired(s_logger, ex, messageId, receiptHandle, _queueName); + Log.DeleteFailedReceiptHandleExpired(_logger, ex, messageId, receiptHandle, _queueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, messageId, receiptHandle, _queueName); + Log.ErrorDeletingMessage(_logger, exception, messageId, receiptHandle, _queueName); throw; } } @@ -566,8 +571,8 @@ private async Task EnsureChannelUrl(AmazonSQSClient client, CancellationToken ca //only grab the queue url once if (_channelUrl is not null) return; - - var urlResponse = await client.GetQueueUrlAsync(_queueName, cancellationToken); + + var urlResponse = await client.GetQueueUrlAsync(_queueName, cancellationToken); _channelUrl = urlResponse.QueueUrl; } @@ -602,7 +607,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "SqsMessageConsumer: Error purging queue {ChannelName}")] public static partial void ErrorPurgingQueue(ILogger logger, Exception exception, string channelName); - + [LoggerMessage(LogLevel.Debug, "SqsMessageConsumer: Preparing to retrieve next message from queue {Url}")] public static partial void RetrievingNextMessage(ILogger logger, string url); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumerFactory.cs index 15ca336fe2..8ddc9931a2 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumerFactory.cs @@ -21,6 +21,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.AWSSQS { /// @@ -29,13 +31,15 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS public class SqsMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly AWSMessagingGatewayConnection _awsConnection; + private readonly ILoggerFactory _loggerFactory; /// /// Initializes a new instance of the class. /// - public SqsMessageConsumerFactory(AWSMessagingGatewayConnection awsConnection) + public SqsMessageConsumerFactory(AWSMessagingGatewayConnection awsConnection, ILoggerFactory loggerFactory) { _awsConnection = awsConnection; + _loggerFactory = loggerFactory; } /// @@ -57,12 +61,13 @@ public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) private SqsMessageConsumer CreateImpl(Subscription subscription) { SqsSubscription? sqsSubscription = subscription as SqsSubscription; - if (sqsSubscription == null) throw new ConfigurationException("We expect an SqsSubscription or SqsSubscription as a parameter"); + if (sqsSubscription == null) + throw new ConfigurationException("We expect an SqsSubscription or SqsSubscription as a parameter"); //if it is a url, don't alter; if it is just a name, ensure it is valid ChannelName queueName = subscription.ChannelName; if (sqsSubscription.FindQueueBy == QueueFindBy.Name) - queueName =queueName.ToValidSQSQueueName(sqsSubscription.QueueAttributes.Type == SqsType.Fifo); + queueName = queueName.ToValidSQSQueueName(sqsSubscription.QueueAttributes.Type == SqsType.Fifo); // Extract DLQ and invalid message routing keys if subscription supports them RoutingKey? deadLetterRoutingKey = null; @@ -87,7 +92,8 @@ private SqsMessageConsumer CreateImpl(Subscription subscription) makeChannels: sqsSubscription.MakeChannels, isQueueUrl: (sqsSubscription.FindQueueBy == QueueFindBy.Url), rawMessageDelivery: sqsSubscription.QueueAttributes.RawMessageDelivery, - queueAttributes: sqsSubscription.QueueAttributes + queueAttributes: sqsSubscription.QueueAttributes, + loggerFactory: _loggerFactory ); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreator.cs index e9b3c9a2e2..bb94ea8a74 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreator.cs @@ -34,7 +34,6 @@ THE SOFTWARE. */ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Transforms.Transformers; @@ -55,7 +54,12 @@ internal enum ARNAmazonSNS internal sealed partial class SqsMessageCreator : SqsMessageCreatorBase, ISqsMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + + public SqsMessageCreator(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) { @@ -92,7 +96,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) messageId: messageId.Result ?? Id.Empty, topic: topic.Result ?? RoutingKey.Empty, messageType.Result, - source: source.Result, + source: source.Result, type: type.Result, timeStamp: timeStamp.Result, correlationId: correlationId.Success ? correlationId.Result : Id.Empty, @@ -117,7 +121,7 @@ public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage) } catch (Exception e) { - Log.FailedToCreateMessageFromAmqpMessage(s_logger, e); + Log.FailedToCreateMessageFromAmqpMessage(_logger, e); return Message.FailureMessage(topic.Result, messageId.Success ? messageId.Result : Id.Empty); } } @@ -147,7 +151,7 @@ private static void PopulateBag(Dictionary bag, HeaderResult(null, false); } - + private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model.Message sqsMessage) { if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.CloudEventHeaders, out var value)) @@ -162,11 +166,12 @@ private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model catch (Exception) { //we weill just suppress conversion errors, and return an empty bag - } } + } + } return new Dictionary(); } - + private static HeaderResult ReadCloudEventSource(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.Source, out var value)) @@ -179,13 +184,13 @@ private static Dictionary ReadCloudEventHeaders(Amazon.SQS.Model return new HeaderResult(null, false); } - - private static HeaderResult ReadCloudEventsSpecVersion(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsSpecVersion(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.SpecVersion, out var value)) { return new HeaderResult(value, true); - } + } return new HeaderResult(MessageHeader.DefaultSpecVersion, true); } @@ -198,34 +203,34 @@ private static HeaderResult ReadCloudEventsSpecVersion(Dictionary(CloudEventsType.Empty, false); } - - private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceParent(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceParent, out var value)) { return new HeaderResult(new TraceParent(value), true); } - + return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsTraceState(Dictionary cloudEventHeaders) { if (cloudEventHeaders.TryGetValue(HeaderNames.TraceState, out var value)) { return new HeaderResult(new TraceState(value), true); - } + } return new HeaderResult(null, true); } - - private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) + + private static HeaderResult ReadCloudEventsBaggage(Dictionary cloudEventHeaders) { var baggage = new Baggage(); if (cloudEventHeaders.TryGetValue(HeaderNames.Baggage, out var value)) { baggage.LoadBaggage(value); - } - + } + return new HeaderResult(baggage, true); } @@ -286,18 +291,18 @@ private static HeaderResult ReadReplyTo(Amazon.SQS.Model.Message sqs private static HeaderResult ReadTimestamp(Amazon.SQS.Model.Message sqsMessage, Dictionary headers) { - if (headers.TryGetValue(HeaderNames.Timestamp, out var val) + if (headers.TryGetValue(HeaderNames.Timestamp, out var val) && DateTimeOffset.TryParse(val, out var timestamp)) { return new HeaderResult(timestamp, true); } - + if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.Time, out var value) && DateTimeOffset.TryParse(value.StringValue, out timestamp)) { return new HeaderResult(timestamp, true); } - + if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.Timestamp, out value) && DateTimeOffset.TryParse(value.StringValue, out timestamp)) { @@ -349,13 +354,13 @@ private static HeaderResult ReadContentType(Amazon.SQS.Model.Messag { return new HeaderResult(new ContentType(value.StringValue), true); } - - if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.ContentType, out value) + + if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.ContentType, out value) && !string.IsNullOrEmpty(value.StringValue)) { return new HeaderResult(new ContentType(value.StringValue), true); } - + if (headers.TryGetValue(HeaderNames.DataContentType, out var val)) { return new HeaderResult(new ContentType(val), true); @@ -421,22 +426,22 @@ private static HeaderResult ReadDeduplicationId(Amazon.SQS.Model.Message return new HeaderResult(null, false); } - + private static HeaderResult ReadSubject(Amazon.SQS.Model.Message sqsMessage, Dictionary headers) { if (sqsMessage.MessageAttributes.TryGetValue(HeaderNames.Subject, out var value)) { return new HeaderResult(value.StringValue, true); } - + if (headers.TryGetValue(HeaderNames.Subject, out var subject)) { return new HeaderResult(subject, true); } - + return new HeaderResult(null, false); } - + private static partial class Log { [LoggerMessage(LogLevel.Warning, "Failed to create message from amqp message")] diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreatorFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreatorFactory.cs index a15ad868c5..42bbeaa067 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreatorFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreatorFactory.cs @@ -21,18 +21,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.AWSSQS { internal sealed class SqsMessageCreatorFactory { - public static ISqsMessageCreator Create(bool rawMessageDelivery) + public static ISqsMessageCreator Create(bool rawMessageDelivery, ILoggerFactory loggerFactory) { if (rawMessageDelivery) { - return new SqsMessageCreator(); + return new SqsMessageCreator(loggerFactory); } - return new SqsInlineMessageCreator(); + return new SqsInlineMessageCreator(loggerFactory); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducer.cs index 6afbd0a103..7808813e60 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducer.cs @@ -41,6 +41,7 @@ public partial class SqsMessageProducer : AwsMessagingGateway, IAmAMessageProduc private readonly SqsPublication _publication; private readonly AWSClientFactory _clientFactory; private readonly InstrumentationOptions _instrumentation; + private readonly ILoggerFactory _loggerFactory; /// /// The publication configuration for this producer @@ -61,16 +62,18 @@ public partial class SqsMessageProducer : AwsMessagingGateway, IAmAMessageProduc /// How do we connect to AWS in order to manage middleware /// Configuration of a producer. Required. /// - public SqsMessageProducer(AWSMessagingGatewayConnection connection, + public SqsMessageProducer(AWSMessagingGatewayConnection connection, SqsPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) - : base(connection) + : base(connection, loggerFactory) { _publication = publication ?? throw new ArgumentNullException(nameof(publication)); - if (_publication.ChannelName is null) + if (_publication.ChannelName is null) throw new InvalidOperationException($"We must have a valid Channel Name on the Publication, either a queue name or a Url"); _clientFactory = new AWSClientFactory(connection); _instrumentation = instrumentation; + _loggerFactory = loggerFactory; if (publication.FindQueueBy == QueueFindBy.Url) { @@ -107,10 +110,10 @@ public async Task ConfirmQueueExistsAsync(CancellationToken cancellationTo //Only do this on first send for a queue for efficiency; won't auto-recreate when goes missing at runtime as a result if (!string.IsNullOrEmpty(ChannelQueueUrl)) return true; - + if (_publication is null) throw new ConfigurationException("No publication specified for producer"); - + if (_publication.ChannelName is null) throw new ConfigurationException("No channel name specified for publication"); @@ -121,7 +124,7 @@ public async Task ConfirmQueueExistsAsync(CancellationToken cancellationTo _publication.QueueAttributes, _publication.MakeChannels, cancellationToken); - + ChannelQueueUrl = queueUrl; return !string.IsNullOrEmpty(queueUrl); @@ -134,13 +137,13 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken /// public async Task SendWithDelayAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken = default) => await SendWithDelayAsync(message, delay, true, cancellationToken); - - + + private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool useAsyncScheduler, CancellationToken cancellationToken = default) { if (_publication is null) throw new ConfigurationException("No publication specified for producer"); - + delay ??= TimeSpan.Zero; // SQS support delay until 15min, more than that we are going to use scheduler if (delay > TimeSpan.FromMinutes(15) && _publication.QueueAttributes.Type == SqsType.Standard) @@ -156,14 +159,14 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use schedulerSync.Schedule(message, delay.Value); return; } - - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); BrighterTracer.WriteProducerEvent(Span, MessagingSystem.AWSSQS, message, _instrumentation); await ConfirmQueueExistsAsync(cancellationToken); using var client = _clientFactory.CreateSqsClient(); - var sender = new SqsMessageSender(ChannelQueueUrl!, client); + var sender = new SqsMessageSender(ChannelQueueUrl!, client, _loggerFactory); var messageId = await sender.SendAsync(message, delay, cancellationToken); if (messageId == null) @@ -172,7 +175,7 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use $"Failed to publish message with topic {message.Header.Topic} and id {message.Id} and message: {message.Body}"); } - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, messageId); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, messageId); } public void Send(Message message) => SendWithDelay(message, null); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducerFactory.cs index 9432b4f881..f0436ca15e 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducerFactory.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS; @@ -11,17 +12,21 @@ public class SqsMessageProducerFactory : IAmAMessageProducerFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Initialize new instance of . /// /// The . /// The collection of . + /// The factory used to create loggers for the producers. public SqsMessageProducerFactory(AWSMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { _connection = connection; _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -37,7 +42,7 @@ public Dictionary Create() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SqsMessageProducer(_connection, publication); + var producer = new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); if (producer.ConfirmQueueExists()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); @@ -68,7 +73,7 @@ public async Task> CreateAsync() if (publication.Topic is null) throw new ConfigurationException("Missing topic on Publication"); - var producer = new SqsMessageProducer(_connection, publication); + var producer = new SqsMessageProducer(_connection, publication, loggerFactory: _loggerFactory); if (await producer.ConfirmQueueExistsAsync()) { var producerKey = new ProducerKey(publication.Topic, publication.Type); diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs index fb43dd426f..8c67ce2335 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs @@ -12,7 +12,6 @@ using Newtonsoft.Json; using Paramore.Brighter.Extensions; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS; @@ -21,9 +20,9 @@ namespace Paramore.Brighter.MessagingGateway.AWSSQS; /// public partial class SqsMessageSender { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); private static readonly TimeSpan s_maxDelay = TimeSpan.FromSeconds(900); - + + private readonly ILogger _logger; private readonly string _queueUrl; private readonly AmazonSQSClient _client; @@ -32,12 +31,14 @@ public partial class SqsMessageSender /// /// The queue ARN /// The SQS Client - public SqsMessageSender(string queueUrl, AmazonSQSClient client) + /// The factory used to create a logger for this sender + public SqsMessageSender(string queueUrl, AmazonSQSClient client, ILoggerFactory loggerFactory) { + _logger = loggerFactory.CreateLogger(); _queueUrl = queueUrl; _client = client; } - + /// /// Sending message via SQS /// @@ -74,7 +75,7 @@ private SendMessageRequest CreateSendMessageRequest(Message message, TimeSpan? d return request; } - private static void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) + private void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) { delay ??= TimeSpan.Zero; if (delay > TimeSpan.Zero) @@ -82,7 +83,7 @@ private static void SetMessageDelay(SendMessageRequest request, TimeSpan? delay) if (delay.Value > s_maxDelay) { delay = s_maxDelay; - Log.DelaySetToMaximum(s_logger, delay); + Log.DelaySetToMaximum(_logger, delay); } request.DelaySeconds = (int)delay.Value.TotalSeconds; @@ -95,7 +96,7 @@ private static void SetFifoQueueProperties(SendMessageRequest request, Message m { return; } - + request.MessageGroupId = message.Header.PartitionKey; if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId)) { @@ -157,7 +158,7 @@ private static string CreateCloudEventHeadersJson(Message message) if (message.Header.DataRef != null) cloudEventHeaders[HeaderNames.DataRef] = message.Header.DataRef; - + if (message.Header.TraceParent != null) cloudEventHeaders[HeaderNames.TraceParent] = message.Header.TraceParent.Value; diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsProducerRegistryFactory.cs index eb3bc3c26f..083dffa2df 100644 --- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsProducerRegistryFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.AWSSQS; @@ -36,18 +37,22 @@ public class SqsProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly AWSMessagingGatewayConnection _connection; private readonly IEnumerable _sqsPublications; + private readonly ILoggerFactory _loggerFactory; /// /// Create a collection of producers from the publication information /// /// The Connection to use to connect to AWS /// The publication describing the SNS topic that we want to use + /// The factory used to create loggers for the producers. public SqsProducerRegistryFactory( AWSMessagingGatewayConnection connection, - IEnumerable sqsPublications) + IEnumerable sqsPublications, + ILoggerFactory loggerFactory) { _connection = connection; _sqsPublications = sqsPublications; + _loggerFactory = loggerFactory; } /// @@ -56,7 +61,7 @@ public SqsProducerRegistryFactory( /// The with . public IAmAProducerRegistry Create() { - var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications); + var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -67,7 +72,7 @@ public IAmAProducerRegistry Create() /// The with . public async Task CreateAsync(CancellationToken ct = default) { - var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications); + var producerFactory = new SqsMessageProducerFactory(_connection, _sqsPublications, _loggerFactory); return new ProducerRegistry(await producerFactory.CreateAsync()); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumer.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumer.cs index 268de563aa..7a94f28a91 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumer.cs @@ -57,10 +57,12 @@ public abstract partial class AzureServiceBusConsumer : IAmAMessageConsumerSync, /// The producer we want to send via /// The admin client for ASB /// Whether the consumer is async + /// The used to create loggers protected AzureServiceBusConsumer( - AzureServiceBusSubscription subscription, + AzureServiceBusSubscription subscription, IAmAMessageProducer messageProducer, IAdministrationClientWrapper administrationClientWrapper, + ILoggerFactory loggerFactory, bool isAsync = false ) { @@ -70,9 +72,9 @@ protected AzureServiceBusConsumer( SubscriptionConfiguration = subscription.Configuration ?? new AzureServiceBusSubscriptionConfiguration(); _messageProducer = messageProducer; AdministrationClientWrapper = administrationClientWrapper; - _azureServiceBusMesssageCreator = new AzureServiceBusMessageCreator(subscription); + _azureServiceBusMesssageCreator = new AzureServiceBusMessageCreator(subscription, loggerFactory); } - + /// /// Dispose of the Consumer. /// @@ -81,10 +83,11 @@ public void Dispose() ServiceBusReceiver?.Close(); GC.SuppressFinalize(this); } - + public async ValueTask DisposeAsync() { - if (ServiceBusReceiver is not null) await ServiceBusReceiver.CloseAsync(); + if (ServiceBusReceiver is not null) + await ServiceBusReceiver.CloseAsync(); GC.SuppressFinalize(this); } @@ -92,7 +95,7 @@ public async ValueTask DisposeAsync() /// Acknowledges the specified message. /// /// The message. - public void Acknowledge(Message message) => BrighterAsyncContext.Run(async() => await AcknowledgeAsync(message)); + public void Acknowledge(Message message) => BrighterAsyncContext.Run(async () => await AcknowledgeAsync(message)); /// /// Acknowledges the specified message. @@ -109,14 +112,15 @@ public async ValueTask DisposeAsync() if (string.IsNullOrEmpty(lockToken)) throw new Exception($"LockToken for message with id {message.Id} is null or empty"); Log.AcknowledgingMessage(Logger, message.Id.Value, lockToken); - - if(ServiceBusReceiver == null) + + if (ServiceBusReceiver == null) await GetMessageReceiverProviderAsync(); await ServiceBusReceiver!.CompleteAsync(lockToken); - + if (SubscriptionConfiguration.RequireSession) - if (ServiceBusReceiver is not null) await ServiceBusReceiver.CloseAsync(); + if (ServiceBusReceiver is not null) + await ServiceBusReceiver.CloseAsync(); } catch (AggregateException ex) { @@ -143,12 +147,12 @@ public async ValueTask DisposeAsync() /// Purges the specified queue name. /// public void Purge() => BrighterAsyncContext.Run(() => PurgeAsync()); - + /// /// Purges the specified queue name. /// public abstract Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken)); - + /// /// Receives the specified queue name. /// An abstraction over a third-party messaging library. Used to read messages from the broker and to acknowledge @@ -159,7 +163,7 @@ public async ValueTask DisposeAsync() /// The timeout for a message being available. Defaults to 300ms. /// Message. public Message[] Receive(TimeSpan? timeOut = null) => BrighterAsyncContext.Run(() => ReceiveAsync(timeOut)); - + /// /// Receives the specified queue name. /// An abstraction over a third-party messaging library. Used to read messages from the broker and to acknowledge @@ -186,7 +190,7 @@ public async ValueTask DisposeAsync() if (ServiceBusReceiver == null) { Log.CouldNotGetSessionLock(Logger, Topic); - return messagesToReturn.ToArray(); + return messagesToReturn.ToArray(); } } @@ -196,11 +200,11 @@ public async ValueTask DisposeAsync() } catch (Exception e) { - if (ServiceBusReceiver is {IsClosedOrClosing: true} && !SubscriptionConfiguration.RequireSession) + if (ServiceBusReceiver is { IsClosedOrClosing: true } && !SubscriptionConfiguration.RequireSession) { Log.MessageReceiverClosing(Logger); var message = new Message( - new MessageHeader(string.Empty, new RoutingKey(Topic), MessageType.MT_QUIT), + new MessageHeader(string.Empty, new RoutingKey(Topic), MessageType.MT_QUIT), new MessageBody(string.Empty)); messagesToReturn.Add(message); return messagesToReturn.ToArray(); @@ -209,7 +213,7 @@ public async ValueTask DisposeAsync() Log.FailingToReceiveMessages(Logger, e); //The connection to Azure Service bus may have failed so we re-establish the connection. - if(!SubscriptionConfiguration.RequireSession || ServiceBusReceiver == null) + if (!SubscriptionConfiguration.RequireSession || ServiceBusReceiver == null) await GetMessageReceiverProviderAsync(); throw new ChannelFailureException("Failing to receive messages.", e); @@ -223,7 +227,7 @@ public async ValueTask DisposeAsync() return messagesToReturn.ToArray(); } - + /// /// Nacks the specified message, abandoning the lock so it is available for redelivery. /// Sync over Async @@ -254,7 +258,8 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken await ServiceBusReceiver!.AbandonAsync(lockToken); if (SubscriptionConfiguration.RequireSession) - if (ServiceBusReceiver is not null) await ServiceBusReceiver.CloseAsync(); + if (ServiceBusReceiver is not null) + await ServiceBusReceiver.CloseAsync(); } catch (AggregateException ex) { @@ -302,18 +307,19 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken if (string.IsNullOrEmpty(lockToken)) throw new Exception($"LockToken for message with id {message.Id} is null or empty"); - + var reasonString = reason is null ? nameof(RejectionReason.DeliveryError) : reason.RejectionReason.ToString(); var description = reason is null ? "unknown" : reason.Description ?? "unknown"; - + Log.DeadLetteringMessage(Logger, message.Id.Value, lockToken, reasonString, description); - if(ServiceBusReceiver == null) + if (ServiceBusReceiver == null) await GetMessageReceiverProviderAsync(); await ServiceBusReceiver!.DeadLetterAsync(lockToken, reasonString, description); if (SubscriptionConfiguration.RequireSession) - if (ServiceBusReceiver is not null) await ServiceBusReceiver.CloseAsync(); + if (ServiceBusReceiver is not null) + await ServiceBusReceiver.CloseAsync(); } catch (Exception ex) { @@ -347,12 +353,12 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken Log.RequeuingMessage(Logger, topic, message.Id.Value); var messageProducerAsync = _messageProducer as IAmAMessageProducerAsync; - - if (messageProducerAsync is null) + + if (messageProducerAsync is null) { - throw new ChannelFailureException("Message Producer is not of type IAmAMessageProducerSync"); + throw new ChannelFailureException("Message Producer is not of type IAmAMessageProducerSync"); } - + if (delay.Value > TimeSpan.Zero) { await messageProducerAsync.SendWithDelayAsync(message, delay.Value, cancellationToken); @@ -361,7 +367,7 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken { await messageProducerAsync.SendAsync(message, cancellationToken); } - + await AcknowledgeAsync(message, cancellationToken); return true; diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs index 077956cf5e..0c316adbae 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs @@ -23,6 +23,7 @@ THE SOFTWARE. */ #endregion using System; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; using IServiceBusClientProvider = Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider.IServiceBusClientProvider; @@ -35,22 +36,26 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; public class AzureServiceBusConsumerFactory : IAmAMessageConsumerFactory { private readonly IServiceBusClientProvider _clientProvider; + private readonly ILoggerFactory _loggerFactory; /// /// Factory to create an Azure Service Bus Consumer /// /// The configuration to connect to - public AzureServiceBusConsumerFactory(AzureServiceBusConfiguration configuration) - : this(new ServiceBusConnectionStringClientProvider(configuration.ConnectionString)) + /// The used to create loggers + public AzureServiceBusConsumerFactory(AzureServiceBusConfiguration configuration, ILoggerFactory loggerFactory) + : this(new ServiceBusConnectionStringClientProvider(configuration.ConnectionString), loggerFactory) { } /// /// Factory to create an Azure Service Bus Consumer /// /// A client Provider to determine how to connect to ASB - public AzureServiceBusConsumerFactory(IServiceBusClientProvider clientProvider) + /// The used to create loggers + public AzureServiceBusConsumerFactory(IServiceBusClientProvider clientProvider, ILoggerFactory loggerFactory) { _clientProvider = clientProvider; + _loggerFactory = loggerFactory; } /// @@ -60,39 +65,43 @@ public AzureServiceBusConsumerFactory(IServiceBusClientProvider clientProvider) /// IAmAMessageConsumerSync public IAmAMessageConsumerSync Create(Subscription subscription) { - var nameSpaceManagerWrapper = new AdministrationClientWrapper(_clientProvider); + var nameSpaceManagerWrapper = new AdministrationClientWrapper(_clientProvider, _loggerFactory); if (!(subscription is AzureServiceBusSubscription sub)) throw new ArgumentException("Subscription is not of type AzureServiceBusSubscription.", nameof(subscription)); - var receiverProvider = new ServiceBusReceiverProvider(_clientProvider); + var receiverProvider = new ServiceBusReceiverProvider(_clientProvider, _loggerFactory); if (sub.Configuration.UseServiceBusQueue) { var messageProducer = new AzureServiceBusQueueMessageProducer( nameSpaceManagerWrapper, new ServiceBusSenderProvider(_clientProvider), - new AzureServiceBusPublication { MakeChannels = subscription.MakeChannels }); + new AzureServiceBusPublication { MakeChannels = subscription.MakeChannels }, + loggerFactory: _loggerFactory); return new AzureServiceBusQueueConsumer( sub, messageProducer, nameSpaceManagerWrapper, - receiverProvider); + receiverProvider, + _loggerFactory); } else { var messageProducer = new AzureServiceBusTopicMessageProducer( nameSpaceManagerWrapper, new ServiceBusSenderProvider(_clientProvider), - new AzureServiceBusPublication { MakeChannels = subscription.MakeChannels }); + new AzureServiceBusPublication { MakeChannels = subscription.MakeChannels }, + loggerFactory: _loggerFactory); return new AzureServiceBusTopicConsumer( sub, messageProducer, nameSpaceManagerWrapper, - receiverProvider); + receiverProvider, + _loggerFactory); } } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageCreator.cs index 4659892d93..8ecb478abf 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageCreator.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System; using System.Net.Mime; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; using Paramore.Brighter.Observability; @@ -36,11 +35,11 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; /// Creates a Brighter from an Azure Service Bus message. /// /// Subscription information, used to help populate the message -public partial class AzureServiceBusMessageCreator(AzureServiceBusSubscription subscription) +/// The used to create the logger. +public partial class AzureServiceBusMessageCreator(AzureServiceBusSubscription subscription, ILoggerFactory loggerFactory) { private readonly RoutingKey _topic = subscription.RoutingKey; - private static readonly ILogger s_logger = - ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// /// Maps an Azure Service Bus message to a Brighter . @@ -51,27 +50,27 @@ public Message MapToBrighterMessage(IBrokeredMessageWrapper? azureServiceBusMess { if (azureServiceBusMessage is null) { - Log.NullMessageReceived(s_logger, _topic, subscription.Name); + Log.NullMessageReceived(_logger, _topic, subscription.Name); return Message.FailureMessage(_topic); } if (azureServiceBusMessage!.MessageBodyValue is null) { - Log.NullMessageBodyReceived(s_logger, _topic, subscription.Name); + Log.NullMessageBodyReceived(_logger, _topic, subscription.Name); } var bodyMemory = azureServiceBusMessage.MessageBodyMemory; #if NETSTANDARD2_0 Log.ReceivedMessage( - s_logger, + _logger, _topic, subscription.Name, System.Text.Encoding.UTF8.GetString(bodyMemory.ToArray()) ); #else Log.ReceivedMessage( - s_logger, + _logger, _topic, subscription.Name, System.Text.Encoding.UTF8.GetString(bodyMemory.Span) @@ -97,9 +96,9 @@ public Message MapToBrighterMessage(IBrokeredMessageWrapper? azureServiceBusMess // https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/servicebus/Azure.Messaging.ServiceBus/samples/Sample11_CloudEvents.md var headers = new MessageHeader( - messageId: azureServiceBusMessage.Id, + messageId: azureServiceBusMessage.Id, topic: new RoutingKey(_topic.Value), - messageType: messageType, + messageType: messageType, source: source, type: type, timeStamp: time, @@ -137,7 +136,7 @@ out object? property ) ) { - Log.NoBaggageFound(s_logger, _topic, subscription.Name); + Log.NoBaggageFound(_logger, _topic, subscription.Name); return new Baggage(); } @@ -158,7 +157,7 @@ out object? property ) ) { - Log.NoCloudEventsDataSchema(s_logger, _topic, subscription.Name); + Log.NoCloudEventsDataSchema(_logger, _topic, subscription.Name); return defaultSchemaUri; } @@ -166,7 +165,7 @@ out object? property if (string.IsNullOrEmpty(dataSchema)) { - Log.EmptyCloudEventsDataSchema(s_logger, _topic, subscription.Name); + Log.EmptyCloudEventsDataSchema(_logger, _topic, subscription.Name); return defaultSchemaUri; } @@ -182,7 +181,7 @@ out object? property ) ) { - Log.NoCloudEventsSubject(s_logger, _topic, subscription.Name); + Log.NoCloudEventsSubject(_logger, _topic, subscription.Name); return string.Empty; } @@ -200,7 +199,7 @@ out object? property ) ) { - Log.NoCloudEventsTime(s_logger, _topic, subscription.Name); + Log.NoCloudEventsTime(_logger, _topic, subscription.Name); return DateTimeOffset.UtcNow; } @@ -214,7 +213,7 @@ out object? property return parsedTime; } - Log.InvalidCloudEventsTimeFormat(s_logger, _topic, subscription.Name); + Log.InvalidCloudEventsTimeFormat(_logger, _topic, subscription.Name); return DateTimeOffset.UtcNow; } @@ -227,7 +226,7 @@ out object? property ) ) { - Log.NoCloudEventsPartitionKey(s_logger, _topic, subscription.Name); + Log.NoCloudEventsPartitionKey(_logger, _topic, subscription.Name); return PartitionKey.Empty; } @@ -243,7 +242,7 @@ out object? property ) ) { - Log.NoCloudEventsType(s_logger, _topic, subscription.Name); + Log.NoCloudEventsType(_logger, _topic, subscription.Name); return CloudEventsType.Empty; } @@ -316,13 +315,13 @@ out object? property ) ) { - Log.NoSourceFound(s_logger, _topic, subscription.Name); + Log.NoSourceFound(_logger, _topic, subscription.Name); return defaultSourceUri; } if (property is not string sourceString || string.IsNullOrEmpty(sourceString)) { - Log.EmptyOrInvalidSource(s_logger, _topic, subscription.Name); + Log.EmptyOrInvalidSource(_logger, _topic, subscription.Name); return defaultSourceUri; } @@ -340,7 +339,7 @@ out object? property ) ) { - Log.NoTraceParentFound(s_logger, _topic, subscription.Name); + Log.NoTraceParentFound(_logger, _topic, subscription.Name); return new TraceParent(string.Empty); } @@ -358,7 +357,7 @@ out object? property ) ) { - Log.NoTraceStateFound(s_logger, _topic, subscription.Name); + Log.NoTraceStateFound(_logger, _topic, subscription.Name); return new TraceState(string.Empty); } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageProducerFactory.cs index 8f88814aa8..16e7705524 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageProducerFactory.cs @@ -27,6 +27,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; @@ -41,6 +42,7 @@ public class AzureServiceBusMessageProducerFactory : IAmAMessageProducerFactory private readonly IServiceBusClientProvider _clientProvider; private readonly IEnumerable _publications; private readonly int _bulkSendBatchSize; + private readonly ILoggerFactory _loggerFactory; /// /// Factory to create a dictionary of Azure Service Bus Producers indexed by topic name @@ -48,14 +50,17 @@ public class AzureServiceBusMessageProducerFactory : IAmAMessageProducerFactory /// The connection to ASB /// A set of publications - topics on the server - to configure /// The maximum size to chunk messages when dispatching to ASB + /// The used to create loggers public AzureServiceBusMessageProducerFactory( IServiceBusClientProvider clientProvider, IEnumerable publications, - int bulkSendBatchSize) + int bulkSendBatchSize, + ILoggerFactory loggerFactory) { _clientProvider = clientProvider; _publications = publications; _bulkSendBatchSize = bulkSendBatchSize; + _loggerFactory = loggerFactory; } /// @@ -66,7 +71,7 @@ public AzureServiceBusMessageProducerFactory( public Dictionary Create() { - var nameSpaceManagerWrapper = new AdministrationClientWrapper(_clientProvider); + var nameSpaceManagerWrapper = new AdministrationClientWrapper(_clientProvider, _loggerFactory); var topicClientProvider = new ServiceBusSenderProvider(_clientProvider); var producers = new Dictionary(); @@ -74,16 +79,16 @@ public Dictionary Create() { if (publication.Topic is null) throw new ArgumentException("Publication must have a Topic."); - + if (publication.UseServiceBusQueue) { - var producer = new AzureServiceBusQueueMessageProducer(nameSpaceManagerWrapper, topicClientProvider, publication, _bulkSendBatchSize); + var producer = new AzureServiceBusQueueMessageProducer(nameSpaceManagerWrapper, topicClientProvider, publication, _loggerFactory, _bulkSendBatchSize); producer.Publication = publication; RegisterProducer(publication, producers, producer); } else { - var producer = new AzureServiceBusTopicMessageProducer(nameSpaceManagerWrapper, topicClientProvider, publication, _bulkSendBatchSize); + var producer = new AzureServiceBusTopicMessageProducer(nameSpaceManagerWrapper, topicClientProvider, publication, _loggerFactory, _bulkSendBatchSize); producer.Publication = publication; RegisterProducer(publication, producers, producer); @@ -92,12 +97,12 @@ public Dictionary Create() return producers; } - + public Task> CreateAsync() { return Task.FromResult(Create()); } - + private static void RegisterProducer(AzureServiceBusPublication publication, Dictionary producers, IAmAMessageProducer producer) { var producerKey = new ProducerKey(publication.Topic!, publication.Type); @@ -106,5 +111,5 @@ private static void RegisterProducer(AzureServiceBusPublication publication, Dic producers[producerKey] = producer; } - + } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusProducerRegistryFactory.cs index 929b86713a..ad87b36092 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusProducerRegistryFactory.cs @@ -27,6 +27,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; @@ -36,19 +37,23 @@ public class AzureServiceBusProducerRegistryFactory : IAmAProducerRegistryFactor private readonly IServiceBusClientProvider _clientProvider; private readonly IEnumerable _asbPublications; private readonly int _bulkSendBatchSize; + private readonly ILoggerFactory _loggerFactory; /// /// Creates a producer registry initialized with producers for ASB derived from the publications /// /// The configuration of the connection to ASB /// A set of publications - topics on the server - to configure + /// The used to create loggers public AzureServiceBusProducerRegistryFactory( - AzureServiceBusConfiguration configuration, - IEnumerable asbPublications) + AzureServiceBusConfiguration configuration, + IEnumerable asbPublications, + ILoggerFactory loggerFactory) { _clientProvider = new ServiceBusConnectionStringClientProvider(configuration.ConnectionString); _asbPublications = asbPublications; _bulkSendBatchSize = configuration.BulkSendBatchSize; + _loggerFactory = loggerFactory; } /// @@ -57,14 +62,17 @@ public AzureServiceBusProducerRegistryFactory( /// The connection to ASB /// A set of publications - topics on the server - to configure /// The maximum size to chunk messages when dispatching to ASB + /// The used to create loggers public AzureServiceBusProducerRegistryFactory( IServiceBusClientProvider clientProvider, IEnumerable asbPublications, + ILoggerFactory loggerFactory, int bulkSendBatchSize = 10) { _clientProvider = clientProvider; _asbPublications = asbPublications; _bulkSendBatchSize = bulkSendBatchSize; + _loggerFactory = loggerFactory; } /// @@ -73,7 +81,7 @@ public AzureServiceBusProducerRegistryFactory( /// A has of middleware clients by topic, for sending messages to the middleware public IAmAProducerRegistry Create() { - var producerFactory = new AzureServiceBusMessageProducerFactory(_clientProvider, _asbPublications, _bulkSendBatchSize); + var producerFactory = new AzureServiceBusMessageProducerFactory(_clientProvider, _asbPublications, _bulkSendBatchSize, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueConsumer.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueConsumer.cs index 1510bbdeb2..78281ded9e 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueConsumer.cs @@ -24,11 +24,10 @@ THE SOFTWARE. */ #endregion using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; using Paramore.Brighter.Tasks; @@ -40,12 +39,12 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; public partial class AzureServiceBusQueueConsumer : AzureServiceBusConsumer { protected override string SubscriptionName => "Queue"; - protected override ILogger Logger => s_logger; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + protected override ILogger Logger => _logger; + private readonly ILogger _logger; private readonly IServiceBusReceiverProvider _serviceBusReceiverProvider; private bool _queueCreated = false; - + /// /// Initializes an Instance of for Service Bus Queus /// @@ -53,34 +52,37 @@ public partial class AzureServiceBusQueueConsumer : AzureServiceBusConsumer /// An instance of the Messaging Producer used for Requeue. /// An Instance of Administration Client Wrapper. /// An Instance of . + /// The used to create the logger. public AzureServiceBusQueueConsumer(AzureServiceBusSubscription subscription, IAmAMessageProducerSync messageProducer, IAdministrationClientWrapper administrationClientWrapper, - IServiceBusReceiverProvider serviceBusReceiverProvider) : base(subscription, - messageProducer, administrationClientWrapper) + IServiceBusReceiverProvider serviceBusReceiverProvider, + ILoggerFactory loggerFactory) : base(subscription, + messageProducer, administrationClientWrapper, loggerFactory: loggerFactory) { + _logger = loggerFactory.CreateLogger(); _serviceBusReceiverProvider = serviceBusReceiverProvider; } protected override async Task GetMessageReceiverProviderAsync() { - Log.GettingMessageReceiverProviderAsync(s_logger, Topic); + Log.GettingMessageReceiverProviderAsync(_logger, Topic); try { ServiceBusReceiver = await _serviceBusReceiverProvider.GetAsync(Topic, SubscriptionConfiguration.RequireSession); } catch (Exception e) { - Log.FailedToGetMessageReceiverProviderAsync(s_logger, Topic, e); + Log.FailedToGetMessageReceiverProviderAsync(_logger, Topic, e); } } - + /// /// Purges the specified queue name. /// public override async Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken)) { - Log.PurgingMessagesFromQueueAsync(s_logger, Topic); + Log.PurgingMessagesFromQueueAsync(_logger, Topic); await AdministrationClientWrapper.DeleteQueueAsync(Topic); await EnsureChannelAsync(); @@ -111,7 +113,7 @@ protected override async Task EnsureChannelAsync() { if (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists) { - Log.MessageEntityAlreadyExists(s_logger, Topic); + Log.MessageEntityAlreadyExists(_logger, Topic); _queueCreated = true; } else @@ -121,7 +123,7 @@ protected override async Task EnsureChannelAsync() } catch (Exception e) { - Log.FailingToCheckOrCreateSubscription(s_logger, e); + Log.FailingToCheckOrCreateSubscription(_logger, e); //The connection to Azure Service bus may have failed so we re-establish the connection. AdministrationClientWrapper.Reset(); @@ -137,7 +139,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Failed to get message receiver provider for queue {Queue}")] public static partial void FailedToGetMessageReceiverProviderAsync(ILogger logger, string queue, Exception e); - + [LoggerMessage(LogLevel.Information, "Purging messages from Queue {Queue}")] public static partial void PurgingMessagesFromQueueAsync(ILogger logger, string queue); diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueMessageProducer.cs index f7a2fd8db8..63ece57e8f 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueMessageProducer.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; namespace Paramore.Brighter.MessagingGateway.AzureServiceBus @@ -36,10 +35,10 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus /// public partial class AzureServiceBusQueueMessageProducer : AzureServiceBusMessageProducer { - protected override ILogger Logger => s_logger; - - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + protected override ILogger Logger => _logger; + + private readonly ILogger _logger; + private readonly IAdministrationClientWrapper _administrationClientWrapper; /// @@ -49,13 +48,16 @@ public partial class AzureServiceBusQueueMessageProducer : AzureServiceBusMessag /// The provider to use when producing messages. /// Configuration of a producer /// When sending more than one message using the MessageProducer, the max amount to send in a single transmission. + /// The used to create the logger. public AzureServiceBusQueueMessageProducer( IAdministrationClientWrapper administrationClientWrapper, IServiceBusSenderProvider serviceBusSenderProvider, AzureServiceBusPublication publication, + ILoggerFactory loggerFactory, int bulkSendBatchSize = 10 ) : base(serviceBusSenderProvider, publication, bulkSendBatchSize) { + _logger = loggerFactory.CreateLogger(); _administrationClientWrapper = administrationClientWrapper; } @@ -84,7 +86,7 @@ protected override async Task EnsureChannelExistsAsync(string channelName) { //The connection to Azure Service bus may have failed so we re-establish the connection. _administrationClientWrapper.Reset(); - Log.FailingToCheckOrCreateQueue(s_logger, e); + Log.FailingToCheckOrCreateQueue(_logger, e); throw; } } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicConsumer.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicConsumer.cs index ba36f72fb3..a391180258 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicConsumer.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; using Paramore.Brighter.Tasks; @@ -39,9 +38,9 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; /// public partial class AzureServiceBusTopicConsumer : AzureServiceBusConsumer { - protected override ILogger Logger => s_logger; + protected override ILogger Logger => _logger; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private bool _subscriptionCreated; private readonly string _subscriptionName; private readonly IServiceBusReceiverProvider _serviceBusReceiverProvider; @@ -54,28 +53,31 @@ public partial class AzureServiceBusTopicConsumer : AzureServiceBusConsumer /// An instance of the Messaging Producer used for Requeue. /// An Instance of Administration Client Wrapper. /// An Instance of . + /// The used to create the logger. public AzureServiceBusTopicConsumer( AzureServiceBusSubscription subscription, IAmAMessageProducer messageProducer, IAdministrationClientWrapper administrationClientWrapper, - IServiceBusReceiverProvider serviceBusReceiverProvider) - : base(subscription, messageProducer, administrationClientWrapper) + IServiceBusReceiverProvider serviceBusReceiverProvider, + ILoggerFactory loggerFactory) + : base(subscription, messageProducer, administrationClientWrapper, loggerFactory: loggerFactory) { + _logger = loggerFactory.CreateLogger(); _subscriptionName = subscription.ChannelName.Value; _serviceBusReceiverProvider = serviceBusReceiverProvider; } - + /// /// Purges the specified queue name. /// public override async Task PurgeAsync(CancellationToken ct = default) { - Log.PurgingMessagesFromSubscriptionOnTopic(s_logger, SubscriptionName, Topic); + Log.PurgingMessagesFromSubscriptionOnTopic(_logger, SubscriptionName, Topic); await AdministrationClientWrapper.DeleteTopicAsync(Topic); await EnsureChannelAsync(); } - + protected override async Task EnsureChannelAsync() { if (_subscriptionCreated || Subscription.MakeChannels.Equals(OnMissingChannel.Assume)) @@ -102,7 +104,7 @@ protected override async Task EnsureChannelAsync() { if (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists) { - Log.MessageEntityAlreadyExists(s_logger, Topic, _subscriptionName); + Log.MessageEntityAlreadyExists(_logger, Topic, _subscriptionName); _subscriptionCreated = true; } else @@ -112,7 +114,7 @@ protected override async Task EnsureChannelAsync() } catch (Exception e) { - Log.FailingToCheckOrCreateSubscription(s_logger, e); + Log.FailingToCheckOrCreateSubscription(_logger, e); //The connection to Azure Service bus may have failed so we re-establish the connection. AdministrationClientWrapper.Reset(); @@ -120,10 +122,10 @@ protected override async Task EnsureChannelAsync() throw new ChannelFailureException("Failing to check or create subscription", e); } } - + protected override async Task GetMessageReceiverProviderAsync() { - Log.GettingMessageReceiverProviderForTopicAndSubscription(s_logger, Topic, _subscriptionName); + Log.GettingMessageReceiverProviderForTopicAndSubscription(_logger, Topic, _subscriptionName); try { ServiceBusReceiver = await _serviceBusReceiverProvider.GetAsync(Topic, _subscriptionName, @@ -131,7 +133,7 @@ protected override async Task GetMessageReceiverProviderAsync() } catch (Exception e) { - Log.FailedToGetMessageReceiverProviderForTopicAndSubscription(s_logger, e, Topic, _subscriptionName); + Log.FailedToGetMessageReceiverProviderForTopicAndSubscription(_logger, e, Topic, _subscriptionName); } } @@ -145,7 +147,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Failing to check or create subscription")] public static partial void FailingToCheckOrCreateSubscription(ILogger logger, Exception e); - + [LoggerMessage(LogLevel.Information, "Getting message receiver provider for topic {Topic} and subscription {ChannelName}...")] public static partial void GettingMessageReceiverProviderForTopicAndSubscription(ILogger logger, string topic, string channelName); diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicMessageProducer.cs index ebfa9d70d5..a3ead27743 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicMessageProducer.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers; namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; @@ -36,10 +35,10 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus; /// public partial class AzureServiceBusTopicMessageProducer : AzureServiceBusMessageProducer { - protected override ILogger Logger => s_logger; - - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + protected override ILogger Logger => _logger; + + private readonly ILogger _logger; + private readonly IAdministrationClientWrapper _administrationClientWrapper; /// @@ -49,13 +48,16 @@ public partial class AzureServiceBusTopicMessageProducer : AzureServiceBusMessag /// The provider to use when producing messages. /// Configuration of a producer /// When sending more than one message using the MessageProducer, the max amount to send in a single transmission. + /// The used to create the logger. public AzureServiceBusTopicMessageProducer( IAdministrationClientWrapper administrationClientWrapper, IServiceBusSenderProvider serviceBusSenderProvider, AzureServiceBusPublication publication, + ILoggerFactory loggerFactory, int bulkSendBatchSize = 10 ) : base(serviceBusSenderProvider, publication, bulkSendBatchSize) { + _logger = loggerFactory.CreateLogger(); _administrationClientWrapper = administrationClientWrapper; } @@ -76,7 +78,7 @@ protected override async Task EnsureChannelExistsAsync(string channelName) { throw new ChannelFailureException($"Topic {channelName} does not exist and missing channel mode set to Validate."); } - + await _administrationClientWrapper.CreateTopicAsync(channelName); TopicCreated = true; } @@ -84,7 +86,7 @@ protected override async Task EnsureChannelExistsAsync(string channelName) { //The connection to Azure Service bus may have failed so we re-establish the connection. _administrationClientWrapper.Reset(); - Log.FailingToCheckOrCreateTopic(s_logger, e); + Log.FailingToCheckOrCreateTopic(_logger, e); throw; } } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs index c73dfe4298..7b6bd575d3 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Azure.Messaging.ServiceBus.Administration; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; using Paramore.Brighter.Tasks; @@ -39,16 +38,18 @@ public partial class AdministrationClientWrapper : IAdministrationClientWrapper { private readonly IServiceBusClientProvider _clientProvider; private ServiceBusAdministrationClient _administrationClient; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; /// /// Initializes an Instance of /// /// - public AdministrationClientWrapper(IServiceBusClientProvider clientProvider) + /// The used to create the logger. + public AdministrationClientWrapper(IServiceBusClientProvider clientProvider, ILoggerFactory loggerFactory) { _clientProvider = clientProvider; _administrationClient = _clientProvider.GetServiceBusAdministrationClient(); + _logger = loggerFactory.CreateLogger(); } /// @@ -56,7 +57,7 @@ public AdministrationClientWrapper(IServiceBusClientProvider clientProvider) /// public void Reset() { - Log.ResettingManagementClientWrapper(s_logger); + Log.ResettingManagementClientWrapper(_logger); Initialise(); } @@ -68,7 +69,7 @@ public void Reset() /// Ma message size in kilobytes : Only available in premium public async Task CreateQueueAsync(string queueName, TimeSpan? autoDeleteOnIdle = null, long? maxMessageSizeInKilobytes = default) { - Log.CreatingTopic(s_logger, queueName); + Log.CreatingTopic(_logger, queueName); try { @@ -80,13 +81,13 @@ await _administrationClient.CreateQueueAsync(new CreateQueueOptions(queueName) } catch (Exception e) { - Log.FailedToCreateQueue(s_logger, e, queueName); + Log.FailedToCreateQueue(_logger, e, queueName); throw; } - Log.QueueCreated(s_logger, queueName); + Log.QueueCreated(_logger, queueName); } - + /// /// Create a Subscription. /// Sync over Async but alright in the context of creating a subscription @@ -96,7 +97,7 @@ await _administrationClient.CreateQueueAsync(new CreateQueueOptions(queueName) /// The configuration options for the subscriptions. public async Task CreateSubscriptionAsync(string topicName, string subscriptionName, AzureServiceBusSubscriptionConfiguration subscriptionConfiguration) { - Log.CreatingSubscriptionForTopic(s_logger, subscriptionName, topicName); + Log.CreatingSubscriptionForTopic(_logger, subscriptionName, topicName); if (!await TopicExistsAsync(topicName)) { @@ -114,7 +115,7 @@ public async Task CreateSubscriptionAsync(string topicName, string subscriptionN }; var ruleOptions = string.IsNullOrEmpty(subscriptionConfiguration.SqlFilter) - ? new CreateRuleOptions() : new CreateRuleOptions("sqlFilter",new SqlRuleFilter(subscriptionConfiguration.SqlFilter)); + ? new CreateRuleOptions() : new CreateRuleOptions("sqlFilter", new SqlRuleFilter(subscriptionConfiguration.SqlFilter)); try { @@ -122,11 +123,11 @@ public async Task CreateSubscriptionAsync(string topicName, string subscriptionN } catch (Exception e) { - Log.FailedToCreateSubscriptionForTopic(s_logger, e, subscriptionName, topicName); + Log.FailedToCreateSubscriptionForTopic(_logger, e, subscriptionName, topicName); throw; } - Log.SubscriptionForTopicCreated(s_logger, subscriptionName, topicName); + Log.SubscriptionForTopicCreated(_logger, subscriptionName, topicName); } @@ -139,7 +140,7 @@ public async Task CreateSubscriptionAsync(string topicName, string subscriptionN /// Ma message size in kilobytes : Only available in premium public async Task CreateTopicAsync(string topicName, TimeSpan? autoDeleteOnIdle = null, long? maxMessageSizeInKilobytes = default) { - Log.CreatingTopic(s_logger, topicName); + Log.CreatingTopic(_logger, topicName); try { @@ -151,11 +152,11 @@ await _administrationClient.CreateTopicAsync(new CreateTopicOptions(topicName) } catch (Exception e) { - Log.FailedToCreateTopic(s_logger, e, topicName); + Log.FailedToCreateTopic(_logger, e, topicName); throw; } - Log.TopicCreated(s_logger, topicName); + Log.TopicCreated(_logger, topicName); } @@ -165,15 +166,15 @@ await _administrationClient.CreateTopicAsync(new CreateTopicOptions(topicName) /// The name of the Queue public async Task DeleteQueueAsync(string queueName) { - Log.DeletingQueue(s_logger, queueName); + Log.DeletingQueue(_logger, queueName); try { - await _administrationClient.DeleteQueueAsync(queueName); - Log.QueueSuccessfullyDeleted(s_logger, queueName); + await _administrationClient.DeleteQueueAsync(queueName); + Log.QueueSuccessfullyDeleted(_logger, queueName); } catch (Exception e) { - Log.FailedToDeleteQueue(s_logger, e, queueName); + Log.FailedToDeleteQueue(_logger, e, queueName); } } @@ -183,18 +184,18 @@ public async Task DeleteQueueAsync(string queueName) /// The name of the Topic public async Task DeleteTopicAsync(string topicName) { - Log.DeletingTopic(s_logger, topicName); + Log.DeletingTopic(_logger, topicName); try { await _administrationClient.DeleteTopicAsync(topicName); - Log.TopicSuccessfullyDeleted(s_logger, topicName); + Log.TopicSuccessfullyDeleted(_logger, topicName); } catch (Exception e) { - Log.FailedToDeleteTopic(s_logger, e, topicName); + Log.FailedToDeleteTopic(_logger, e, topicName); } } - + /// /// GetAsync a Subscription. /// @@ -206,7 +207,7 @@ public async Task GetSubscriptionAsync(string topicName, { return await _administrationClient.GetSubscriptionAsync(topicName, subscriptionName, cancellationToken); } - + /// /// Check if a Queue exists /// Sync over async but runs in the context of checking queue existence @@ -215,7 +216,7 @@ public async Task GetSubscriptionAsync(string topicName, /// True if the Queue exists. public async Task QueueExistsAsync(string queueName) { - Log.CheckingIfQueueExists(s_logger, queueName); + Log.CheckingIfQueueExists(_logger, queueName); bool result; @@ -225,17 +226,17 @@ public async Task QueueExistsAsync(string queueName) } catch (Exception e) { - Log.FailedToCheckIfQueueExists(s_logger, e, queueName); + Log.FailedToCheckIfQueueExists(_logger, e, queueName); throw; } if (result) { - Log.QueueExists(s_logger, queueName); + Log.QueueExists(_logger, queueName); } else { - Log.QueueDoesNotExist(s_logger, queueName); + Log.QueueDoesNotExist(_logger, queueName); } return result; @@ -249,7 +250,7 @@ public async Task QueueExistsAsync(string queueName) /// True if the subscription exists on the specified Topic. public async Task SubscriptionExistsAsync(string topicName, string subscriptionName) { - Log.CheckingIfSubscriptionForTopicExists(s_logger, subscriptionName, topicName); + Log.CheckingIfSubscriptionForTopicExists(_logger, subscriptionName, topicName); bool result; @@ -259,17 +260,17 @@ public async Task SubscriptionExistsAsync(string topicName, string subscri } catch (Exception e) { - Log.FailedToCheckIfSubscriptionForTopicExists(s_logger, e, subscriptionName, topicName); + Log.FailedToCheckIfSubscriptionForTopicExists(_logger, e, subscriptionName, topicName); throw; } if (result) { - Log.SubscriptionForTopicExists(s_logger, subscriptionName, topicName); + Log.SubscriptionForTopicExists(_logger, subscriptionName, topicName); } else { - Log.SubscriptionForTopicDoesNotExist(s_logger, subscriptionName, topicName); + Log.SubscriptionForTopicDoesNotExist(_logger, subscriptionName, topicName); } return result; @@ -283,7 +284,7 @@ public async Task SubscriptionExistsAsync(string topicName, string subscri /// True if the Topic exists. public async Task TopicExistsAsync(string topicName) { - Log.CheckingIfTopicExists(s_logger, topicName); + Log.CheckingIfTopicExists(_logger, topicName); bool result; @@ -293,25 +294,25 @@ public async Task TopicExistsAsync(string topicName) } catch (Exception e) { - Log.FailedToCheckIfTopicExists(s_logger, e, topicName); + Log.FailedToCheckIfTopicExists(_logger, e, topicName); throw; } if (result) { - Log.TopicExists(s_logger, topicName); + Log.TopicExists(_logger, topicName); } else { - Log.TopicDoesNotExist(s_logger, topicName); + Log.TopicDoesNotExist(_logger, topicName); } return result; } - + private void Initialise() { - Log.InitialisingNewManagementClientWrapper(s_logger); + Log.InitialisingNewManagementClientWrapper(_logger); try { @@ -319,102 +320,102 @@ private void Initialise() } catch (Exception e) { - Log.FailedToInitialiseNewManagementClientWrapper(s_logger, e); + Log.FailedToInitialiseNewManagementClientWrapper(_logger, e); throw; } - Log.NewManagementClientWrapperInitialised(s_logger); + Log.NewManagementClientWrapperInitialised(_logger); } private static partial class Log { [LoggerMessage(LogLevel.Warning, "Resetting management client wrapper...")] public static partial void ResettingManagementClientWrapper(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Creating topic {Topic}...")] public static partial void CreatingTopic(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Error, "Failed to create queue {Queue}.")] public static partial void FailedToCreateQueue(ILogger logger, Exception exception, string queue); - + [LoggerMessage(LogLevel.Information, "Queue {Queue} created.")] public static partial void QueueCreated(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Information, "Creating subscription {ChannelName} for topic {Topic}...")] public static partial void CreatingSubscriptionForTopic(ILogger logger, string channelName, string topic); [LoggerMessage(LogLevel.Error, "Failed to create subscription {ChannelName} for topic {Topic}.")] public static partial void FailedToCreateSubscriptionForTopic(ILogger logger, Exception exception, string channelName, string topic); - + [LoggerMessage(LogLevel.Information, "Subscription {ChannelName} for topic {Topic} created.")] public static partial void SubscriptionForTopicCreated(ILogger logger, string channelName, string topic); - + [LoggerMessage(LogLevel.Error, "Failed to create topic {Topic}.")] public static partial void FailedToCreateTopic(ILogger logger, Exception exception, string topic); - + [LoggerMessage(LogLevel.Information, "Topic {Topic} created.")] public static partial void TopicCreated(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Information, "Deleting queue {Queue}...")] public static partial void DeletingQueue(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Information, "Queue {Queue} successfully deleted")] public static partial void QueueSuccessfullyDeleted(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Error, "Failed to delete Queue {Queue}")] public static partial void FailedToDeleteQueue(ILogger logger, Exception exception, string queue); - + [LoggerMessage(LogLevel.Information, "Deleting topic {Topic}...")] public static partial void DeletingTopic(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Information, "Topic {Topic} successfully deleted")] public static partial void TopicSuccessfullyDeleted(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Error, "Failed to delete Topic {Topic}")] public static partial void FailedToDeleteTopic(ILogger logger, Exception exception, string topic); - + [LoggerMessage(LogLevel.Debug, "Checking if queue {Queue} exists...")] public static partial void CheckingIfQueueExists(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Error, "Failed to check if queue {Queue} exists")] public static partial void FailedToCheckIfQueueExists(ILogger logger, Exception exception, string queue); - + [LoggerMessage(LogLevel.Debug, "Queue {Queue} exists")] public static partial void QueueExists(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Warning, "Queue {Queue} does not exist")] public static partial void QueueDoesNotExist(ILogger logger, string queue); - + [LoggerMessage(LogLevel.Debug, "Checking if subscription {ChannelName} for topic {Topic} exists...")] public static partial void CheckingIfSubscriptionForTopicExists(ILogger logger, string channelName, string topic); - + [LoggerMessage(LogLevel.Error, "Failed to check if subscription {ChannelName} for topic {Topic} exists.")] public static partial void FailedToCheckIfSubscriptionForTopicExists(ILogger logger, Exception exception, string channelName, string topic); - + [LoggerMessage(LogLevel.Debug, "Subscription {ChannelName} for topic {Topic} exists.")] public static partial void SubscriptionForTopicExists(ILogger logger, string channelName, string topic); - + [LoggerMessage(LogLevel.Warning, "Subscription {ChannelName} for topic {Topic} does not exist.")] public static partial void SubscriptionForTopicDoesNotExist(ILogger logger, string channelName, string topic); - + [LoggerMessage(LogLevel.Debug, "Checking if topic {Topic} exists...")] public static partial void CheckingIfTopicExists(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Error, "Failed to check if topic {Topic} exists")] public static partial void FailedToCheckIfTopicExists(ILogger logger, Exception exception, string topic); - + [LoggerMessage(LogLevel.Debug, "Topic {Topic} exists")] public static partial void TopicExists(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Warning, "Topic {Topic} does not exist")] public static partial void TopicDoesNotExist(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Debug, "Initialising new management client wrapper...")] public static partial void InitialisingNewManagementClientWrapper(ILogger logger); - + [LoggerMessage(LogLevel.Error, "Failed to initialise new management client wrapper.")] public static partial void FailedToInitialiseNewManagementClientWrapper(ILogger logger, Exception exception); - + [LoggerMessage(LogLevel.Debug, "New management client wrapper initialised.")] public static partial void NewManagementClientWrapperInitialised(ILogger logger); } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverProvider.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverProvider.cs index 50acb7b19c..6340ff93d1 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverProvider.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverProvider.cs @@ -23,13 +23,15 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Azure.Messaging.ServiceBus; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MessagingGateway.AzureServiceBus.ClientProvider; namespace Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers { - internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clientProvider) : IServiceBusReceiverProvider + internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clientProvider, ILoggerFactory loggerFactory) : IServiceBusReceiverProvider { private readonly ServiceBusClient _client = clientProvider.GetServiceBusClient(); + private readonly ILoggerFactory _loggerFactory = loggerFactory; /// /// Gets a for a Service Bus Queue @@ -45,7 +47,7 @@ internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clien try { return new ServiceBusReceiverWrapper(await _client.AcceptNextSessionAsync(queueName, - new ServiceBusSessionReceiverOptions() {ReceiveMode = ServiceBusReceiveMode.PeekLock})); + new ServiceBusSessionReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock }), _loggerFactory); } catch (ServiceBusException e) { @@ -61,7 +63,7 @@ internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clien else { return new ServiceBusReceiverWrapper(_client.CreateReceiver(queueName, - new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock })); + new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock }), _loggerFactory); } } @@ -80,7 +82,7 @@ internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clien try { return new ServiceBusReceiverWrapper(await _client.AcceptNextSessionAsync(topicName, subscriptionName, - new ServiceBusSessionReceiverOptions() {ReceiveMode = ServiceBusReceiveMode.PeekLock})); + new ServiceBusSessionReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock }), _loggerFactory); } catch (ServiceBusException e) { @@ -96,7 +98,7 @@ internal sealed class ServiceBusReceiverProvider(IServiceBusClientProvider clien else { return new ServiceBusReceiverWrapper(_client.CreateReceiver(topicName, subscriptionName, - new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock })); + new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock }), _loggerFactory); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverWrapper.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverWrapper.cs index bcd6227eaa..cae4ce05c0 100644 --- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverWrapper.cs +++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverWrapper.cs @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrappers { @@ -37,15 +36,17 @@ namespace Paramore.Brighter.MessagingGateway.AzureServiceBus.AzureServiceBusWrap internal sealed partial class ServiceBusReceiverWrapper : IServiceBusReceiverWrapper { private readonly ServiceBusReceiver _messageReceiver; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// The to wrap. - public ServiceBusReceiverWrapper(ServiceBusReceiver messageReceiver) + /// The used to create the logger. + public ServiceBusReceiverWrapper(ServiceBusReceiver messageReceiver, ILoggerFactory loggerFactory) { _messageReceiver = messageReceiver; + _logger = loggerFactory.CreateLogger(); } /// @@ -70,16 +71,16 @@ public async Task> ReceiveAsync(int batchSi /// public void Close() { - Log.ClosingMessageReceiverConnection(s_logger); + Log.ClosingMessageReceiverConnection(_logger); _messageReceiver.CloseAsync().GetAwaiter().GetResult(); - Log.MessageReceiverConnectionStopped(s_logger); + Log.MessageReceiverConnectionStopped(_logger); } - + public async Task CloseAsync() { - Log.ClosingMessageReceiverConnection(s_logger); + Log.ClosingMessageReceiverConnection(_logger); await _messageReceiver.CloseAsync().ConfigureAwait(false); - Log.MessageReceiverConnectionStopped(s_logger); + Log.MessageReceiverConnectionStopped(_logger); } /// diff --git a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubChannelFactory.cs b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubChannelFactory.cs index 597b97f981..6b6216fbba 100644 --- a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubChannelFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubChannelFactory.cs @@ -1,6 +1,7 @@ using Google.Api.Gax.Grpc; using Google.Cloud.PubSub.V1; using Grpc.Core; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.GcpPubSub; @@ -11,10 +12,10 @@ namespace Paramore.Brighter.MessagingGateway.GcpPubSub; /// on the Pub/Sub service. /// /// The connection details for the Google Cloud Pub/Sub gateway. -public class GcpPubSubChannelFactory(GcpMessagingGatewayConnection connection) +public class GcpPubSubChannelFactory(GcpMessagingGatewayConnection connection, ILoggerFactory loggerFactory) : GcpPubSubMessageGateway(connection), IAmAChannelFactory { - private readonly GcpPubSubConsumerFactory _consumerFactory = new(connection); + private readonly GcpPubSubConsumerFactory _consumerFactory = new(connection, loggerFactory); /// /// Creates a synchronous for the given subscription. diff --git a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubConsumerFactory.cs index 6809efdeff..229cf096c0 100644 --- a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubConsumerFactory.cs @@ -1,6 +1,7 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using Google.Api.Gax; using Google.Cloud.PubSub.V1; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.GcpPubSub; @@ -12,10 +13,12 @@ namespace Paramore.Brighter.MessagingGateway.GcpPubSub; /// dedicated pull consumers, as well as ensuring the underlying subscription exists. /// /// The connection details for the Google Cloud Pub/Sub gateway. -public class GcpPubSubConsumerFactory(GcpMessagingGatewayConnection connection) +/// The used to create loggers for the consumers. +public class GcpPubSubConsumerFactory(GcpMessagingGatewayConnection connection, ILoggerFactory loggerFactory) : GcpPubSubMessageGateway(connection), IAmAMessageConsumerFactory { private readonly GcpMessagingGatewayConnection _connection = connection; + private readonly ILoggerFactory _loggerFactory = loggerFactory; /// /// Creates a synchronous message consumer for the given subscription. @@ -81,7 +84,7 @@ private async Task CreateAsync(GcpPubSubSubscription pubSubSubscription) { // Create a new, non-shared consumer that uses the Pull API for each request return new GcpPullMessageConsumer(_connection, subscriptionName, - pubSubSubscription.BufferSize, pubSubSubscription.TimeProvider); + pubSubSubscription.BufferSize, pubSubSubscription.TimeProvider, _loggerFactory); } // If not Pull, use Stream mode. Stream mode consumers are shared per subscription to manage @@ -100,7 +103,8 @@ private async Task CreateAsync(GcpPubSubSubscription pubSubSubscription) _connection, consumer, subscriptionName, - pubSubSubscription.TimeProvider); + pubSubSubscription.TimeProvider, + _loggerFactory); } private Google.Cloud.PubSub.V1.SubscriberClient CreateSubscriberClient(Google.Cloud.PubSub.V1.SubscriptionName subscriptionName, diff --git a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubStreamMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubStreamMessageConsumer.cs index fc30338d24..bce94a3e9d 100644 --- a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubStreamMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubStreamMessageConsumer.cs @@ -1,7 +1,6 @@ using Google.Cloud.PubSub.V1; using Google.Protobuf.WellKnownTypes; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.GcpPubSub; @@ -19,11 +18,12 @@ public partial class GcpPubSubStreamMessageConsumer( GcpMessagingGatewayConnection connection, GcpStreamConsumer consumer, Google.Cloud.PubSub.V1.SubscriptionName subscriptionName, - TimeProvider timeProvider) : IAmAMessageConsumerSync, IAmAMessageConsumerAsync + TimeProvider timeProvider, + ILoggerFactory loggerFactory) : IAmAMessageConsumerSync, IAmAMessageConsumerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + private readonly ILogger _logger = loggerFactory.CreateLogger(); + /// /// Synchronously acknowledges a message, signalling the Pub/Sub service that the message /// has been successfully processed and can be discarded. @@ -35,11 +35,11 @@ public void Acknowledge(Message message) { return; } - + gcpStreamMessage.Accepted(); - Log.AcknowledgeSuccess(s_logger, message.Id.Value, "", subscriptionName.ToString()); + Log.AcknowledgeSuccess(_logger, message.Id.Value, "", subscriptionName.ToString()); } - + /// /// Asynchronously acknowledges a message, signalling the Pub/Sub service that the message /// has been successfully processed and can be discarded. @@ -87,12 +87,12 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { return true; } - + gcpStreamMessage.Accepted(); - Log.RejectMessage(s_logger, message.Id.Value, "", subscriptionName.ToString()); + Log.RejectMessage(_logger, message.Id.Value, "", subscriptionName.ToString()); return true; } - + /// /// Asynchronously rejects a message. In this implementation, it calls /// to signal processing completion and prevents redelivery, while logging the rejection. @@ -117,22 +117,22 @@ public void Purge() { var client = connection.GetOrCreateSubscriberServiceApiClient(); - Log.PurgeStart(s_logger, subscriptionName.ToString()); + Log.PurgeStart(_logger, subscriptionName.ToString()); client.Seek(new SeekRequest { Time = Timestamp.FromDateTimeOffset(timeProvider.GetUtcNow().AddMinutes(1)) }); - Log.PurgeComplete(s_logger, subscriptionName.ToString()); + Log.PurgeComplete(_logger, subscriptionName.ToString()); } catch (Exception ex) { - Log.PurgeError(s_logger, ex, subscriptionName.ToString()); + Log.PurgeError(_logger, ex, subscriptionName.ToString()); throw; } } - + /// /// Asynchronously purges all messages from the subscription backlog by executing a /// Pub/Sub Seek operation to a timestamp slightly in the future. @@ -146,17 +146,17 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) { var client = await connection.CreateSubscriberServiceApiClientAsync(); - Log.PurgeStart(s_logger, subscriptionName.ToString()); + Log.PurgeStart(_logger, subscriptionName.ToString()); await client.SeekAsync( new SeekRequest { Time = Timestamp.FromDateTimeOffset(timeProvider.GetUtcNow().AddMinutes(1)) }, cancellationToken); - Log.PurgeComplete(s_logger, subscriptionName.ToString()); + Log.PurgeComplete(_logger, subscriptionName.ToString()); } catch (Exception ex) { - Log.PurgeError(s_logger, ex, subscriptionName.ToString()); + Log.PurgeError(_logger, ex, subscriptionName.ToString()); throw; } } @@ -171,7 +171,7 @@ public Message[] Receive(TimeSpan? timeOut = null) { return BrighterAsyncContext.Run(() => ReceiveAsync(timeOut)); } - + /// /// Asynchronously reads the next message from the internal channel reader, waiting /// until a message is available or the timeout is reached. @@ -198,7 +198,7 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, Cancellation return [Parser.ToBrighterMessage(message)]; } } - + return [new Message()]; } catch (OperationCanceledException) @@ -220,9 +220,9 @@ public bool Requeue(Message message, TimeSpan? delay = null) { return true; } - + gcpStreamMessage.Reject(); - Log.RequeueComplete(s_logger, message.Id.Value); + Log.RequeueComplete(_logger, message.Id.Value); return true; } @@ -239,7 +239,7 @@ public Task RequeueAsync(Message message, TimeSpan? delay = null, { return Task.FromResult(Requeue(message, delay)); } - + /// /// Disposes of the consumer's resources synchronously. /// @@ -247,7 +247,7 @@ public void Dispose() { consumer.StopAsync().GetAwaiter().GetResult(); } - + /// /// Disposes of the consumer's resources asynchronously. /// @@ -256,7 +256,7 @@ public async ValueTask DisposeAsync() { await consumer.StopAsync(); } - + private static partial class Log { [LoggerMessage(LogLevel.Information, "GcpStreamMessageConsumer: The message {Id} acknowledged with the receipt handle {ReceiptHandle} on the subscription {SubscriptionName}")] diff --git a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPullMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPullMessageConsumer.cs index 88dce2619b..6e69f4771b 100644 --- a/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPullMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPullMessageConsumer.cs @@ -2,7 +2,6 @@ using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.GcpPubSub; @@ -15,11 +14,12 @@ public partial class GcpPullMessageConsumer( GcpMessagingGatewayConnection connection, Google.Cloud.PubSub.V1.SubscriptionName subscriptionName, int batchSize, - TimeProvider timeProvider) + TimeProvider timeProvider, + ILoggerFactory loggerFactory) : IAmAMessageConsumerAsync, IAmAMessageConsumerSync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + private readonly ILogger _logger = loggerFactory.CreateLogger(); + /// /// Synchronously acknowledges a message. /// @@ -35,11 +35,11 @@ public void Acknowledge(Message message) { var client = connection.GetOrCreateSubscriberServiceApiClient(); client.Acknowledge(subscriptionName, [ackId]); - Log.AcknowledgeSuccess(s_logger, message.Id.Value, ackId, subscriptionName.ToString()); + Log.AcknowledgeSuccess(_logger, message.Id.Value, ackId, subscriptionName.ToString()); } catch (Exception ex) { - Log.AcknowledgeError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.AcknowledgeError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); throw; } } @@ -61,11 +61,11 @@ public async Task AcknowledgeAsync(Message message, CancellationToken cancellati { var client = await connection.CreateSubscriberServiceApiClientAsync(); await client.AcknowledgeAsync(subscriptionName, [ackId], cancellationToken); - Log.AcknowledgeSuccess(s_logger, message.Id.Value, ackId, subscriptionName.ToString()); + Log.AcknowledgeSuccess(_logger, message.Id.Value, ackId, subscriptionName.ToString()); } catch (Exception ex) { - Log.AcknowledgeError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.AcknowledgeError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); throw; } } @@ -98,14 +98,14 @@ public void Purge() { var client = connection.GetOrCreateSubscriberServiceApiClient(); - Log.PurgeStart(s_logger, subscriptionName.ToString()); + Log.PurgeStart(_logger, subscriptionName.ToString()); client.Seek( new SeekRequest { Time = Timestamp.FromDateTimeOffset(timeProvider.GetUtcNow().AddMinutes(1)) }); - Log.PurgeComplete(s_logger, subscriptionName.ToString()); + Log.PurgeComplete(_logger, subscriptionName.ToString()); } catch (Exception ex) { - Log.PurgeError(s_logger, ex, subscriptionName.ToString()); + Log.PurgeError(_logger, ex, subscriptionName.ToString()); throw; } } @@ -122,17 +122,17 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) { var client = await connection.CreateSubscriberServiceApiClientAsync(); - Log.PurgeStart(s_logger, subscriptionName.ToString()); + Log.PurgeStart(_logger, subscriptionName.ToString()); await client.SeekAsync( new SeekRequest { Time = Timestamp.FromDateTimeOffset(timeProvider.GetUtcNow().AddMinutes(1)) }, cancellationToken); - Log.PurgeComplete(s_logger, subscriptionName.ToString()); + Log.PurgeComplete(_logger, subscriptionName.ToString()); } catch (Exception ex) { - Log.PurgeError(s_logger, ex, subscriptionName.ToString()); + Log.PurgeError(_logger, ex, subscriptionName.ToString()); throw; } } @@ -152,7 +152,7 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, Cancellation response = await client.PullAsync( new PullRequest { - SubscriptionAsSubscriptionName = subscriptionName, + SubscriptionAsSubscriptionName = subscriptionName, MaxMessages = batchSize, }, cancellationToken); @@ -164,20 +164,20 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, Cancellation } catch (RpcException rcpException) when (rcpException.Status.StatusCode == StatusCode.Unavailable) { - Log.ReceiveConnectionError(s_logger); + Log.ReceiveConnectionError(_logger); throw new ChannelFailureException("Error connecting to Pub/Sub, see inner exception for details", rcpException); } catch (Exception e) { - Log.ReceiveError(s_logger, e, subscriptionName.ToString()); + Log.ReceiveError(_logger, e, subscriptionName.ToString()); throw; } return response.ReceivedMessages.Select(Parser.ToBrighterMessage).ToArray(); } - + /// /// Synchronously receives a batch of messages from the subscription using the Pull API. /// @@ -192,7 +192,8 @@ public Message[] Receive(TimeSpan? timeOut = null) var client = connection.GetOrCreateSubscriberServiceApiClient(); response = client.Pull(new PullRequest { - SubscriptionAsSubscriptionName = subscriptionName, MaxMessages = batchSize + SubscriptionAsSubscriptionName = subscriptionName, + MaxMessages = batchSize }); if (response.ReceivedMessages.Count == 0) @@ -202,20 +203,20 @@ public Message[] Receive(TimeSpan? timeOut = null) } catch (RpcException rcpException) when (rcpException.Status.StatusCode == StatusCode.Unavailable) { - Log.ReceiveConnectionError(s_logger); + Log.ReceiveConnectionError(_logger); throw new ChannelFailureException("Error connecting to Pub/Sub, see inner exception for details", rcpException); } catch (Exception e) { - Log.ReceiveError(s_logger, e, subscriptionName.ToString()); + Log.ReceiveError(_logger, e, subscriptionName.ToString()); throw; } return response.ReceivedMessages.Select(Parser.ToBrighterMessage).ToArray(); } - - /// + + /// /// Synchronously rejects a message. /// /// The message to reject. @@ -232,18 +233,18 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { var client = connection.GetOrCreateSubscriberServiceApiClient(); - Log.RejectMessage(s_logger, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RejectMessage(_logger, message.Id.Value, ackId, subscriptionName.ToString()); client.Acknowledge(subscriptionName, [ackId]); } catch (Exception ex) { - Log.RejectError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RejectError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); throw; } return true; } - + /// /// Asynchronously rejects a message. /// @@ -261,12 +262,12 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea try { var client = await connection.CreateSubscriberServiceApiClientAsync(); - Log.RejectMessage(s_logger, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RejectMessage(_logger, message.Id.Value, ackId, subscriptionName.ToString()); await client.AcknowledgeAsync(subscriptionName, [ackId], cancellationToken); } catch (Exception ex) { - Log.RejectError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RejectError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); throw; } @@ -291,21 +292,21 @@ public bool Requeue(Message message, TimeSpan? delay = null) { var client = connection.GetOrCreateSubscriberServiceApiClient(); - Log.RequeueStart(s_logger, message.Id.Value); + Log.RequeueStart(_logger, message.Id.Value); // The requeue policy is defined by subscription, during its creation client.ModifyAckDeadline(subscriptionName, [ackId], 0); - Log.RequeueComplete(s_logger, message.Id.Value); + Log.RequeueComplete(_logger, message.Id.Value); return true; } catch (Exception ex) { - Log.RequeueError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RequeueError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); return false; } } - + /// /// Asynchronously requeues a message by setting its acknowledgment deadline to zero seconds. /// This tells Pub/Sub to immediately redeliver the message according to the subscription's retry policy. @@ -326,7 +327,7 @@ public async Task RequeueAsync(Message message, TimeSpan? delay = null, { var client = await connection.CreateSubscriberServiceApiClientAsync(); - Log.RequeueStart(s_logger, message.Id.Value); + Log.RequeueStart(_logger, message.Id.Value); // The requeue policy is defined by subscription, during its creation await client.ModifyAckDeadlineAsync(new ModifyAckDeadlineRequest @@ -336,12 +337,12 @@ await client.ModifyAckDeadlineAsync(new ModifyAckDeadlineRequest AckDeadlineSeconds = 0 }, cancellationToken); - Log.RequeueComplete(s_logger, message.Id.Value); + Log.RequeueComplete(_logger, message.Id.Value); return true; } catch (Exception ex) { - Log.RequeueError(s_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); + Log.RequeueError(_logger, ex, message.Id.Value, ackId, subscriptionName.ToString()); return false; } } diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs index 0cfcdd31cb..7e52dc5df0 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs @@ -112,11 +112,13 @@ public partial class KafkaMessageConsumer : KafkaMessagingGateway, IAmAMessageCo /// requeue producer will use this scheduler for delayed sends. /// The used to apply Kafka group coordination settings. Defaults to with when . /// The consumer back-fills any properties of a in place, so do not share an instance across subscriptions. + /// The used to create loggers for this consumer and the producers it creates. /// Throws an exception if required parameters missing public KafkaMessageConsumer( KafkaMessagingGatewayConfiguration configuration, RoutingKey routingKey, string? groupId, + ILoggerFactory loggerFactory, AutoOffsetReset offsetDefault = AutoOffsetReset.Earliest, TimeSpan? sessionTimeout = null, TimeSpan? maxPollInterval = null, @@ -136,33 +138,21 @@ public KafkaMessageConsumer( IAmAMessageScheduler? scheduler = null, IGroupProtocol? groupProtocol = null, Func? errorLogLevel = null) + : base(loggerFactory) { if (groupId is null) throw new ConfigurationException("You must set a GroupId for the consumer"); - + Topic = routingKey ?? throw new ConfigurationException("You must set a RoutingKey as the Topic for the consumer"); - + _configuration = configuration ?? throw new ConfigurationException("You must set a KafkaMessagingGatewayConfiguration to connect to a broker"); _scheduler = scheduler; _errorLogLevel = errorLogLevel; _deadLetterRoutingKey = deadLetterRoutingKey; _invalidMessageRoutingKey = invalidMessageRoutingKey; - // LazyThreadSafetyMode.None: message pumps are single-threaded per consumer, so no - // thread-safety mode is needed. None does not cache exceptions, allowing the factory - // to retry on the next .Value access after a transient failure. - if (_deadLetterRoutingKey != null) - { - _deadLetterProducer = new Lazy( - () => CreateProducer(_deadLetterRoutingKey, Log.ErrorCreatingDLQ), LazyThreadSafetyMode.None); - } + (_deadLetterProducer, _invalidMessageProducer) = CreateRejectionProducers(); - if (_invalidMessageRoutingKey != null) - { - _invalidMessageProducer = new Lazy( - () => CreateProducer(_invalidMessageRoutingKey, Log.ErrorCreatingInvalidMessage), LazyThreadSafetyMode.None); - } - sessionTimeout ??= TimeSpan.FromSeconds(10); maxPollInterval ??= TimeSpan.FromSeconds(10); sweepUncommittedOffsetsInterval ??= TimeSpan.FromSeconds(30); @@ -171,28 +161,28 @@ public KafkaMessageConsumer( ClientConfig = new ClientConfig { - BootstrapServers = string.Join(",", configuration.BootStrapServers), + BootstrapServers = string.Join(",", configuration.BootStrapServers), ClientId = configuration.Name, Debug = configuration.Debug, SaslMechanism = configuration.SaslMechanisms.HasValue ? (Confluent.Kafka.SaslMechanism?)((int)configuration.SaslMechanisms.Value) : null, SaslKerberosPrincipal = configuration.SaslKerberosPrincipal, SaslUsername = configuration.SaslUsername, SaslPassword = configuration.SaslPassword, - SecurityProtocol = configuration.SecurityProtocol.HasValue ? (Confluent.Kafka.SecurityProtocol?)((int) configuration.SecurityProtocol.Value) : null, + SecurityProtocol = configuration.SecurityProtocol.HasValue ? (Confluent.Kafka.SecurityProtocol?)((int)configuration.SecurityProtocol.Value) : null, SslCaLocation = configuration.SslCaLocation }; - + // We repeat properties because copying them from the ClientConfig modifies the ClientConfig in place _consumerConfig = new ConsumerConfig { - BootstrapServers = string.Join(",", configuration.BootStrapServers), + BootstrapServers = string.Join(",", configuration.BootStrapServers), ClientId = configuration.Name, Debug = configuration.Debug, SaslMechanism = configuration.SaslMechanisms.HasValue ? (Confluent.Kafka.SaslMechanism?)((int)configuration.SaslMechanisms.Value) : null, SaslKerberosPrincipal = configuration.SaslKerberosPrincipal, SaslUsername = configuration.SaslUsername, SaslPassword = configuration.SaslPassword, - SecurityProtocol = configuration.SecurityProtocol.HasValue ? (Confluent.Kafka.SecurityProtocol?)((int) configuration.SecurityProtocol.Value) : null, + SecurityProtocol = configuration.SecurityProtocol.HasValue ? (Confluent.Kafka.SecurityProtocol?)((int)configuration.SecurityProtocol.Value) : null, SslCaLocation = configuration.SslCaLocation, GroupId = groupId, AutoOffsetReset = offsetDefault, @@ -213,7 +203,7 @@ public KafkaMessageConsumer( } groupProtocol.Apply(_consumerConfig); - + if (configHook != null) configHook(_consumerConfig); @@ -224,61 +214,79 @@ public KafkaMessageConsumer( timeProvider ??= TimeProvider.System; _timeProvider = timeProvider; _lastFlushAt = _timeProvider.GetUtcNow().UtcDateTime; - _sweeperTimer = timeProvider.CreateTimer(_ => - { - if (_isClosed) - { - return; - } - - SweepOffsets(); - }, null, _sweepUncommittedInterval, _sweepUncommittedInterval); + _sweeperTimer = timeProvider.CreateTimer( + _ => SweepOffsetsIfOpen(), null, _sweepUncommittedInterval, _sweepUncommittedInterval); _consumer = new ConsumerBuilder(_consumerConfig) .SetPartitionsAssignedHandler((_, list) => { var partitions = list.Select(p => $"{p.Topic} : {p.Partition.Value}"); - - Log.PartitionAdded(s_logger, String.Join(",", partitions)); - + + Log.PartitionAdded(_logger, String.Join(",", partitions)); + _partitions.AddRange(list); }) .SetPartitionsRevokedHandler((_, list) => { //We should commit any offsets we have stored for these partitions CommitOffsetsFor(list); - + var revokedPartitionInfo = list.Select(tpo => $"{tpo.Topic} : {tpo.Partition}").ToList(); - - Log.PartitionsRevoked(s_logger, string.Join(",", revokedPartitionInfo)); - + + Log.PartitionsRevoked(_logger, string.Join(",", revokedPartitionInfo)); + _partitions = _partitions.Where(tp => list.All(tpo => tpo.TopicPartition != tp)).ToList(); }) .SetPartitionsLostHandler((_, list) => { var lostPartitions = list.Select(tpo => $"{tpo.Topic} : {tpo.Partition}").ToList(); - - Log.PartitionsLost(s_logger, string.Join(",", lostPartitions)); - + + Log.PartitionsLost(_logger, string.Join(",", lostPartitions)); + _partitions = _partitions.Where(tp => list.All(tpo => tpo.TopicPartition != tp)).ToList(); }) .SetErrorHandler((_, error) => HandleError(error)) .Build(); - Log.SubscribingToTopic(s_logger, Topic); + Log.SubscribingToTopic(_logger, Topic); _consumer.Subscribe([Topic.Value]); - _creator = new KafkaMessageCreator(); - + _creator = new KafkaMessageCreator(_loggerFactory.CreateLogger()); + MakeChannels = makeChannels; Topic = routingKey; NumPartitions = numPartitions; ReplicationFactor = replicationFactor; TopicFindTimeout = topicFindTimeout.Value; - + EnsureTopic(); } + private (Lazy? DeadLetter, Lazy? Invalid) + CreateRejectionProducers() + { + // Message pumps are single-threaded per consumer. None also avoids caching transient factory failures. + var deadLetterProducer = _deadLetterRoutingKey is null + ? null + : new Lazy( + () => CreateProducer(_deadLetterRoutingKey, Log.ErrorCreatingDLQ), LazyThreadSafetyMode.None); + var invalidMessageProducer = _invalidMessageRoutingKey is null + ? null + : new Lazy( + () => CreateProducer(_invalidMessageRoutingKey, Log.ErrorCreatingInvalidMessage), + LazyThreadSafetyMode.None); + + return (deadLetterProducer, invalidMessageProducer); + } + + private void SweepOffsetsIfOpen() + { + if (_isClosed) + return; + + SweepOffsets(); + } + /// /// Destroys the consumer /// @@ -302,7 +310,7 @@ public void Acknowledge(Message message) { if (!message.Header.Bag.TryGetValue(HeaderNames.PARTITION_OFFSET, out var bagData)) { - Log.CannotAcknowledgeMessage(s_logger, message.Id.Value); + Log.CannotAcknowledgeMessage(_logger, message.Id.Value); return; } @@ -311,26 +319,26 @@ public void Acknowledge(Message message) var topicPartitionOffset = bagData as TopicPartitionOffset; if (topicPartitionOffset == null) { - Log.CannotAcknowledgeMessage(s_logger, message.Id.Value); + Log.CannotAcknowledgeMessage(_logger, message.Id.Value); return; } var offset = new TopicPartitionOffset(topicPartitionOffset.TopicPartition, new Offset(topicPartitionOffset.Offset + 1)); - Log.StoringOffset(s_logger, new Offset(topicPartitionOffset.Offset + 1).Value, topicPartitionOffset.TopicPartition.Topic, topicPartitionOffset.TopicPartition.Partition.Value); + Log.StoringOffset(_logger, new Offset(topicPartitionOffset.Offset + 1).Value, topicPartitionOffset.TopicPartition.Topic, topicPartitionOffset.TopicPartition.Partition.Value); _offsetStorage.Add(offset); if (_offsetStorage.Count % _maxBatchSize == 0) FlushOffsets(); - Log.CurrentKafkaBatchCount(s_logger, _offsetStorage.Count.ToString(), _maxBatchSize.ToString()); + Log.CurrentKafkaBatchCount(_logger, _offsetStorage.Count.ToString(), _maxBatchSize.ToString()); } catch (TopicPartitionException tpe) { var results = tpe.Results.Select(r => $"Error committing topic {r.Topic} for partition {r.Partition.Value.ToString()} because {r.Error.Reason}"); var errorString = string.Join(Environment.NewLine, results); - Log.ErrorCommittingOffsetsAsDebug(s_logger, errorString); + Log.ErrorCommittingOffsetsAsDebug(_logger, errorString); } } @@ -352,7 +360,7 @@ public void Acknowledge(Message message) Acknowledge(message); return Task.CompletedTask; } - + /// /// Nacks the specified message by seeking the consumer back to the message's offset, /// so that the next call will return the same message again. @@ -362,7 +370,7 @@ public void Nack(Message message) { if (!message.Header.Bag.TryGetValue(HeaderNames.PARTITION_OFFSET, out var bagData)) { - Log.CannotNackMessage(s_logger, message.Id.Value); + Log.CannotNackMessage(_logger, message.Id.Value); return; } @@ -371,17 +379,17 @@ public void Nack(Message message) var topicPartitionOffset = bagData as TopicPartitionOffset; if (topicPartitionOffset == null) { - Log.CannotNackMessageTypeMismatch(s_logger, message.Id.Value, bagData?.GetType().FullName ?? "null"); + Log.CannotNackMessageTypeMismatch(_logger, message.Id.Value, bagData?.GetType().FullName ?? "null"); return; } - Log.NackingMessage(s_logger, topicPartitionOffset.Offset.Value, topicPartitionOffset.Topic, topicPartitionOffset.Partition.Value); + Log.NackingMessage(_logger, topicPartitionOffset.Offset.Value, topicPartitionOffset.Topic, topicPartitionOffset.Partition.Value); _consumer.Seek(topicPartitionOffset); } catch (Exception ex) when (ex is KafkaException or InvalidOperationException) { - Log.ErrorSeekingOffsetForNack(s_logger, ex.Message); + Log.ErrorSeekingOffsetForNack(_logger, ex.Message); } } @@ -406,7 +414,8 @@ public Task NackAsync(Message message, CancellationToken cancellationToken = def public void Close() { //we will be called twice if explicitly disposed as well as closed, so just skip in that case - if (_isClosed) return; + if (_isClosed) + return; try { @@ -418,13 +427,13 @@ public void Close() } else { - Log.SkippedCommittingOffsetsBeforeClose(s_logger); + Log.SkippedCommittingOffsetsBeforeClose(_logger); } } catch (Exception ex) { //Close anyway, we just will get replay of those messages - Log.ErrorCommittingOffsetBeforeClosing(s_logger, ex.Message); + Log.ErrorCommittingOffsetBeforeClosing(_logger, ex.Message); } finally { @@ -433,9 +442,9 @@ public void Close() } } - /// - /// Purges the specified queue name. - /// + /// + /// Purges the specified queue name. + /// /// /// There is no 'queue' to purge in Kafka, so we treat this as moving the offset to the end of any assigned partitions, /// thus skipping over anything that exists at that point. @@ -450,7 +459,7 @@ public void Purge() _consumer.Seek(new TopicPartitionOffset(topicPartition, Offset.End)); } } - + /// /// Purges the specified queue name. /// @@ -461,12 +470,12 @@ public void Purge() /// so we use a new thread pool thread to run this and await that. This could lead to thread pool exhaustion but Purge is rarely used /// in production code /// - /// + /// public async Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken)) { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var purgeTask = Task.Run(() => + var purgeTask = Task.Run(() => { try { @@ -478,7 +487,7 @@ public void Purge() tcs.SetException(e); } }, cancellationToken); - + await tcs.Task; await purgeTask; } @@ -497,53 +506,53 @@ public Message[] Receive(TimeSpan? timeOut = null) { if (_hasFatalError) throw new ChannelFailureException("Fatal error on Kafka consumer, see logs for details"); - + timeOut ??= TimeSpan.FromMilliseconds(300); - + try { - + LogOffSets(); - Log.ConsumingMessages(s_logger, timeOut.Value.TotalMilliseconds); + Log.ConsumingMessages(_logger, timeOut.Value.TotalMilliseconds); var consumeResult = _consumer.Consume(timeOut.Value); if (consumeResult == null) { CheckHasPartitions(); - - Log.NoMessagesAvailable(s_logger); + + Log.NoMessagesAvailable(_logger); return [new Message()]; } if (consumeResult.IsPartitionEOF) { - Log.EndOfPartition(s_logger, _consumer.MemberId); + Log.EndOfPartition(_logger, _consumer.MemberId); return [new Message()]; } - Log.UsableMessageRetrieved(s_logger, consumeResult.Message.Value); - Log.PartitionOffsetValue(s_logger, consumeResult.Partition, consumeResult.Offset, consumeResult.Message.Value); + Log.UsableMessageRetrieved(_logger, consumeResult.Message.Value); + Log.PartitionOffsetValue(_logger, consumeResult.Partition, consumeResult.Offset, consumeResult.Message.Value); return [_creator.CreateMessage(consumeResult)]; } catch (ConsumeException consumeException) { - Log.ErrorListeningToTopic(s_logger, consumeException, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); + Log.ErrorListeningToTopic(_logger, consumeException, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); throw new ChannelFailureException("Error connecting to Kafka, see inner exception for details", consumeException); } catch (KafkaException kafkaException) { - Log.ErrorListeningToTopic(s_logger, kafkaException, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); + Log.ErrorListeningToTopic(_logger, kafkaException, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); if (kafkaException.Error.IsFatal) //this can't be recovered and requires a new consumer throw; - + throw new ChannelFailureException("Error connecting to Kafka, see inner exception for details", kafkaException); } catch (Exception exception) { - Log.ErrorListeningToTopic(s_logger, exception, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); + Log.ErrorListeningToTopic(_logger, exception, Topic ?? RoutingKey.Empty, _consumerConfig.GroupId, _consumerConfig.BootstrapServers); throw; } } @@ -566,7 +575,7 @@ public Message[] Receive(TimeSpan? timeOut = null) var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); timeOut ??= TimeSpan.Zero; - var recieveTask = Task.Run(() => + var recieveTask = Task.Run(() => { try { @@ -578,10 +587,10 @@ public Message[] Receive(TimeSpan? timeOut = null) tcs.SetException(e); } }, cancellationToken); - + var messages = await tcs.Task; await recieveTask; - + return messages; } @@ -598,58 +607,58 @@ public Message[] Receive(TimeSpan? timeOut = null) /// True if the message has been removed from the channel, false otherwise public bool Reject(Message message, MessageRejectionReason? reason = null) { - // If no reason provided or no channels configured, just acknowledge - if (_deadLetterProducer == null && _invalidMessageProducer == null) - { - if (reason != null) - { - Log.NoChannelsConfiguredForRejection(s_logger, message.Header.MessageId.Value, reason.RejectionReason.ToString()); - } - Acknowledge(message); - return true; - } - - var rejectionReason = reason?.RejectionReason ?? RejectionReason.None; - var partitionOffset = ExtractPartitionOffset(message); - - try - { - RefreshMetadata(message, reason); - - // Determine routing based on rejection reason - var (routingKey, shouldRoute, isFallingBackToDlq) = DetermineRejectionRoute( - rejectionReason, _invalidMessageProducer != null, _deadLetterProducer != null); - - IAmAMessageProducerSync? producer = null; - if (shouldRoute) - { - message.Header.Topic = routingKey!; - if (isFallingBackToDlq) - Log.FallingBackToDLQ(s_logger, message.Header.MessageId.Value); - - // Get the appropriate producer based on routing - producer = GetRejectionProducer(routingKey); - } - - if (producer != null) - { - producer.Send(message); - Log.MessageSentToRejectionChannel(s_logger, message.Header.MessageId.Value, rejectionReason.ToString()); - } - else - { - Log.NoChannelsConfiguredForRejection(s_logger, message.Header.MessageId.Value, rejectionReason.ToString()); - } - } - catch (Exception ex) - { - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Header.MessageId.Value, rejectionReason.ToString()); - Acknowledge(message); - return true; - } - - AcknowledgeOffset(partitionOffset); - return true; + // If no reason provided or no channels configured, just acknowledge + if (_deadLetterProducer == null && _invalidMessageProducer == null) + { + if (reason != null) + { + Log.NoChannelsConfiguredForRejection(_logger, message.Header.MessageId.Value, reason.RejectionReason.ToString()); + } + Acknowledge(message); + return true; + } + + var rejectionReason = reason?.RejectionReason ?? RejectionReason.None; + var partitionOffset = ExtractPartitionOffset(message); + + try + { + RefreshMetadata(message, reason); + + // Determine routing based on rejection reason + var (routingKey, shouldRoute, isFallingBackToDlq) = DetermineRejectionRoute( + rejectionReason, _invalidMessageProducer != null, _deadLetterProducer != null); + + IAmAMessageProducerSync? producer = null; + if (shouldRoute) + { + message.Header.Topic = routingKey!; + if (isFallingBackToDlq) + Log.FallingBackToDLQ(_logger, message.Header.MessageId.Value); + + // Get the appropriate producer based on routing + producer = GetRejectionProducer(routingKey); + } + + if (producer != null) + { + producer.Send(message); + Log.MessageSentToRejectionChannel(_logger, message.Header.MessageId.Value, rejectionReason.ToString()); + } + else + { + Log.NoChannelsConfiguredForRejection(_logger, message.Header.MessageId.Value, rejectionReason.ToString()); + } + } + catch (Exception ex) + { + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Header.MessageId.Value, rejectionReason.ToString()); + Acknowledge(message); + return true; + } + + AcknowledgeOffset(partitionOffset); + return true; } /// @@ -670,7 +679,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea { if (reason != null) { - Log.NoChannelsConfiguredForRejection(s_logger, message.Header.MessageId.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Header.MessageId.Value, reason.RejectionReason.ToString()); } await AcknowledgeAsync(message, cancellationToken); return true; @@ -692,7 +701,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDLQ(s_logger, message.Header.MessageId.Value); + Log.FallingBackToDLQ(_logger, message.Header.MessageId.Value); // Get the appropriate producer based on routing producer = GetRejectionProducer(routingKey); @@ -701,16 +710,16 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Header.MessageId.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Header.MessageId.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Header.MessageId.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Header.MessageId.Value, rejectionReason.ToString()); } } catch (Exception ex) { - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Header.MessageId.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Header.MessageId.Value, rejectionReason.ToString()); await AcknowledgeAsync(message, cancellationToken); return true; } @@ -783,7 +792,7 @@ public bool Requeue(Message message, TimeSpan? delay = null) AcknowledgeOffset(partitionOffset); return true; } - + /// /// Handles an error raised by the underlying Kafka consumer. Extracted from the /// SetErrorHandler callback so the behaviour is reachable from tests. Not intended to be @@ -805,13 +814,13 @@ public void HandleError(Error error) // Log against the error we actually received, independent of the latch, so a non-fatal error // that arrives after a fatal one is still logged as non-fatal. - Log.KafkaError(s_logger, logLevel, error.Code, error.Reason, error.IsFatal); + Log.KafkaError(_logger, logLevel, error.Code, error.Reason, error.IsFatal); } private void CheckHasPartitions() { if (_partitions.Count <= 0) - Log.NoPartitionsAllocated(s_logger); + Log.NoPartitionsAllocated(_logger); } @@ -822,27 +831,28 @@ private void LogOffSets() try { var highestReadOffset = new Dictionary(); - + var committedOffsets = _consumer.Committed(_partitions, _readCommittedOffsetsTimeout); foreach (var committedOffset in committedOffsets) { if (highestReadOffset.TryGetValue(committedOffset.TopicPartition, out long offset)) { - if (committedOffset.Offset < offset) continue; + if (committedOffset.Offset < offset) + continue; } highestReadOffset[committedOffset.TopicPartition] = committedOffset.Offset; } - foreach (KeyValuePair pair in highestReadOffset) + foreach (KeyValuePair pair in highestReadOffset) { var topicPartition = pair.Key; - Log.OffsetToConsumeFrom(s_logger, pair.Value.ToString(), topicPartition.Partition.Value.ToString(), topicPartition.Topic); + Log.OffsetToConsumeFrom(_logger, pair.Value.ToString(), topicPartition.Partition.Value.ToString(), topicPartition.Topic); } } catch (KafkaException ke) { //This is only login for debug, so skip errors here - Log.KafkaErrorLoggingOffsets(s_logger, ke.Message); + Log.KafkaErrorLoggingOffsets(_logger, ke.Message); } } @@ -854,7 +864,7 @@ public int StoredOffsets() { return _offsetStorage.Count; } - + /// /// We commit a batch size worth at a time; this may be called from the sweeper thread, and we don't want it to /// loop endlessly over the offset list as new items are added, which will trigger a commit anyway. So we limit @@ -875,20 +885,20 @@ private void CommitOffsets() } - if (s_logger.IsEnabled(LogLevel.Information)) + if (_logger.IsEnabled(LogLevel.Information)) { var offsets = listOffsets.Select(tpo => $"Topic: {tpo.Topic} Partition: {tpo.Partition.Value} Offset: {tpo.Offset.Value}"); var offsetAsString = string.Join(Environment.NewLine, offsets); - Log.CommittingOffsets(s_logger, Environment.NewLine, offsetAsString); + Log.CommittingOffsets(_logger, Environment.NewLine, offsetAsString); } _consumer.Commit(listOffsets); } - catch(Exception ex) + catch (Exception ex) { //may happen if the consumer is not valid when the thread runs - Log.ErrorCommittingOffsetsAsWarning(s_logger, ex.Message); + Log.ErrorCommittingOffsetsAsWarning(_logger, ex.Message); } finally { @@ -907,7 +917,7 @@ private void CommitOffsetsFor(List revokedPartitions) //wait for any in-flight background commit to finish before we commit revoked offsets if (!_flushToken.Wait(s_commitSyncTimeout)) { - Log.SkippedCommittingOffsetsForRevokedPartitions(s_logger); + Log.SkippedCommittingOffsetsForRevokedPartitions(_logger); return; } @@ -939,7 +949,7 @@ private void CommitOffsetsFor(List revokedPartitions) } catch (KafkaException error) { - Log.ErrorCommittingOffsetsDuringPartitionRevoke(s_logger, error.Message, error.Error.Code, error.Error.Reason, error.Error.IsFatal); + Log.ErrorCommittingOffsetsDuringPartitionRevoke(_logger, error.Message, error.Error.Code, error.Error.Reason, error.Error.IsFatal); } } @@ -947,13 +957,13 @@ private void CommitOffsetsFor(List revokedPartitions) [DebuggerStepThrough] private void LogOffSetCommitRevokedPartitions(List revokedOffsetsToCommit) { - Log.SavingRevokedPartitionOffsets(s_logger, revokedOffsetsToCommit.Count); + Log.SavingRevokedPartitionOffsets(_logger, revokedOffsetsToCommit.Count); foreach (var offset in revokedOffsetsToCommit) { - Log.SavingRevokedPartitionOffset(s_logger, offset.Offset.Value.ToString(), offset.Partition.Value.ToString(), offset.Topic); + Log.SavingRevokedPartitionOffset(_logger, offset.Offset.Value.ToString(), offset.Partition.Value.ToString(), offset.Topic); } } - + //Just flush everything private void CommitAllOffsets(DateTime flushTime) { @@ -971,12 +981,12 @@ private void CommitAllOffsets(DateTime flushTime) } - if (s_logger.IsEnabled(LogLevel.Information) && listOffsets.Count != 0) + if (_logger.IsEnabled(LogLevel.Information) && listOffsets.Count != 0) { var offsets = listOffsets.Select(tpo => $"Topic: {tpo.Topic} Partition: {tpo.Partition.Value} Offset: {tpo.Offset.Value}"); var offsetAsString = string.Join(Environment.NewLine, offsets); - Log.SweepingOffsets(s_logger, Environment.NewLine, offsetAsString); + Log.SweepingOffsets(_logger, Environment.NewLine, offsetAsString); } _consumer.Commit(listOffsets); @@ -987,7 +997,7 @@ private void CommitAllOffsets(DateTime flushTime) _flushToken.Release(1); } } - + private void EnsureRequeueProducer() { LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, @@ -1018,13 +1028,13 @@ private void EnsureRequeueProducer() try { - var producer = new KafkaMessageProducer(_configuration, publication); + var producer = new KafkaMessageProducer(_configuration, publication, loggerFactory: _loggerFactory); producer.Init(); return producer; } catch (Exception e) { - logError?.Invoke(s_logger, e); + logError?.Invoke(_logger, e); return null; } } @@ -1037,7 +1047,7 @@ private void EnsureRequeueProducer() return _deadLetterProducer?.Value; return null; } - + /// /// Extracts the from the message bag before it is cleaned for resend. /// @@ -1054,11 +1064,12 @@ private void EnsureRequeueProducer() /// private void AcknowledgeOffset(TopicPartitionOffset? partitionOffset) { - if (partitionOffset == null) return; + if (partitionOffset == null) + return; var offset = new TopicPartitionOffset(partitionOffset.TopicPartition, new Offset(partitionOffset.Offset + 1)); - Log.StoringOffset(s_logger, new Offset(partitionOffset.Offset + 1).Value, partitionOffset.TopicPartition.Topic, partitionOffset.TopicPartition.Partition.Value); + Log.StoringOffset(_logger, new Offset(partitionOffset.Offset + 1).Value, partitionOffset.TopicPartition.Topic, partitionOffset.TopicPartition.Partition.Value); _offsetStorage.Add(offset); if (_offsetStorage.Count % _maxBatchSize == 0) @@ -1091,7 +1102,8 @@ private void RefreshMetadata(Message message, MessageRejectionReason? reason) CleanBagForResend(message); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag[HeaderNames.REJECTION_REASON] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -1112,7 +1124,7 @@ private void RefreshMetadata(Message message, MessageRejectionReason? reason) bool hasInvalidProducer, bool hasDeadLetterProducer) { - + switch (rejectionReason) { case RejectionReason.Unacceptable: @@ -1124,7 +1136,7 @@ private void RefreshMetadata(Message message, MessageRejectionReason? reason) return (null, false, false); case RejectionReason.DeliveryError: - case RejectionReason.None: + case RejectionReason.None: default: // Send to DLQ if (hasDeadLetterProducer) @@ -1149,7 +1161,7 @@ private void FlushOffsets() } else { - Log.SkippedCommittingOffsets(s_logger); + Log.SkippedCommittingOffsets(_logger); } } @@ -1162,7 +1174,7 @@ private void SweepOffsets() { return; } - + if (_flushToken.Wait(TimeSpan.Zero)) { if (now - _lastFlushAt < _sweepUncommittedInterval) @@ -1170,10 +1182,10 @@ private void SweepOffsets() _flushToken.Release(1); return; } - + //This is expensive, so use a background thread Task.Factory.StartNew( - action: state => CommitAllOffsets(state is not null ? (DateTime) state : _timeProvider.GetUtcNow().UtcDateTime), + action: state => CommitAllOffsets(state is not null ? (DateTime)state : _timeProvider.GetUtcNow().UtcDateTime), state: now, cancellationToken: CancellationToken.None, creationOptions: TaskCreationOptions.DenyChildAttach, @@ -1181,13 +1193,14 @@ private void SweepOffsets() } else { - Log.SkippedSweepingOffsets(s_logger); + Log.SkippedSweepingOffsets(_logger); } } private void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + return; _sweeperTimer.Dispose(); Close(); @@ -1236,28 +1249,28 @@ public async ValueTask DisposeAsync() GC.SuppressFinalize(this); } - + private static partial class Log { [LoggerMessage(LogLevel.Information, "Partition Added {Channels}")] public static partial void PartitionAdded(ILogger logger, string channels); - + [LoggerMessage(LogLevel.Information, "Partitions for consumer revoked {Channels}")] public static partial void PartitionsRevoked(ILogger logger, string channels); - + [LoggerMessage(LogLevel.Information, "Partitions for consumer lost {Channels}")] public static partial void PartitionsLost(ILogger logger, string channels); - + // A dynamic-level logger cannot use the [LoggerMessage] attribute with a fixed Level, so we log // through the ILogger directly. Named placeholders are preserved for structured logging providers. public static void KafkaError(ILogger logger, LogLevel logLevel, ErrorCode errorCode, string errorMessage, bool fatalError) { logger.Log(logLevel, "Code: {ErrorCode}, Reason: {ErrorMessage}, Fatal: {FatalError}", errorCode, errorMessage, fatalError); } - + [LoggerMessage(LogLevel.Information, "Kafka consumer subscribing to {Topic}")] public static partial void SubscribingToTopic(ILogger logger, RoutingKey topic); - + [LoggerMessage(LogLevel.Warning, "Cannot acknowledge message {MessageId} as no offset data")] public static partial void CannotAcknowledgeMessage(ILogger logger, string messageId); @@ -1275,67 +1288,67 @@ public static void KafkaError(ILogger logger, LogLevel logLevel, ErrorCode error [LoggerMessage(LogLevel.Information, "Storing offset {Offset} to topic {Topic} for partition {ChannelName}")] public static partial void StoringOffset(ILogger logger, long offset, string topic, int channelName); - + [LoggerMessage(LogLevel.Information, "Current Kafka batch count {OffsetCount} and {MaxBatchSize}")] public static partial void CurrentKafkaBatchCount(ILogger logger, string offsetCount, string maxBatchSize); - + [LoggerMessage(LogLevel.Debug, "Error committing offsets: {NewLine} {ErrorMessage}")] public static partial void ErrorCommittingOffsetsDebug(ILogger logger, string newLine, string errorMessage); - + [LoggerMessage(LogLevel.Debug, "Error committing the current offset to Kafka before closing: {ErrorMessage}")] public static partial void ErrorCommittingOffsetBeforeClosing(ILogger logger, string errorMessage); - + [LoggerMessage(LogLevel.Debug, "Consuming messages from Kafka stream, will wait for {Timeout}")] public static partial void ConsumingMessages(ILogger logger, double timeout); - + [LoggerMessage(LogLevel.Debug, "No messages available from Kafka stream")] public static partial void NoMessagesAvailable(ILogger logger); - + [LoggerMessage(LogLevel.Debug, "Consumer {ConsumerMemberId} has reached the end of the partition")] public static partial void EndOfPartition(ILogger logger, string consumerMemberId); - + [LoggerMessage(LogLevel.Debug, "Usable message retrieved from Kafka stream: {Request}")] public static partial void UsableMessageRetrieved(ILogger logger, byte[] request); - + [LoggerMessage(LogLevel.Debug, "Partition: {ChannelName} Offset: {Offset} Value: {Request}")] public static partial void PartitionOffsetValue(ILogger logger, Partition channelName, Offset offset, byte[] request); - + [LoggerMessage(LogLevel.Error, "KafkaMessageConsumer: There was an error listening to topic {Topic} with groupId {ConsumerGroupId} on bootstrap servers: {Servers})")] public static partial void ErrorListeningToTopic(ILogger logger, Exception exception, RoutingKey topic, string consumerGroupId, string servers); - + [LoggerMessage(LogLevel.Debug, "Consumer is not allocated any partitions")] public static partial void NoPartitionsAllocated(ILogger logger); - + [LoggerMessage(LogLevel.Debug, "Offset to consume from is: {Offset} on partition: {ChannelName} for topic: {Topic}")] public static partial void OffsetToConsumeFrom(ILogger logger, string offset, string channelName, string topic); - + [LoggerMessage(LogLevel.Debug, "Kafka error logging offsets: {ErrorMessage}")] public static partial void KafkaErrorLoggingOffsets(ILogger logger, string errorMessage); - + [LoggerMessage(LogLevel.Information, "Commiting offsets: {NewLine} {Offset}")] public static partial void CommittingOffsets(ILogger logger, string newLine, string offset); - + [LoggerMessage(LogLevel.Warning, "KafkaMessageConsumer: Error Committing Offsets: {ErrorMessage}")] public static partial void ErrorCommittingOffsetsAsWarning(ILogger logger, string errorMessage); [LoggerMessage(LogLevel.Debug, "Error Committing Offsets: {ErrorMessage}")] public static partial void ErrorCommittingOffsetsAsDebug(ILogger logger, string errorMessage); - + [LoggerMessage(LogLevel.Error, "Error Committing Offsets During Partition Revoke: {Message} Code: {ErrorCode}, Reason: {ErrorMessage}, Fatal: {FatalError}")] public static partial void ErrorCommittingOffsetsDuringPartitionRevoke(ILogger logger, string message, ErrorCode errorCode, string errorMessage, bool fatalError); - + [LoggerMessage(LogLevel.Debug, "Saving revoked partition offsets: {OffsetCount}")] public static partial void SavingRevokedPartitionOffsets(ILogger logger, int offsetCount); - + [LoggerMessage(LogLevel.Debug, "Saving revoked partition offset: {Offset} on partition: {Partition} for topic: {Topic}")] public static partial void SavingRevokedPartitionOffset(ILogger logger, string offset, string partition, string topic); - + [LoggerMessage(LogLevel.Information, "Sweeping offsets: {NewLine} {Offset}")] public static partial void SweepingOffsets(ILogger logger, string newLine, string offset); - + [LoggerMessage(LogLevel.Information, "Skipped committing offsets, as another commit or sweep was running")] public static partial void SkippedCommittingOffsets(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Skipped sweeping offsets, as another commit or sweep was running")] public static partial void SkippedSweepingOffsets(ILogger logger); @@ -1344,7 +1357,7 @@ public static void KafkaError(ILogger logger, LogLevel logLevel, ErrorCode error [LoggerMessage(LogLevel.Warning, "Skipped committing offsets before close, timed out waiting for in-flight commit to complete")] public static partial void SkippedCommittingOffsetsBeforeClose(ILogger logger); - + [LoggerMessage(LogLevel.Warning, "Message {MessageId} rejected with reason {RejectionReason} but no channels configured for rejection")] public static partial void NoChannelsConfiguredForRejection(ILogger logger, string messageId, string rejectionReason); diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumerFactory.cs index e1fe2da4a3..ddffb519d7 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumerFactory.cs @@ -21,16 +21,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.Kafka { /// /// - /// A factory for creating a Kafka message consumer from a > + /// A factory for creating a Kafka message consumer from a > /// - + public class KafkaMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly KafkaMessagingGatewayConfiguration _configuration; + private readonly ILoggerFactory _loggerFactory; private IAmAMessageScheduler? _scheduler; /// @@ -48,13 +51,16 @@ public IAmAMessageScheduler? Scheduler /// /// The used to connect to the Broker /// The optional message scheduler for delayed requeue support + /// The used to create loggers for the consumers public KafkaMessageConsumerFactory( KafkaMessagingGatewayConfiguration configuration, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null ) { _configuration = configuration; _scheduler = scheduler; + _loggerFactory = loggerFactory; } /// @@ -64,10 +70,10 @@ public KafkaMessageConsumerFactory( /// A consumer that can be used to read from the stream public IAmAMessageConsumerSync Create(Subscription subscription) { - KafkaSubscription? kafkaSubscription = subscription as KafkaSubscription; + KafkaSubscription? kafkaSubscription = subscription as KafkaSubscription; if (kafkaSubscription == null) throw new ConfigurationException("We expect a KafkaSubscription or KafkaSubscription as a parameter"); - + // Extract DLQ and invalid message routing keys if subscription supports them RoutingKey? deadLetterRoutingKey = null; RoutingKey? invalidMessageRoutingKey = null; @@ -85,7 +91,7 @@ public IAmAMessageConsumerSync Create(Subscription subscription) #pragma warning disable CS0618 return new KafkaMessageConsumer( configuration: _configuration, - routingKey:kafkaSubscription.RoutingKey, //topic + routingKey: kafkaSubscription.RoutingKey, //topic groupId: kafkaSubscription.GroupId, offsetDefault: kafkaSubscription.OffsetDefault, sessionTimeout: kafkaSubscription.SessionTimeout, @@ -105,7 +111,8 @@ public IAmAMessageConsumerSync Create(Subscription subscription) invalidMessageRoutingKey: invalidMessageRoutingKey, timeProvider: kafkaSubscription.TimeProvider, scheduler: _scheduler, - groupProtocol: kafkaSubscription.GroupProtocol); + groupProtocol: kafkaSubscription.GroupProtocol, + loggerFactory: _loggerFactory); #pragma warning restore CS0618 } diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageCreator.cs index 949ffbea7d..6ee7f44984 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageCreator.cs @@ -31,7 +31,6 @@ THE SOFTWARE. */ using Confluent.Kafka; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.MessagingGateway.Kafka @@ -45,7 +44,12 @@ namespace Paramore.Brighter.MessagingGateway.Kafka /// public partial class KafkaMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + + public KafkaMessageCreator(ILogger logger) + { + _logger = logger; + } private sealed class MessageHeaderResults { @@ -65,24 +69,24 @@ private sealed class MessageHeaderResults public required HeaderResult Source { get; set; } public required HeaderResult TraceParent { get; set; } public required HeaderResult TraceState { get; set; } - public required HeaderResult Baggage { get; set; } + public required HeaderResult Baggage { get; set; } } public Message CreateMessage(ConsumeResult consumeResult) { try { - var headerResults = KafkaMessageCreator.ReadAllHeaders(consumeResult); + var headerResults = ReadAllHeaders(consumeResult); return CreateMessageFromHeaders(headerResults, consumeResult); } catch (Exception e) { - Log.FailedToCreateMessageFromKafkaOffset(s_logger, e); + Log.FailedToCreateMessageFromKafkaOffset(_logger, e); return Message.FailureMessage(RoutingKey.Empty, Id.Empty); } } - private static MessageHeaderResults ReadAllHeaders(ConsumeResult consumeResult) + private MessageHeaderResults ReadAllHeaders(ConsumeResult consumeResult) { var result = new MessageHeaderResults { @@ -118,11 +122,11 @@ private Message CreateMessageFromHeaders(MessageHeaderResults headers, ConsumeRe var message = SuccessMessage(headers, consumeResult); AddPartitionOffset(message, consumeResult); AddCustomHeaders(message, consumeResult.Message.Headers); - + return message; } - private static Message SuccessMessage(MessageHeaderResults headers, ConsumeResult consumeResult) + private Message SuccessMessage(MessageHeaderResults headers, ConsumeResult consumeResult) { var messageHeader = new MessageHeader( messageId: (headers.MessageId.Success ? headers.MessageId.Result : Id.Empty)!, @@ -158,12 +162,12 @@ private void AddCustomHeaders(Message message, Headers headers) headers.Each(header => ReadBagEntry(header, message)); } - private static HeaderResult ReadContentType(Headers headers) + private HeaderResult ReadContentType(Headers headers) { var contentType = ReadHeader(headers, HeaderNames.CLOUD_EVENTS_DATA_CONTENT_TYPE, true); - + if (contentType.Success && !string.IsNullOrEmpty(contentType.Result)) - return new HeaderResult( new ContentType(contentType.Result!), true); + return new HeaderResult(new ContentType(contentType.Result!), true); contentType = ReadHeader(headers, HeaderNames.CONTENT_TYPE); if (contentType.Success && !string.IsNullOrEmpty(contentType.Result)) @@ -172,14 +176,14 @@ private void AddCustomHeaders(Message message, Headers headers) return new HeaderResult(null, false); } - private static HeaderResult ReadCorrelationId(Headers headers) + private HeaderResult ReadCorrelationId(Headers headers) { return ReadHeader(headers, HeaderNames.CORRELATION_ID) .Map(correlationId => { if (string.IsNullOrEmpty(correlationId)) { - Log.NoCorrelationIdFoundInMessage(s_logger); + Log.NoCorrelationIdFoundInMessage(_logger); return new HeaderResult(Id.Empty, true); } @@ -187,14 +191,14 @@ private void AddCustomHeaders(Message message, Headers headers) }); } - private static HeaderResult ReadDelay(Headers headers) + private HeaderResult ReadDelay(Headers headers) { return ReadHeader(headers, HeaderNames.DELAYED_MILLISECONDS) .Map(s => { if (string.IsNullOrEmpty(s)) { - Log.NoDelayMillisecondsFoundInMessage(s_logger); + Log.NoDelayMillisecondsFoundInMessage(_logger); return new HeaderResult(TimeSpan.Zero, true); } @@ -203,19 +207,19 @@ private static HeaderResult ReadDelay(Headers headers) return new HeaderResult(TimeSpan.FromMilliseconds(delayMilliseconds), true); } - Log.CouldNotParseMessageDelayMilliseconds(s_logger, s!); + Log.CouldNotParseMessageDelayMilliseconds(_logger, s!); return new HeaderResult(TimeSpan.Zero, false); }); } - private static HeaderResult ReadHandledCount(Headers headers) + private HeaderResult ReadHandledCount(Headers headers) { return ReadHeader(headers, HeaderNames.HANDLED_COUNT) .Map(s => { if (string.IsNullOrEmpty(s)) { - Log.NoHandledCountFoundInMessage(s_logger); + Log.NoHandledCountFoundInMessage(_logger); return new HeaderResult(0, true); } @@ -224,19 +228,19 @@ private static HeaderResult ReadHandledCount(Headers headers) return new HeaderResult(handledCount, true); } - Log.CouldNotParseMessageHandledCount(s_logger, s!); + Log.CouldNotParseMessageHandledCount(_logger, s!); return new HeaderResult(0, false); }); } - private static HeaderResult ReadReplyTo(Headers headers) + private HeaderResult ReadReplyTo(Headers headers) { return ReadHeader(headers, HeaderNames.REPLY_TO) .Map(s => { if (string.IsNullOrEmpty(s)) { - Log.NoReplyToFoundInMessage(s_logger); + Log.NoReplyToFoundInMessage(_logger); return new HeaderResult(RoutingKey.Empty, true); } @@ -244,7 +248,7 @@ private static HeaderResult ReadHandledCount(Headers headers) }); } - private static HeaderResult ReadTimeStamp(Headers headers) + private HeaderResult ReadTimeStamp(Headers headers) { if (headers.TryGetLastBytesIgnoreCase(HeaderNames.TIMESTAMP, out var lastHeader)) { @@ -270,7 +274,7 @@ private static HeaderResult ReadTimeStamp(Headers headers) : new HeaderResult(DateTimeOffset.UtcNow, true)); } - private static HeaderResult ReadMessageType(Headers headers) + private HeaderResult ReadMessageType(Headers headers) { return ReadHeader(headers, HeaderNames.MESSAGE_TYPE) .Map(s => @@ -285,16 +289,16 @@ private static HeaderResult ReadMessageType(Headers headers) }); } - private static HeaderResult ReadTopic(string topic) + private HeaderResult ReadTopic(string topic) { return new HeaderResult(new RoutingKey(topic), true); } - private static HeaderResult ReadMessageId(Headers headers) + private HeaderResult ReadMessageId(Headers headers) { var id = ReadHeader(headers, HeaderNames.CLOUD_EVENTS_ID, true) .Map(messageId => new HeaderResult(string.IsNullOrEmpty(messageId) ? Id.Random() : Id.Create(messageId), true)); - + if (id.Success) { return id; @@ -306,7 +310,7 @@ private static HeaderResult ReadTopic(string topic) { if (string.IsNullOrEmpty(messageId)) { - Log.NoMessageIdFoundInMessage(s_logger, newMessageId); + Log.NoMessageIdFoundInMessage(_logger, newMessageId); return new HeaderResult(Id.Random(), true); } @@ -314,7 +318,7 @@ private static HeaderResult ReadTopic(string topic) }); } - private static HeaderResult ReadPartitionKey(Message message) + private HeaderResult ReadPartitionKey(Message message) { var pKey = ReadHeader(message.Headers, HeaderNames.PARTITIONKEY) @@ -322,7 +326,7 @@ private static HeaderResult ReadTopic(string topic) { if (string.IsNullOrEmpty(s)) { - Log.NoPartitionKeyFoundInMessage(s_logger); + Log.NoPartitionKeyFoundInMessage(_logger); return new HeaderResult(PartitionKey.Empty, false); } @@ -334,40 +338,40 @@ private static HeaderResult ReadTopic(string topic) { return pKey; } - + //if we have no partition key header, but we have a message key, we assume it is not a Brighter message, //and we use the message key as the partition key if (!string.IsNullOrEmpty(message.Key)) { return new HeaderResult(message.Key, true); } - + //if we have no partition key header, and no message key, we return empty - return new HeaderResult(PartitionKey.Empty, false); + return new HeaderResult(PartitionKey.Empty, false); } - private static HeaderResult ReadSubject(Headers headers) + private HeaderResult ReadSubject(Headers headers) => ReadHeader(headers, HeaderNames.CLOUD_EVENTS_SUBJECT); - private static HeaderResult ReadType(Headers headers) + private HeaderResult ReadType(Headers headers) => ReadHeader(headers, HeaderNames.CLOUD_EVENTS_TYPE) - .Map(x =>x is not null + .Map(x => x is not null ? new HeaderResult(new CloudEventsType(x), true) : new HeaderResult(CloudEventsType.Empty, true)); - private static HeaderResult ReadDataSchema(Headers headers) => + private HeaderResult ReadDataSchema(Headers headers) => ReadHeader(headers, HeaderNames.CLOUD_EVENTS_DATA_SCHEMA, true) .Map(x => Uri.TryCreate(x, UriKind.RelativeOrAbsolute, out var dataSchema) ? new HeaderResult(dataSchema, true) : new HeaderResult(null, false)); - private static HeaderResult ReadSource(Headers headers) => + private HeaderResult ReadSource(Headers headers) => ReadHeader(headers, HeaderNames.CLOUD_EVENTS_SOURCE) .Map(x => Uri.TryCreate(x, UriKind.RelativeOrAbsolute, out var dataSchema) ? new HeaderResult(dataSchema, true) : new HeaderResult(new Uri("http://goparamore.io"), true)); - private static HeaderResult ReadTraceParent(Headers headers) + private HeaderResult ReadTraceParent(Headers headers) { return ReadHeader(headers, HeaderNames.CLOUD_EVENTS_TRACE_PARENT) .Map(s => @@ -381,7 +385,7 @@ private static HeaderResult ReadTopic(string topic) }); } - private static HeaderResult ReadTraceState(Headers headers) + private HeaderResult ReadTraceState(Headers headers) { return ReadHeader(headers, HeaderNames.CLOUD_EVENTS_TRACE_STATE) .Map(s => @@ -395,7 +399,7 @@ private static HeaderResult ReadTopic(string topic) }); } - private static HeaderResult ReadBaggage(Headers headers) + private HeaderResult ReadBaggage(Headers headers) { return ReadHeader(headers, HeaderNames.W3C_BAGGAGE) .Map(s => @@ -411,7 +415,7 @@ private static HeaderResult ReadTopic(string topic) }); } - private static HeaderResult ReadHeader(Headers headers, string key, bool dieOnMissing = false) + private HeaderResult ReadHeader(Headers headers, string key, bool dieOnMissing = false) { if (headers.TryGetLastBytesIgnoreCase(key, out byte[]? lastHeader)) { @@ -423,7 +427,7 @@ private static HeaderResult ReadTopic(string topic) catch (Exception e) { var firstTwentyBytes = BitConverter.ToString(lastHeader!.Take(20).ToArray()); - Log.FailedToReadTheValueOfHeader(s_logger, e, key, firstTwentyBytes); + Log.FailedToReadTheValueOfHeader(_logger, e, key, firstTwentyBytes); return new HeaderResult(null, false); } } diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducer.cs index 8f5c715f9b..5cce0fe6ac 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducer.cs @@ -55,12 +55,12 @@ event Func ISupportPublishConfirmationAsync.OnM add => _onMessagePublishedAsync += value; remove => _onMessagePublishedAsync -= value; } - + /// /// The publication configuration for this producer /// public Publication Publication { get; set; } - + /// /// The OTel Span we are writing Producer events too /// @@ -82,13 +82,15 @@ event Func ISupportPublishConfirmationAsync.OnM private readonly InFlightCallbackTracker _confirmationCallbacks = new(); public KafkaMessageProducer( - KafkaMessagingGatewayConfiguration configuration, + KafkaMessagingGatewayConfiguration configuration, KafkaPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) + : base(loggerFactory) { if (publication is null) throw new ArgumentNullException(nameof(publication)); - + if (string.IsNullOrEmpty(publication.Topic!)) throw new ConfigurationException("Topic is required for a publication"); @@ -146,7 +148,7 @@ public KafkaMessageProducer( _headerBuilder = publication.MessageHeaderBuilder; _instrumentation = instrumentation; } - + /// /// Dispose of the producer /// @@ -155,8 +157,8 @@ public void Dispose() Dispose(true); GC.SuppressFinalize(this); } - - + + /// /// Dispose of the producer /// @@ -178,7 +180,7 @@ public void ConfigHook(Action configHook) { configHook(_producerConfig); } - + /// /// Flushes the producer to ensure all messages in the internal buffer have been sent /// @@ -196,7 +198,10 @@ public void Init() _producer = new ProducerBuilder(_producerConfig) .SetErrorHandler((_, error) => HandleError(error)) .Build(); - _publisher = new KafkaMessagePublisher(_producer, _headerBuilder); + _publisher = new KafkaMessagePublisher( + _producer, + _headerBuilder, + _loggerFactory.CreateLogger()); EnsureTopic(); } @@ -216,11 +221,11 @@ public void HandleError(Error error) // Log against the error we actually received, independent of the latch, so a non-fatal error // that arrives after a fatal one is still logged as non-fatal. if (error.IsFatal) - Log.FatalProducerError(s_logger, error.Code, error.Reason, true); + Log.FatalProducerError(_logger, error.Code, error.Reason, true); else - Log.NonFatalProducerError(s_logger, error.Code, error.Reason, false); + Log.NonFatalProducerError(_logger, error.Code, error.Reason, false); } - + /// /// Sends the specified message. /// @@ -246,7 +251,7 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken { await SendWithDelayAsync(message, TimeSpan.Zero, cancellationToken); } - + /// /// Sends the message with the given delay /// @@ -291,29 +296,29 @@ public void SendWithDelay(Message message, TimeSpan? delay = null) //confirmation can be linked back to the original publish even on the synthetic path. var publishContext = Activity.Current?.Context; BrighterTracer.WriteProducerEvent(Span, MessagingSystem.Kafka, message, _instrumentation); - Log.SendingMessageToKafka(s_logger, _producerConfig.BootstrapServers, message.Header.Topic.Value, message.Body.Value); + Log.SendingMessageToKafka(_logger, _producerConfig.BootstrapServers, message.Header.Topic.Value, message.Body.Value); _publisher.PublishMessage(message, report => PublishResults(report.Status, report.Headers, message.Header.Topic, publishContext)); } catch (ProduceException pe) { - Log.ErrorSendingMessageToKafka(s_logger, pe, _producerConfig.BootstrapServers, pe.Error.Reason); + Log.ErrorSendingMessageToKafka(_logger, pe, _producerConfig.BootstrapServers, pe.Error.Reason); throw new ChannelFailureException("Error talking to the broker, see inner exception for details", pe); } catch (InvalidOperationException ioe) { - Log.ErrorSendingMessageToKafka(s_logger, ioe, _producerConfig.BootstrapServers, ioe.Message); + Log.ErrorSendingMessageToKafka(_logger, ioe, _producerConfig.BootstrapServers, ioe.Message); throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ioe); } catch (ArgumentException ae) { - Log.ErrorSendingMessageToKafka(s_logger, ae, _producerConfig.BootstrapServers, ae.Message); + Log.ErrorSendingMessageToKafka(_logger, ae, _producerConfig.BootstrapServers, ae.Message); throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ae); } catch (KafkaException kafkaException) { - Log.KafkaExceptionError(s_logger, kafkaException, Topic?.Value ?? RoutingKey.Empty.Value); + Log.KafkaExceptionError(_logger, kafkaException, Topic?.Value ?? RoutingKey.Empty.Value); if (kafkaException.Error.IsFatal) //this can't be recovered and requires a new producer throw; @@ -333,12 +338,12 @@ public void SendWithDelay(Message message, TimeSpan? delay = null) /// Cancels the send operation public async Task SendWithDelayAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken = default) { - if (message is null) - throw new ArgumentNullException(nameof(message)); + if (message is null) + throw new ArgumentNullException(nameof(message)); - delay ??= TimeSpan.Zero; - if (delay != TimeSpan.Zero) - { + delay ??= TimeSpan.Zero; + if (delay != TimeSpan.Zero) + { if (Scheduler is IAmAMessageSchedulerAsync async) { await async.ScheduleAsync(message, delay.Value, cancellationToken); @@ -353,41 +358,40 @@ public async Task SendWithDelayAsync(Message message, TimeSpan? delay, Cancellat throw new ConfigurationException( $"KafkaMessageProducer: delay of {delay} was requested but no scheduler is configured; configure a scheduler via MessageSchedulerFactory."); - } - - if (_publisher is null) - throw new InvalidOperationException("The publisher cannot be null"); - - if (_hasFatalProducerError) - throw new ChannelFailureException("Producer is in unrecoverable state"); - - try - { - //Capture the publish span context synchronously, before any closure runs, so the - //confirmation can be linked back to the original publish even on the synthetic path. - var publishContext = Activity.Current?.Context; - BrighterTracer.WriteProducerEvent(Span, MessagingSystem.Kafka, message, _instrumentation); - Log.SendingMessageToKafka(s_logger, _producerConfig.BootstrapServers, message.Header.Topic.Value, message.Body.Value); - await _publisher.PublishMessageAsync(message, result => PublishResults(result.Status, result.Headers, message.Header.Topic, publishContext), cancellationToken); - - } - catch (ProduceException pe) - { - Log.ErrorSendingMessageToKafka(s_logger, pe, _producerConfig.BootstrapServers, pe.Error.Reason); - throw new ChannelFailureException("Error talking to the broker, see inner exception for details", pe); - } - catch (InvalidOperationException ioe) - { - Log.ErrorSendingMessageToKafka(s_logger, ioe, _producerConfig.BootstrapServers, ioe.Message); - throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ioe); - - } - catch (ArgumentException ae) - { - Log.ErrorSendingMessageToKafka(s_logger, ae, _producerConfig.BootstrapServers, ae.Message); - throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ae); - - } + } + + if (_publisher is null) + throw new InvalidOperationException("The publisher cannot be null"); + + if (_hasFatalProducerError) + throw new ChannelFailureException("Producer is in unrecoverable state"); + + try + { + //Capture the publish span context synchronously, before any closure runs, so the + //confirmation can be linked back to the original publish even on the synthetic path. + var publishContext = Activity.Current?.Context; + BrighterTracer.WriteProducerEvent(Span, MessagingSystem.Kafka, message, _instrumentation); + Log.SendingMessageToKafka(_logger, _producerConfig.BootstrapServers, message.Header.Topic.Value, message.Body.Value); + await _publisher.PublishMessageAsync(message, result => PublishResults(result.Status, result.Headers, message.Header.Topic, publishContext), cancellationToken); + } + catch (ProduceException pe) + { + Log.ErrorSendingMessageToKafka(_logger, pe, _producerConfig.BootstrapServers, pe.Error.Reason); + throw new ChannelFailureException("Error talking to the broker, see inner exception for details", pe); + } + catch (InvalidOperationException ioe) + { + Log.ErrorSendingMessageToKafka(_logger, ioe, _producerConfig.BootstrapServers, ioe.Message); + throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ioe); + + } + catch (ArgumentException ae) + { + Log.ErrorSendingMessageToKafka(_logger, ae, _producerConfig.BootstrapServers, ae.Message); + throw new ChannelFailureException("Error talking to the broker, see inner exception for details", ae); + + } } private void Dispose(bool disposing) @@ -401,7 +405,7 @@ private void Dispose(bool disposing) _producer?.Dispose(); } } - + private void PublishResults(PersistenceStatus status, Headers headers, RoutingKey topic, ActivityContext? publishContext) { if (status == PersistenceStatus.Persisted) @@ -423,7 +427,7 @@ private void PublishResults(PersistenceStatus status, Headers headers, RoutingKe // degraded state is diagnosable: MarkDispatched(Id.Empty) matches no Outbox row, so the // message stays un-dispatched and the Sweeper re-delivers it rather than being marked sent. if (Id.IsNullOrEmpty(persistedId)) - Log.PersistedReportMissingId(s_logger, topic.Value); + Log.PersistedReportMissingId(_logger, topic.Value); RaisePublishConfirmation(new PublishConfirmationResult(true, persistedId, topic, publishContext)); return; @@ -462,7 +466,7 @@ private void RaisePublishConfirmation(PublishConfirmationResult result) } catch (Exception ex) { - Log.PublishConfirmationRaiseFault(s_logger, ex); + Log.PublishConfirmationRaiseFault(_logger, ex); } finally { @@ -474,7 +478,7 @@ private void RaisePublishConfirmation(PublishConfirmationResult result) private void WaitForConfirmationCallbacks() { if (!_confirmationCallbacks.TryWait(TimeSpan.FromMilliseconds(ConfirmationCallbacksShutdownTimeoutMs), out int stillInFlight)) - Log.FailedToAwaitConfirmationCallbacks(s_logger, stillInFlight, ConfirmationCallbacksShutdownTimeoutMs); + Log.FailedToAwaitConfirmationCallbacks(_logger, stillInFlight, ConfirmationCallbacksShutdownTimeoutMs); } private static partial class Log @@ -496,7 +500,7 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Kafka reported topic {Topic} as persisted but the delivery report carried no message id; confirmation degraded to an empty id so the message stays un-dispatched for Sweeper retry")] public static partial void PersistedReportMissingId(ILogger logger, string topic); - + [LoggerMessage(LogLevel.Error, "KafkaMessageProducer: There was an error sending to topic {Topic})")] public static partial void KafkaExceptionError(ILogger logger, Exception exception, string topic); diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducerFactory.cs index 692afe6fca..3464ae1b1f 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducerFactory.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading.Tasks; using Confluent.Kafka; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Kafka { @@ -36,22 +37,26 @@ public class KafkaMessageProducerFactory : IAmAMessageProducerFactory { private readonly KafkaMessagingGatewayConfiguration _globalConfiguration; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; private Action? _configHook; /// /// This constructs a which can be used to create a dictionary of /// instances indexed by topic name. - /// It takes a dependency on a to connect to the broker, and a collection of + /// It takes a dependency on a to connect to the broker, and a collection of /// instances that determine how we publish to Kafka and the parameters of any topics if required. /// /// Configures how we connect to the broker /// The list of topics that we want to publish to + /// The used to create loggers for the producers public KafkaMessageProducerFactory( - KafkaMessagingGatewayConfiguration globalConfiguration, - IEnumerable publications) + KafkaMessagingGatewayConfiguration globalConfiguration, + IEnumerable publications, + ILoggerFactory loggerFactory) { _globalConfiguration = globalConfiguration; _publications = publications; + _loggerFactory = loggerFactory; _configHook = null; } @@ -59,13 +64,14 @@ public KafkaMessageProducerFactory( /// Creates a message producer registry. /// /// A registry of middleware clients by topic, for sending messages to the middleware - public Dictionary Create() + public Dictionary Create() { var publicationsByTopic = new Dictionary(); foreach (var publication in _publications) { - if (publication.Topic is null) continue; - var producer = new KafkaMessageProducer(_globalConfiguration, publication); + if (publication.Topic is null) + continue; + var producer = new KafkaMessageProducer(_globalConfiguration, publication, loggerFactory: _loggerFactory); if (_configHook != null) producer.ConfigHook(_configHook); producer.Init(); @@ -84,7 +90,7 @@ public Dictionary Create() /// A registry of middleware clients by topic, for sending messages to the middleware public Task> CreateAsync() { - return Task.FromResult(Create()); + return Task.FromResult(Create()); } /// diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagePublisher.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagePublisher.cs index 40fafa24f3..66ddaf4ea9 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagePublisher.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagePublisher.cs @@ -27,20 +27,18 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Confluent.Kafka; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.Kafka { internal sealed partial class KafkaMessagePublisher( IProducer producer, - IKafkaMessageHeaderBuilder headerBuilder) + IKafkaMessageHeaderBuilder headerBuilder, + ILogger logger) { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - public void PublishMessage(Message message, Action> deliveryReport) { var kafkaMessage = BuildMessage(message); - + producer.Produce(message.Header.Topic, kafkaMessage, deliveryReport); } @@ -49,7 +47,7 @@ public async Task PublishMessageAsync(Message message, Action deliveryResult = new(); deliveryResult.Status = PersistenceStatus.NotPersisted; deliveryResult.Message = new Message(); diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagingGateway.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagingGateway.cs index 47ceffa079..efb0131e86 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagingGateway.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagingGateway.cs @@ -29,7 +29,6 @@ THE SOFTWARE. */ using Confluent.Kafka; using Confluent.Kafka.Admin; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.Kafka @@ -41,7 +40,8 @@ namespace Paramore.Brighter.MessagingGateway.Kafka /// public partial class KafkaMessagingGateway { - protected static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + protected readonly ILogger _logger; + protected readonly ILoggerFactory _loggerFactory; protected ClientConfig? ClientConfig; protected OnMissingChannel MakeChannels; protected RoutingKey? Topic; @@ -49,6 +49,16 @@ public partial class KafkaMessagingGateway protected short ReplicationFactor; protected TimeSpan TopicFindTimeout; + /// + /// Initializes a new instance of the class. + /// + /// The used to create loggers for the gateway and any producers it creates. + protected KafkaMessagingGateway(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); + } + /// /// Ensure that the topic exists, behaviour based on the MakeChannels flag of the publication /// Sync over async, but alright as we in topic creation @@ -76,8 +86,9 @@ protected void EnsureTopic() private async Task MakeTopic() { - if (RoutingKey.IsNullOrEmpty(Topic)) throw new InvalidOperationException("Topic cannot be null"); - + if (RoutingKey.IsNullOrEmpty(Topic)) + throw new InvalidOperationException("Topic cannot be null"); + using var adminClient = new AdminClientBuilder(ClientConfig).Build(); try { @@ -99,14 +110,15 @@ await adminClient.CreateTopicsAsync(new List $"An error occured creating topic {Topic.Value}: {e.Results[0].Error.Reason}"); } - Log.TopicAlreadyExists(s_logger, Topic.Value); + Log.TopicAlreadyExists(_logger, Topic.Value); } } private bool FindTopic() { - if (RoutingKey.IsNullOrEmpty(Topic)) throw new InvalidOperationException("Topic cannot be null"); - + if (RoutingKey.IsNullOrEmpty(Topic)) + throw new InvalidOperationException("Topic cannot be null"); + using var adminClient = new AdminClientBuilder(ClientConfig).Build(); try { @@ -118,7 +130,7 @@ private bool FindTopic() if (matchingTopics.Length > 0) { var matchingTopic = matchingTopics[0]; - + //was it found? found = matchingTopic.Error != null && matchingTopic.Error.Code != ErrorCode.UnknownTopicOrPart; if (found) @@ -153,14 +165,14 @@ private bool FindTopic() $"topic is misconfigured => ReplicationFactor should be {ReplicationFactor} but is {matchingTopic.Partitions[0].Replicas.Length};"; } - Log.TopicMisconfiguredWarning(s_logger, error); + Log.TopicMisconfiguredWarning(_logger, error); } } } if (found) - Log.TopicExists(s_logger, Topic.Value); - + Log.TopicExists(_logger, Topic.Value); + return found; } catch (Exception e) @@ -176,7 +188,7 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "{TopicMisconfiguredError}")] public static partial void TopicMisconfiguredWarning(ILogger logger, string topicMisconfiguredError); - + [LoggerMessage(LogLevel.Information, "Topic {Topic} exists")] public static partial void TopicExists(ILogger logger, string topic); } diff --git a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaProducerRegistryFactory.cs index 91e799bf51..8ffd2014a7 100644 --- a/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Kafka/KafkaProducerRegistryFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Confluent.Kafka; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Kafka { @@ -37,6 +38,7 @@ public class KafkaProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly KafkaMessagingGatewayConfiguration _globalConfiguration; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; private Action? _configHook; /// @@ -46,15 +48,18 @@ public class KafkaProducerRegistryFactory : IAmAProducerRegistryFactory /// /// Configures how we connect to the broker /// The list of topics that we want to publish to + /// The used to create loggers for the producers public KafkaProducerRegistryFactory( - KafkaMessagingGatewayConfiguration globalConfiguration, - IEnumerable publications) + KafkaMessagingGatewayConfiguration globalConfiguration, + IEnumerable publications, + ILoggerFactory loggerFactory) { _globalConfiguration = globalConfiguration; _publications = publications; + _loggerFactory = loggerFactory; _configHook = null; } - + /// /// Create a producer registry from the and instances supplied /// to the constructor @@ -62,7 +67,7 @@ public KafkaProducerRegistryFactory( /// An that represents a collection of Kafka Message Producers public IAmAProducerRegistry Create() { - var producerFactory = new KafkaMessageProducerFactory(_globalConfiguration, _publications); + var producerFactory = new KafkaMessageProducerFactory(_globalConfiguration, _publications, _loggerFactory); producerFactory.SetConfigHook(_configHook); return new ProducerRegistry(producerFactory.Create()); @@ -75,7 +80,7 @@ public IAmAProducerRegistry Create() /// An that represents a collection of Kafka Message Producers public Task CreateAsync(CancellationToken ct = default) { - return Task.FromResult(Create()); + return Task.FromResult(Create()); } /// diff --git a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs index 45adfb7cfe..45a5d9d0ab 100644 --- a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs @@ -10,7 +10,6 @@ using MQTTnet.Packets; using MQTTnet.Protocol; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.MQTT @@ -25,7 +24,8 @@ public partial class MqttMessageConsumer : IAmAMessageConsumerSync, IAmAMessageC private readonly string _topic; private readonly MqttMessagingGatewayConsumerConfiguration _configuration; private readonly ConcurrentQueue _messageQueue = new(); - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly Message _noopMessage = new(); private readonly IMqttClient _mqttClient; private readonly MqttClientOptions _mqttClientOptions; @@ -51,6 +51,7 @@ public partial class MqttMessageConsumer : IAmAMessageConsumerSync, IAmAMessageC /// /// The routing key for the dead letter queue, if using Brighter-managed DLQ. /// The routing key for the invalid message queue, if using Brighter-managed invalid message handling. + /// The used to create loggers for this consumer and the producers it creates. /// /// Thrown when the is null. /// @@ -63,10 +64,13 @@ public partial class MqttMessageConsumer : IAmAMessageConsumerSync, IAmAMessageC /// public MqttMessageConsumer( MqttMessagingGatewayConsumerConfiguration configuration, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null) { + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); _configuration = configuration; _scheduler = scheduler; _deadLetterRoutingKey = deadLetterRoutingKey; @@ -106,7 +110,7 @@ public MqttMessageConsumer( _mqttClient.ApplicationMessageReceivedAsync += e => { - Log.MqttMessageConsumerReceivedMessage(s_logger, configuration.TopicPrefix); + Log.MqttMessageConsumerReceivedMessage(_logger, configuration.TopicPrefix); var message = JsonSerializer.Deserialize(e.ApplicationMessage.PayloadSegment.ToArray(), JsonSerialisationOptions.Options); _messageQueue.Enqueue(message!); @@ -166,7 +170,8 @@ public void Dispose() public async ValueTask DisposeAsync() { - if (_requeueProducer != null) await _requeueProducer.DisposeAsync(); + if (_requeueProducer != null) + await _requeueProducer.DisposeAsync(); // IMqttClient only implements IDisposable, not IAsyncDisposable (MQTTnet 4.3) _mqttClient.Dispose(); } @@ -229,19 +234,20 @@ public Task ReceiveAsync(TimeSpan? timeOut = null, CancellationToken public bool Reject(Message message, MessageRejectionReason? reason = null) { var (producer, routingKey) = ResolveRejectionProducer(message, reason); - if (producer == null || routingKey == null) return true; + if (producer == null || routingKey == null) + return true; try { producer.Send(message); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, routingKey.Value); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, routingKey.Value); } catch (Exception ex) { // DLQ send failed — MQTT fire-and-forget model means the source message // only exists in memory and cannot be requeued. Return true to prevent // requeue loops (per ADR 0034). - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, routingKey.Value); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, routingKey.Value); return true; } @@ -258,19 +264,20 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) public async Task RejectAsync(Message message, MessageRejectionReason? reason = null, CancellationToken cancellationToken = default) { var (producer, routingKey) = ResolveRejectionProducer(message, reason); - if (producer == null || routingKey == null) return true; + if (producer == null || routingKey == null) + return true; try { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, routingKey.Value); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, routingKey.Value); } catch (Exception ex) { // DLQ send failed — MQTT fire-and-forget model means the source message // only exists in memory and cannot be requeued. Return true to prevent // requeue loops (per ADR 0034). - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, routingKey.Value); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, routingKey.Value); return true; } @@ -281,7 +288,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea { if (_deadLetterProducer == null && _invalidMessageProducer == null) { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value); return (null, null); } @@ -290,11 +297,11 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea var (routingKey, hasProducer, isFallingBackToDlq) = DetermineRejectionRoute(reason); if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (!hasProducer) { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value); return (null, null); } @@ -378,7 +385,7 @@ private void EnsureRequeueProducer() CleanSession = _configuration.CleanSession, Username = _configuration.Username, Password = _configuration.Password - }); + }, _loggerFactory); return new MqttMessageProducer(publisher, new Publication()) { Scheduler = _scheduler @@ -392,7 +399,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea message.Header.Bag["rejectionTimestamp"] = DateTimeOffset.UtcNow.ToString("o"); message.Header.Bag["originalMessageType"] = message.Header.MessageType.ToString(); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -417,7 +425,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea private MqttMessageProducer? CreateDeadLetterProducer() { - if (_deadLetterRoutingKey == null) return null; + if (_deadLetterRoutingKey == null) + return null; try { @@ -431,19 +440,20 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea ClientID = string.IsNullOrEmpty(_configuration.ClientID) ? null : $"{_configuration.ClientID}-dlq", TopicPrefix = _deadLetterRoutingKey.Value }; - var publisher = new MqttMessagePublisher(config); + var publisher = new MqttMessagePublisher(config, _loggerFactory); return new MqttMessageProducer(publisher, new Publication { Topic = _deadLetterRoutingKey }); } catch (Exception ex) { - Log.ErrorCreatingDlqProducer(s_logger, ex, _deadLetterRoutingKey.Value); + Log.ErrorCreatingDlqProducer(_logger, ex, _deadLetterRoutingKey.Value); return null; } } private MqttMessageProducer? CreateInvalidMessageProducer() { - if (_invalidMessageRoutingKey == null) return null; + if (_invalidMessageRoutingKey == null) + return null; try { @@ -457,12 +467,12 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea ClientID = string.IsNullOrEmpty(_configuration.ClientID) ? null : $"{_configuration.ClientID}-invalid", TopicPrefix = _invalidMessageRoutingKey.Value }; - var publisher = new MqttMessagePublisher(config); + var publisher = new MqttMessagePublisher(config, _loggerFactory); return new MqttMessageProducer(publisher, new Publication { Topic = _invalidMessageRoutingKey }); } catch (Exception ex) { - Log.ErrorCreatingInvalidMessageProducer(s_logger, ex, _invalidMessageRoutingKey.Value); + Log.ErrorCreatingInvalidMessageProducer(_logger, ex, _invalidMessageRoutingKey.Value); return null; } } @@ -474,16 +484,16 @@ private async Task Connect(int connectionAttempts) try { await _mqttClient.ConnectAsync(_mqttClientOptions, CancellationToken.None); - Log.MqttConsumerClientConnected(s_logger); + Log.MqttConsumerClientConnected(_logger); await _mqttClient.SubscribeAsync(new MqttTopicFilter { Topic = _topic, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce }); - Log.SubscribedToTopic(s_logger, _topic); + Log.SubscribedToTopic(_logger, _topic); return; } catch (Exception ex) { - Log.UnableToConnectMqttConsumerClient(s_logger, ex); + Log.UnableToConnectMqttConsumerClient(_logger, ex); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessagePublisher.cs b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessagePublisher.cs index 00013ac5ea..516f31c43a 100644 --- a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessagePublisher.cs +++ b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessagePublisher.cs @@ -7,7 +7,6 @@ using MQTTnet.Client; using MQTTnet.Protocol; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.MQTT @@ -17,7 +16,7 @@ namespace Paramore.Brighter.MessagingGateway.MQTT /// public partial class MqttMessagePublisher : IDisposable, IAsyncDisposable { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly MqttMessagingGatewayConfiguration _config; private readonly IMqttClient _mqttClient; private readonly MqttClientOptions _mqttClientOptions; @@ -27,8 +26,10 @@ public partial class MqttMessagePublisher : IDisposable, IAsyncDisposable /// Sync over async, but necessary as we are in the ctor /// /// The Publisher configuration. - public MqttMessagePublisher(MqttMessagingGatewayConfiguration config) + /// The used to create the logger. + public MqttMessagePublisher(MqttMessagingGatewayConfiguration config, ILoggerFactory loggerFactory) { + _logger = loggerFactory.CreateLogger(); _config = config; _mqttClient = new MqttFactory().CreateMqttClient(); @@ -113,12 +114,12 @@ private async Task ConnectAsync() try { await _mqttClient.ConnectAsync(_mqttClientOptions, CancellationToken.None); - Log.ConnectedToHost(s_logger, _config.Hostname, _config.Port); + Log.ConnectedToHost(_logger, _config.Hostname, _config.Port); return; } catch (Exception) { - Log.UnableToConnectToHost(s_logger, _config.Hostname!, _config.Port); + Log.UnableToConnectToHost(_logger, _config.Hostname!, _config.Port); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.MQTT/MqttMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.MQTT/MqttMessageConsumerFactory.cs index 3790452423..cc6b8ecc66 100644 --- a/src/Paramore.Brighter.MessagingGateway.MQTT/MqttMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.MQTT/MqttMessageConsumerFactory.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -22,6 +22,8 @@ THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.MQTT { /// @@ -30,6 +32,7 @@ namespace Paramore.Brighter.MessagingGateway.MQTT public class MqttMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly MqttMessagingGatewayConsumerConfiguration _configuration; + private readonly ILoggerFactory _loggerFactory; private IAmAMessageScheduler? _scheduler; /// @@ -47,12 +50,15 @@ public IAmAMessageScheduler? Scheduler /// /// The MQTT consumer configuration containing broker connection details. /// The optional message scheduler for delayed requeue support + /// The used to create loggers for the consumers. public MqttMessageConsumerFactory( MqttMessagingGatewayConsumerConfiguration configuration, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null) { _configuration = configuration; _scheduler = scheduler; + _loggerFactory = loggerFactory; } /// @@ -65,7 +71,7 @@ public IAmAMessageConsumerSync Create(Subscription subscription) var deadLetterRoutingKey = (subscription as IUseBrighterDeadLetterSupport)?.DeadLetterRoutingKey; var invalidMessageRoutingKey = (subscription as IUseBrighterInvalidMessageSupport)?.InvalidMessageRoutingKey; - return new MqttMessageConsumer(_configuration, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); + return new MqttMessageConsumer(_configuration, _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); } /// @@ -78,7 +84,7 @@ public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) var deadLetterRoutingKey = (subscription as IUseBrighterDeadLetterSupport)?.DeadLetterRoutingKey; var invalidMessageRoutingKey = (subscription as IUseBrighterInvalidMessageSupport)?.InvalidMessageRoutingKey; - return new MqttMessageConsumer(_configuration, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); + return new MqttMessageConsumer(_configuration, _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/ChannelFactory.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/ChannelFactory.cs index 1bbfe14a2c..eecb6939dc 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/ChannelFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/ChannelFactory.cs @@ -2,7 +2,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.MsSql; @@ -11,7 +10,7 @@ namespace Paramore.Brighter.MessagingGateway.MsSql; /// public partial class ChannelFactory : IAmAChannelFactory, IAmAChannelFactoryWithScheduler { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly MsSqlMessageConsumerFactory _msSqlMessageConsumerFactory; /// @@ -28,11 +27,13 @@ public IAmAMessageScheduler? Scheduler /// Initializes a new instance of the class. /// /// The factory for creating MS SQL message consumers. + /// The logger. /// Thrown when the msSqlMessageConsumerFactory is null. - public ChannelFactory(MsSqlMessageConsumerFactory msSqlMessageConsumerFactory) + public ChannelFactory(MsSqlMessageConsumerFactory msSqlMessageConsumerFactory, ILogger logger) { _msSqlMessageConsumerFactory = msSqlMessageConsumerFactory ?? throw new ArgumentNullException(nameof(msSqlMessageConsumerFactory)); + _logger = logger; } /// @@ -47,7 +48,7 @@ public IAmAChannelSync CreateSyncChannel(Subscription subscription) if (rmqSubscription == null) throw new ConfigurationException("MS SQL ChannelFactory We expect an MsSqlSubscription or MsSqlSubscription as a parameter"); - Log.MsSqlInputChannelFactoryCreateInputChannel(s_logger, subscription.ChannelName, subscription.RoutingKey.Value); + Log.MsSqlInputChannelFactoryCreateInputChannel(_logger, subscription.ChannelName, subscription.RoutingKey.Value); return new Channel( subscription.ChannelName, subscription.RoutingKey, @@ -67,7 +68,7 @@ public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) if (rmqSubscription == null) throw new ConfigurationException("MS SQL ChannelFactory We expect an MsSqlSubscription or MsSqlSubscription as a parameter"); - Log.MsSqlInputChannelFactoryCreateInputChannel(s_logger, subscription.ChannelName, subscription.RoutingKey.Value); + Log.MsSqlInputChannelFactoryCreateInputChannel(_logger, subscription.ChannelName, subscription.RoutingKey.Value); return new ChannelAsync( subscription.ChannelName, subscription.RoutingKey, @@ -89,9 +90,9 @@ public async Task CreateAsyncChannelAsync(Subscription subscri if (rmqSubscription == null) throw new ConfigurationException("MS SQL ChannelFactory We expect an MsSqlSubscription or MsSqlSubscription as a parameter"); - Log.MsSqlInputChannelFactoryCreateInputChannel(s_logger, subscription.ChannelName, subscription.RoutingKey.Value); + Log.MsSqlInputChannelFactoryCreateInputChannel(_logger, subscription.ChannelName, subscription.RoutingKey.Value); var channel = new ChannelAsync( - subscription.ChannelName, + subscription.ChannelName, subscription.RoutingKey, _msSqlMessageConsumerFactory.CreateAsync(subscription), subscription.BufferSize); diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumer.cs index 3fbb43beba..c86dcb254b 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumer.cs @@ -2,7 +2,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.MsSql.SqlQueues; using Paramore.Brighter.MsSql; @@ -11,7 +10,8 @@ namespace Paramore.Brighter.MessagingGateway.MsSql public partial class MsSqlMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync { private readonly string _topic; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly MsSqlMessageQueue _sqlMessageQueue; private readonly RelationalDatabaseConfiguration _msSqlConfiguration; private readonly RoutingKey? _deadLetterRoutingKey; @@ -27,13 +27,16 @@ public MsSqlMessageConsumer( RelationalDatabaseConfiguration msSqlConfiguration, string topic, RelationalDbConnectionProvider connectionProvider, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null) { + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); _topic = topic ?? throw new ArgumentNullException(nameof(topic)); _msSqlConfiguration = msSqlConfiguration ?? throw new ArgumentNullException(nameof(msSqlConfiguration)); - _sqlMessageQueue = new MsSqlMessageQueue(msSqlConfiguration, connectionProvider); + _sqlMessageQueue = new MsSqlMessageQueue(msSqlConfiguration, connectionProvider, loggerFactory); _scheduler = scheduler; _deadLetterRoutingKey = deadLetterRoutingKey; _invalidMessageRoutingKey = invalidMessageRoutingKey; @@ -50,11 +53,12 @@ public MsSqlMessageConsumer( public MsSqlMessageConsumer( RelationalDatabaseConfiguration msSqlConfiguration, string topic, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null) - : this(msSqlConfiguration, topic, new MsSqlConnectionProvider(msSqlConfiguration), scheduler, deadLetterRoutingKey, invalidMessageRoutingKey) - {} + : this(msSqlConfiguration, topic, new MsSqlConnectionProvider(msSqlConfiguration), loggerFactory, scheduler, deadLetterRoutingKey, invalidMessageRoutingKey) + { } /// /// Acknowledges the specified message. @@ -63,7 +67,7 @@ public MsSqlMessageConsumer( /// No implementation required because of atomic 'read-and-delete' /// /// The message. - public void Acknowledge(Message message) {} + public void Acknowledge(Message message) { } public Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default(CancellationToken)) { @@ -77,7 +81,7 @@ public void Acknowledge(Message message) {} /// No implementation required because of atomic 'read-and-delete' /// /// The message. - public void Nack(Message message) {} + public void Nack(Message message) { } public Task NackAsync(Message message, CancellationToken cancellationToken = default) { @@ -89,14 +93,14 @@ public Task NackAsync(Message message, CancellationToken cancellationToken = def /// public void Purge() { - Log.PurgingQueue(s_logger); + Log.PurgingQueue(_logger); _sqlMessageQueue.Purge(); } public async Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken)) { - Log.PurgingQueue(s_logger); - await Task.Run( () => _sqlMessageQueue.Purge(), cancellationToken); + Log.PurgingQueue(_logger); + await Task.Run(() => _sqlMessageQueue.Purge(), cancellationToken); } /// @@ -149,7 +153,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); return true; } @@ -168,7 +172,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -179,11 +183,11 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (producer != null) { producer.Send(message); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) @@ -191,7 +195,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) // DLQ send failed — the message was already atomically deleted from the source // queue on Receive, so we cannot requeue it. Log and return true to prevent the // message pump from retrying endlessly. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); return true; } @@ -213,7 +217,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); return true; } @@ -232,7 +236,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -243,11 +247,11 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) @@ -255,7 +259,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) // DLQ send failed — the message was already atomically deleted from the source // queue on ReceiveAsync, so we cannot requeue it. Log and return true to prevent // the message pump from retrying endlessly. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); return true; } @@ -273,7 +277,7 @@ public bool Requeue(Message message, TimeSpan? delay = null) delay ??= TimeSpan.Zero; var topic = message.Header.Topic; - Log.RequeuingMessage(s_logger, topic.Value, message.Id.ToString()); + Log.RequeuingMessage(_logger, topic.Value, message.Id.ToString()); if (!message.Header.Bag.ContainsKey(Message.OriginalMessageIdHeaderName)) { @@ -303,7 +307,7 @@ public bool Requeue(Message message, TimeSpan? delay = null) delay ??= TimeSpan.Zero; var topic = message.Header.Topic; - Log.RequeuingMessage(s_logger, topic.Value, message.Id.ToString()); + Log.RequeuingMessage(_logger, topic.Value, message.Id.ToString()); if (!message.Header.Bag.ContainsKey(Message.OriginalMessageIdHeaderName)) { @@ -332,14 +336,15 @@ public void Dispose() public async ValueTask DisposeAsync() { - if (_requeueProducer != null) await _requeueProducer.DisposeAsync(); + if (_requeueProducer != null) + await _requeueProducer.DisposeAsync(); GC.SuppressFinalize(this); } private void EnsureRequeueProducer() { LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, - ref _requeueProducerLock, () => new MsSqlMessageProducer(_msSqlConfiguration) + ref _requeueProducerLock, () => new MsSqlMessageProducer(_msSqlConfiguration, loggerFactory: _loggerFactory) { Scheduler = _scheduler }); @@ -347,32 +352,34 @@ private void EnsureRequeueProducer() private MsSqlMessageProducer? CreateDeadLetterProducer() { - if (_deadLetterRoutingKey == null) return null; + if (_deadLetterRoutingKey == null) + return null; try { - return new MsSqlMessageProducer(_msSqlConfiguration, + return new MsSqlMessageProducer(_msSqlConfiguration, _loggerFactory, new Publication { Topic = _deadLetterRoutingKey }); } catch (Exception e) { - Log.ErrorCreatingDlqProducer(s_logger, e, _deadLetterRoutingKey.Value); + Log.ErrorCreatingDlqProducer(_logger, e, _deadLetterRoutingKey.Value); return null; } } private MsSqlMessageProducer? CreateInvalidMessageProducer() { - if (_invalidMessageRoutingKey == null) return null; + if (_invalidMessageRoutingKey == null) + return null; try { - return new MsSqlMessageProducer(_msSqlConfiguration, + return new MsSqlMessageProducer(_msSqlConfiguration, _loggerFactory, new Publication { Topic = _invalidMessageRoutingKey }); } catch (Exception e) { - Log.ErrorCreatingInvalidMessageProducer(s_logger, e, _invalidMessageRoutingKey.Value); + Log.ErrorCreatingInvalidMessageProducer(_logger, e, _invalidMessageRoutingKey.Value); return null; } } @@ -383,7 +390,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea message.Header.Bag["rejectionTimestamp"] = DateTimeOffset.UtcNow.ToString("o"); message.Header.Bag["originalMessageType"] = message.Header.MessageType.ToString(); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumerFactory.cs index 1b21ea5638..486c552a92 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumerFactory.cs @@ -1,13 +1,13 @@ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MsSql; namespace Paramore.Brighter.MessagingGateway.MsSql { public partial class MsSqlMessageConsumerFactory : IAmAMessageConsumerFactory { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly RelationalDatabaseConfiguration _msSqlConfiguration; private IAmAMessageScheduler? _scheduler; @@ -26,10 +26,13 @@ public IAmAMessageScheduler? Scheduler /// /// The configuration for connecting to the MsSql database /// The optional message scheduler for delayed requeue support - public MsSqlMessageConsumerFactory(RelationalDatabaseConfiguration msSqlConfiguration, IAmAMessageScheduler? scheduler = null) + /// The optional used to create loggers + public MsSqlMessageConsumerFactory(RelationalDatabaseConfiguration msSqlConfiguration, ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null) { _msSqlConfiguration = msSqlConfiguration ?? throw new ArgumentNullException(nameof(msSqlConfiguration)); _scheduler = scheduler; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } /// @@ -37,26 +40,28 @@ public MsSqlMessageConsumerFactory(RelationalDatabaseConfiguration msSqlConfigur /// /// The queue to connect to /// IAmAMessageConsumerSync - public IAmAMessageConsumerSync Create(Subscription subscription) + public IAmAMessageConsumerSync Create(Subscription subscription) { - if (subscription.ChannelName is null) throw new ConfigurationException(nameof(subscription.ChannelName)); + if (subscription.ChannelName is null) + throw new ConfigurationException(nameof(subscription.ChannelName)); var deadLetterRoutingKey = (subscription as IUseBrighterDeadLetterSupport)?.DeadLetterRoutingKey; var invalidMessageRoutingKey = (subscription as IUseBrighterInvalidMessageSupport)?.InvalidMessageRoutingKey; - Log.MsSqlMessageConsumerFactoryCreate(s_logger, subscription.ChannelName); - return new MsSqlMessageConsumer(_msSqlConfiguration, subscription.ChannelName!, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); + Log.MsSqlMessageConsumerFactoryCreate(_logger, subscription.ChannelName); + return new MsSqlMessageConsumer(_msSqlConfiguration, subscription.ChannelName!, _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); } public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) { - if (subscription.ChannelName is null) throw new ConfigurationException(nameof(subscription.ChannelName)); + if (subscription.ChannelName is null) + throw new ConfigurationException(nameof(subscription.ChannelName)); var deadLetterRoutingKey = (subscription as IUseBrighterDeadLetterSupport)?.DeadLetterRoutingKey; var invalidMessageRoutingKey = (subscription as IUseBrighterInvalidMessageSupport)?.InvalidMessageRoutingKey; - Log.MsSqlMessageConsumerFactoryCreateAsync(s_logger, subscription.ChannelName); - return new MsSqlMessageConsumer(_msSqlConfiguration, subscription.ChannelName!, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); + Log.MsSqlMessageConsumerFactoryCreateAsync(_logger, subscription.ChannelName); + return new MsSqlMessageConsumer(_msSqlConfiguration, subscription.ChannelName!, _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); } private static partial class Log diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs index 47bee5bb9f..ff58a05ca4 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.MsSql.SqlQueues; using Paramore.Brighter.MsSql; using Paramore.Brighter.Observability; @@ -41,7 +40,7 @@ namespace Paramore.Brighter.MessagingGateway.MsSql /// public partial class MsSqlMessageProducer : IAmAMessageProducerSync, IAmAMessageProducerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly InstrumentationOptions _instrumentation; private readonly MsSqlMessageQueue _sqlQ; @@ -68,11 +67,13 @@ public partial class MsSqlMessageProducer : IAmAMessageProducerSync, IAmAMessage public MsSqlMessageProducer( RelationalDatabaseConfiguration msSqlConfiguration, IAmARelationalDbConnectionProvider connectonProvider, + ILoggerFactory loggerFactory, Publication? publication = null, InstrumentationOptions instrumentation = InstrumentationOptions.All ) { - _sqlQ = new MsSqlMessageQueue(msSqlConfiguration, connectonProvider); + _logger = loggerFactory.CreateLogger(); + _sqlQ = new MsSqlMessageQueue(msSqlConfiguration, connectonProvider, loggerFactory); _instrumentation = instrumentation; Publication = publication ?? new Publication { MakeChannels = OnMissingChannel.Create }; } @@ -84,8 +85,9 @@ public MsSqlMessageProducer( /// The publication configuration. public MsSqlMessageProducer( RelationalDatabaseConfiguration msSqlConfiguration, + ILoggerFactory loggerFactory, Publication? publication = null) - : this(msSqlConfiguration, new MsSqlConnectionProvider(msSqlConfiguration), publication) + : this(msSqlConfiguration, new MsSqlConnectionProvider(msSqlConfiguration), loggerFactory, publication) { } @@ -116,7 +118,7 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken /// The message to send. /// The delay to use. public void SendWithDelay(Message message, TimeSpan? delay = null) - { + { delay ??= TimeSpan.Zero; if (delay != TimeSpan.Zero) { @@ -125,21 +127,21 @@ public void SendWithDelay(Message message, TimeSpan? delay = null) sync.Schedule(message, delay.Value); return; } - + if (Scheduler is IAmAMessageSchedulerAsync async) { BrighterAsyncContext.Run(() => async.ScheduleAsync(message, delay.Value)); return; - } - + } + throw new ConfigurationException( $"MsSqlMessageProducer: delay of {delay} was requested but no scheduler is configured; configure a scheduler via MessageSchedulerFactory."); } - + BrighterTracer.WriteProducerEvent(Span, "microsoft_sql_server", message, _instrumentation); var topic = message.Header.Topic; - Log.SendMessage(s_logger, topic.Value, message.Id.Value); + Log.SendMessage(_logger, topic.Value, message.Id.Value); _sqlQ.Send(message, topic); } @@ -168,7 +170,7 @@ public async Task SendWithDelayAsync(Message message, TimeSpan? delay, Cancellat sync.Schedule(message, delay.Value); return; } - + throw new ConfigurationException( $"MsSqlMessageProducer: delay of {delay} was requested but no scheduler is configured; configure a scheduler via MessageSchedulerFactory."); } @@ -176,7 +178,7 @@ public async Task SendWithDelayAsync(Message message, TimeSpan? delay, Cancellat BrighterTracer.WriteProducerEvent(Span, "microsoft_sql_server", message, _instrumentation); var topic = message.Header.Topic; - Log.SendMessageAsync(s_logger, topic.Value, message.Id.Value); + Log.SendMessageAsync(_logger, topic.Value, message.Id.Value); await _sqlQ.SendAsync(message, topic.Value, TimeSpan.Zero, cancellationToken); } @@ -195,7 +197,7 @@ private static partial class Log { [LoggerMessage(LogLevel.Debug, "MsSqlMessageProducer: send message with topic {Topic} and id {Id}")] public static partial void SendMessage(ILogger logger, string topic, string id); - + [LoggerMessage(LogLevel.Debug, "MsSqlMessageProducer: send async message with topic {Topic} and id {Id}")] public static partial void SendMessageAsync(ILogger logger, string topic, string id); } diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducerFactory.cs index 60f036b96e..76fa468a56 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducerFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.MsSql { @@ -31,21 +32,25 @@ public class MsSqlMessageProducerFactory : IAmAMessageProducerFactory { private readonly RelationalDatabaseConfiguration _msSqlConfiguration; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Creates a collection of MsSQL message producers from the MsSQL publication information /// /// The connection to use to connect to MsSQL /// The publications describing the MySQL topics that we want to use + /// The optional used to create loggers public MsSqlMessageProducerFactory( RelationalDatabaseConfiguration msSqlConfiguration, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { - _msSqlConfiguration = + _msSqlConfiguration = msSqlConfiguration ?? throw new ArgumentNullException(nameof(msSqlConfiguration)); if (string.IsNullOrEmpty(msSqlConfiguration.QueueStoreTable)) throw new ArgumentNullException(nameof(msSqlConfiguration.QueueStoreTable)); _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -53,20 +58,21 @@ public MsSqlMessageProducerFactory( /// /// A dictionary of indexed by /// Thrown when a publication does not have a topic - public Dictionary Create() + public Dictionary Create() { var producers = new Dictionary(); foreach (var publication in _publications) { - if (publication.Topic is null) throw new ConfigurationException("MS SQL Message Producer Factory: Topic is missing from the publication"); - var producer = new MsSqlMessageProducer(_msSqlConfiguration, publication); + if (publication.Topic is null) + throw new ConfigurationException("MS SQL Message Producer Factory: Topic is missing from the publication"); + var producer = new MsSqlMessageProducer(_msSqlConfiguration, _loggerFactory, publication); producer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); if (producers.ContainsKey(producerKey)) - throw new ConfigurationException($"MS SQL Message Producer Factory: A publication with the topic {publication.Topic} and {publication.Type} already exists in the producer registry. Each topic + type must be unique in the producer registry. If you did not set a type, we will match against an empty type, so you cannot have two publications with the same topic and no type in the producer registry."); + throw new ConfigurationException($"MS SQL Message Producer Factory: A publication with the topic {publication.Topic} and {publication.Type} already exists in the producer registry. Each topic + type must be unique in the producer registry. If you did not set a type, we will match against an empty type, so you cannot have two publications with the same topic and no type in the producer registry."); producers[producerKey] = producer; - + } return producers; @@ -79,7 +85,7 @@ public Dictionary Create() /// Thrown when a publication does not have a topic public Task> CreateAsync() { - return Task.FromResult(Create()); + return Task.FromResult(Create()); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlProducerRegistryFactory.cs index afbd86f2aa..d51aa2c145 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlProducerRegistryFactory.cs @@ -3,25 +3,28 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.MsSql { public partial class MsSqlProducerRegistryFactory : IAmAProducerRegistryFactory { private readonly RelationalDatabaseConfiguration _msSqlConfiguration; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly IEnumerable _publications; //-- placeholder for future use public MsSqlProducerRegistryFactory( RelationalDatabaseConfiguration msSqlConfiguration, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { - _msSqlConfiguration = + _msSqlConfiguration = msSqlConfiguration ?? throw new ArgumentNullException(nameof(msSqlConfiguration)); if (string.IsNullOrEmpty(msSqlConfiguration.QueueStoreTable)) throw new ArgumentNullException(nameof(msSqlConfiguration.QueueStoreTable)); _publications = publications; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } /// @@ -30,9 +33,9 @@ public MsSqlProducerRegistryFactory( /// A registry of middleware clients by topic, for sending messages to the middleware public IAmAProducerRegistry Create() { - Log.MsSqlMessageProducerFactoryCreateProducer(s_logger); + Log.MsSqlMessageProducerFactoryCreateProducer(_logger); - var producerFactory = new MsSqlMessageProducerFactory(_msSqlConfiguration, _publications); + var producerFactory = new MsSqlMessageProducerFactory(_msSqlConfiguration, _publications, _loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -47,7 +50,7 @@ public IAmAProducerRegistry Create() /// A registry of middleware clients by topic, for sending messages to the middleware public Task CreateAsync(CancellationToken ct = default) { - return Task.FromResult(Create()); + return Task.FromResult(Create()); } private static partial class Log diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/MsSqlMessageQueue.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/MsSqlMessageQueue.cs index 797c7b5531..3ee5bde2bd 100644 --- a/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/MsSqlMessageQueue.cs +++ b/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/MsSqlMessageQueue.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.MessagingGateway.MsSql.SqlQueues { @@ -18,7 +17,7 @@ namespace Paramore.Brighter.MessagingGateway.MsSql.SqlQueues public partial class MsSqlMessageQueue { private const int RetryDelay = 100; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private readonly RelationalDatabaseConfiguration _configuration; private readonly IAmARelationalDbConnectionProvider _connectionProvider; @@ -27,11 +26,12 @@ public partial class MsSqlMessageQueue /// /// /// - public MsSqlMessageQueue(RelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) + public MsSqlMessageQueue(RelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILoggerFactory loggerFactory) { + _logger = loggerFactory.CreateLogger>(); _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _connectionProvider = connectionProvider; - Log.MsSqlMessageQueueCtor(s_logger, _configuration.ConnectionString, _configuration.QueueStoreTable); + Log.MsSqlMessageQueueCtor(_logger, _configuration.ConnectionString, _configuration.QueueStoreTable); ContinueOnCapturedContext = false; } @@ -54,8 +54,8 @@ public MsSqlMessageQueue(RelationalDatabaseConfiguration configuration, IAmARela public void Send(T message, RoutingKey topic, TimeSpan? timeOut = null) { timeOut ??= TimeSpan.FromMilliseconds(-1); - - Log.Send(s_logger, typeof(T).FullName, topic); + + Log.Send(_logger, typeof(T).FullName, topic); var parameters = InitAddDbParameters(topic.Value, message); @@ -74,10 +74,10 @@ public void Send(T message, RoutingKey topic, TimeSpan? timeOut = null) /// public async Task SendAsync(T message, string topic, TimeSpan? timeOut, CancellationToken cancellationToken = default) { - Log.SendAsync(s_logger, typeof(T).FullName, topic); + Log.SendAsync(_logger, typeof(T).FullName, topic); timeOut ??= TimeSpan.FromMilliseconds(-1); - + var parameters = InitAddDbParameters(topic, message); using var connection = await _connectionProvider.GetConnectionAsync(cancellationToken); @@ -95,9 +95,9 @@ public async Task SendAsync(T message, string topic, TimeSpan? timeOut, Cancella public ReceivedResult TryReceive(string topic, TimeSpan? timeout = null) { timeout ??= TimeSpan.FromMilliseconds(-1); - - Log.TryReceive(s_logger, typeof(T).FullName, timeout.Value.TotalMilliseconds); - + + Log.TryReceive(_logger, typeof(T).FullName, timeout.Value.TotalMilliseconds); + var rc = TryReceive(topic); var timeLeft = timeout.Value.TotalMilliseconds; while (!rc.IsDataValid && timeLeft > 0) @@ -117,7 +117,7 @@ public ReceivedResult TryReceive(string topic, TimeSpan? timeout = null) /// The message received -or- ReceivedResult<T>.Empty when no message is waiting private ReceivedResult TryReceive(string topic) { - Log.TryReceiveInner(s_logger, typeof(T).FullName); + Log.TryReceiveInner(_logger, typeof(T).FullName); var parameters = InitRemoveDbParameters(topic); @@ -126,9 +126,9 @@ private ReceivedResult TryReceive(string topic) var reader = sqlCmd.ExecuteReader(); if (!reader.Read()) return ReceivedResult.Empty; - var json = (string) reader[0]; - var messageType = (string) reader[1]; - var id = (long) reader[3]; + var json = (string)reader[0]; + var messageType = (string)reader[1]; + var id = (long)reader[3]; var message = JsonSerializer.Deserialize(json, JsonSerialisationOptions.Options); return new ReceivedResult(true, json, topic, messageType, id, message); } @@ -142,7 +142,7 @@ private ReceivedResult TryReceive(string topic) public async Task> TryReceiveAsync(string topic, CancellationToken cancellationToken = default) { - Log.TryReceiveAsync(s_logger, typeof(T).FullName); + Log.TryReceiveAsync(_logger, typeof(T).FullName); var parameters = InitRemoveDbParameters(topic); @@ -152,9 +152,9 @@ public async Task> TryReceiveAsync(string topic, .ConfigureAwait(ContinueOnCapturedContext); if (!await reader.ReadAsync(cancellationToken)) return ReceivedResult.Empty; - var json = (string) reader[0]; - var messageType = (string) reader[1]; - var id = (long) reader[3]; + var json = (string)reader[0]; + var messageType = (string)reader[1]; + var id = (long)reader[3]; var message = JsonSerializer.Deserialize(json, JsonSerialisationOptions.Options); return new ReceivedResult(true, json, topic, messageType, id, message); } @@ -171,10 +171,11 @@ public int NumberOfMessageReady(string topic) var sqlCmd = connection.CreateCommand(); sqlCmd.CommandText = sql; object? count = sqlCmd.ExecuteScalar(); - - if (count is null) return 0; - - return (int) count; + + if (count is null) + return 0; + + return (int)count; } /// @@ -182,13 +183,13 @@ public int NumberOfMessageReady(string topic) /// public void Purge() { - Log.Purge(s_logger); + Log.Purge(_logger); using var connection = _connectionProvider.GetConnection(); var sqlCmd = InitPurgeDbCommand(connection); sqlCmd.ExecuteNonQuery(); } - + private static IDbDataParameter CreateDbDataParameter(string parameterName, object value) { return new SqlParameter(parameterName, value); @@ -198,8 +199,9 @@ private static IDbDataParameter[] InitAddDbParameters(string topic, T message) { string? fullName = typeof(T).FullName; //not sure how we would ever get here. - if (fullName is null) throw new ArgumentNullException(nameof(fullName), "MsSQLMessageQueue: The type of the message must have a full name"); - + if (fullName is null) + throw new ArgumentNullException(nameof(fullName), "MsSQLMessageQueue: The type of the message must have a full name"); + var parameters = new[] { CreateDbDataParameter("topic", topic), @@ -214,7 +216,8 @@ private DbCommand InitAddDbCommand(TimeSpan timeOut, DbConnection connection, ID var sql = $"set nocount on;insert into [{_configuration.QueueStoreTable}] (Topic, MessageType, Payload) values(@topic, @messageType, @payload);"; var sqlCmd = connection.CreateCommand(); - if (timeOut != TimeSpan.FromSeconds(-1)) sqlCmd.CommandTimeout = timeOut.Seconds; + if (timeOut != TimeSpan.FromSeconds(-1)) + sqlCmd.CommandTimeout = timeOut.Seconds; sqlCmd.CommandText = sql; sqlCmd.Parameters.AddRange(parameters); @@ -262,7 +265,7 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "TryReceive<{CommandType}>(..., {Timeout})")] public static partial void TryReceive(ILogger logger, string? commandType, double timeout); - + [LoggerMessage(LogLevel.Debug, "TryReceive<{CommandType}>(...)")] public static partial void TryReceiveInner(ILogger logger, string? commandType); diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresChannelFactory.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresChannelFactory.cs index 4531e5d5e7..6c1cee3230 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresChannelFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresChannelFactory.cs @@ -1,5 +1,6 @@ using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Postgres; @@ -8,9 +9,9 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; /// This factory is responsible for ensuring the underlying queue store exists and for creating channels /// configured according to the provided . /// -public class PostgresChannelFactory(PostgresMessagingGatewayConnection connection): PostgresMessagingGateway(connection), IAmAChannelFactory +public class PostgresChannelFactory(PostgresMessagingGatewayConnection connection, ILoggerFactory loggerFactory): PostgresMessagingGateway(connection), IAmAChannelFactory { - private readonly PostgresConsumerFactory _factory = new(connection); + private readonly PostgresConsumerFactory _factory = new(connection, loggerFactory); /// public IAmAChannelSync CreateSyncChannel(Subscription subscription) diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresConsumerFactory.cs index b90884f681..4649a8da7d 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresConsumerFactory.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.Postgres; /// @@ -5,14 +7,14 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; /// This factory is responsible for instantiating instances based on the /// provided configuration. /// -public class PostgresConsumerFactory(PostgresMessagingGatewayConnection connection) : IAmAMessageConsumerFactory +public class PostgresConsumerFactory(PostgresMessagingGatewayConnection connection, ILoggerFactory loggerFactory) : IAmAMessageConsumerFactory { /// public IAmAMessageConsumerSync Create(Subscription subscription) => CreateMessageConsumer(subscription); /// - public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) + public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) => CreateMessageConsumer(subscription); private PostgresMessageConsumer CreateMessageConsumer(Subscription subscription) @@ -28,6 +30,7 @@ private PostgresMessageConsumer CreateMessageConsumer(Subscription subscription) return new PostgresMessageConsumer( connection.Configuration, postgresSubscription, + loggerFactory, deadLetterRoutingKey, invalidMessageRoutingKey); } diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageConsumer.cs index 29a079ec0d..ac78faf59e 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageConsumer.cs @@ -8,7 +8,6 @@ using Npgsql; using NpgsqlTypes; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.PostgreSql; using JsonSerializer = System.Text.Json.JsonSerializer; @@ -21,11 +20,12 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; public partial class PostgresMessageConsumer( RelationalDatabaseConfiguration configuration, PostgresSubscription subscription, + ILoggerFactory loggerFactory, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null ) : IAmAMessageConsumerAsync, IAmAMessageConsumerSync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private readonly RelationalDatabaseConfiguration _configuration = configuration; private readonly PostgreSqlConnectionProvider _connectionProvider = new(configuration); private readonly RoutingKey? _deadLetterRoutingKey = deadLetterRoutingKey; @@ -34,9 +34,9 @@ public partial class PostgresMessageConsumer( // thread-safety mode is needed. None does not cache exceptions, allowing the factory // to retry on the next .Value access after a transient failure. private readonly Lazy? _deadLetterProducer = - deadLetterRoutingKey != null ? new Lazy(() => CreateProducer(configuration, deadLetterRoutingKey), LazyThreadSafetyMode.None) : null; + deadLetterRoutingKey != null ? new Lazy(() => CreateProducer(configuration, deadLetterRoutingKey, loggerFactory), LazyThreadSafetyMode.None) : null; private readonly Lazy? _invalidMessageProducer = - invalidMessageRoutingKey != null ? new Lazy(() => CreateProducer(configuration, invalidMessageRoutingKey), LazyThreadSafetyMode.None) : null; + invalidMessageRoutingKey != null ? new Lazy(() => CreateProducer(configuration, invalidMessageRoutingKey, loggerFactory), LazyThreadSafetyMode.None) : null; private string SchemaName => subscription.SchemaName ?? _configuration.SchemaName ?? "public"; private string TableName => subscription.QueueStoreTable ?? _configuration.QueueStoreTable; @@ -45,7 +45,7 @@ public partial class PostgresMessageConsumer( private int BufferSize => subscription.BufferSize; private TimeSpan VisibleTimeout => subscription.VisibleTimeout; private bool HasLargeMessage => subscription.TableWithLargeMessage; - + private NpgsqlDbType DbType => BinaryMessagePayload ? NpgsqlDbType.Jsonb : NpgsqlDbType.Json; /// @@ -63,15 +63,15 @@ public void Acknowledge(Message message) command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"id\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); command.ExecuteNonQuery(); - Log.DeletedMessage(s_logger, message.Id.Value, receiptHandle, QueueName); + Log.DeletedMessage(_logger, message.Id.Value, receiptHandle, QueueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, message.Id.Value, receiptHandle, QueueName); + Log.ErrorDeletingMessage(_logger, exception, message.Id.Value, receiptHandle, QueueName); throw; } } - + /// public async Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default) { @@ -87,35 +87,35 @@ public async Task AcknowledgeAsync(Message message, CancellationToken cancellati command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"id\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); await command.ExecuteNonQueryAsync(cancellationToken); - Log.DeletedMessage(s_logger, message.Id.Value, receiptHandle, QueueName); + Log.DeletedMessage(_logger, message.Id.Value, receiptHandle, QueueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, message.Id.Value, receiptHandle, QueueName); + Log.ErrorDeletingMessage(_logger, exception, message.Id.Value, receiptHandle, QueueName); throw; } } - + /// public async Task PurgeAsync(CancellationToken cancellationToken = default) { try { - Log.PurgingQueue(s_logger, TableName); + Log.PurgingQueue(_logger, TableName); await using var connection = await _connectionProvider.GetConnectionAsync(cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"queue\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); await command.ExecuteNonQueryAsync(cancellationToken); - - Log.PurgedQueue(s_logger, QueueName); + + Log.PurgedQueue(_logger, QueueName); } catch (Exception exception) { - Log.ErrorPurgingQueue(s_logger, exception, QueueName); + Log.ErrorPurgingQueue(_logger, exception, QueueName); throw; } - + } /// @@ -123,14 +123,14 @@ public async Task ReceiveAsync(TimeSpan? timeOut = null, Cancellation { try { - Log.RetrievingNextMessage(s_logger, QueueName); + Log.RetrievingNextMessage(_logger, QueueName); await using var connection = await _connectionProvider.GetConnectionAsync(cancellationToken); await using var command = connection.CreateCommand(); if (timeOut != null && timeOut != TimeSpan.Zero) { command.CommandTimeout = Convert.ToInt32(timeOut.Value.TotalSeconds); } - + command.CommandText = $""" UPDATE "{SchemaName}"."{TableName}" queue SET @@ -154,7 +154,7 @@ FOR UPDATE SKIP LOCKED { if (HasLargeMessage) { - messages.Add(await ToLargeMessageAsync(reader,cancellationToken)); + messages.Add(await ToLargeMessageAsync(reader, cancellationToken)); } else { @@ -171,11 +171,11 @@ FOR UPDATE SKIP LOCKED } catch (Exception exception) { - Log.ErrorListeningToQueue(s_logger, exception, QueueName); + Log.ErrorListeningToQueue(_logger, exception, QueueName); throw; } } - + /// public void Nack(Message message) { @@ -197,12 +197,12 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) return false; } - Log.RejectingMessage(s_logger, message.Id.Value, receiptHandle, QueueName); + Log.RejectingMessage(_logger, message.Id.Value, receiptHandle, QueueName); if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); DeleteSourceMessage(receiptHandle); return true; @@ -222,7 +222,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -233,18 +233,18 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (producer != null) { producer.Send(message); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // DLQ send failed — delete the source message (in finally) and return true // to prevent the message pump from retrying endlessly. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); return true; } finally @@ -254,7 +254,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) return true; } - + /// public async Task RejectAsync(Message message, MessageRejectionReason? reason = null, CancellationToken cancellationToken = default) { @@ -263,12 +263,12 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea return false; } - Log.RejectingMessage(s_logger, message.Id.Value, receiptHandle, QueueName); + Log.RejectingMessage(_logger, message.Id.Value, receiptHandle, QueueName); if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); await DeleteSourceMessageAsync(receiptHandle, cancellationToken); return true; @@ -288,7 +288,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -299,18 +299,18 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // DLQ send failed — delete the source message and return true // to prevent the message pump from retrying endlessly. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); return true; } finally @@ -321,7 +321,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea return true; } - + /// public async Task RequeueAsync(Message message, TimeSpan? delay = null, CancellationToken cancellationToken = default) @@ -330,10 +330,10 @@ public async Task RequeueAsync(Message message, TimeSpan? delay = null, Ca { return false; } - + try { - Log.RequeueingMessage(s_logger, message.Id.Value); + Log.RequeueingMessage(_logger, message.Id.Value); if (!message.Header.Bag.ContainsKey(Message.OriginalMessageIdHeaderName)) { @@ -345,40 +345,40 @@ public async Task RequeueAsync(Message message, TimeSpan? delay = null, Ca command.CommandText = $"UPDATE \"{SchemaName}\".\"{TableName}\" SET \"visible_timeout\" = CURRENT_TIMESTAMP + $1, \"content\" = $2 WHERE \"id\" = $3"; command.Parameters.Add(new NpgsqlParameter { Value = delay ?? TimeSpan.Zero }); - command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = DbType}); + command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = DbType }); command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); await command.ExecuteNonQueryAsync(cancellationToken); - - Log.RequeuedMessage(s_logger, message.Id.Value); + + Log.RequeuedMessage(_logger, message.Id.Value); return true; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value, receiptHandle, QueueName); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value, receiptHandle, QueueName); return false; } } - + /// public void Purge() { try { - Log.PurgingQueue(s_logger, QueueName); + Log.PurgingQueue(_logger, QueueName); using var connection = _connectionProvider.GetConnection(); using var command = connection.CreateCommand(); command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"queue\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); command.ExecuteNonQuery(); - Log.PurgedQueue(s_logger, QueueName); + Log.PurgedQueue(_logger, QueueName); } catch (Exception exception) { - Log.ErrorPurgingQueue(s_logger, exception, QueueName); + Log.ErrorPurgingQueue(_logger, exception, QueueName); throw; } } @@ -388,8 +388,8 @@ public Message[] Receive(TimeSpan? timeOut = null) { try { - Log.RetrievingNextMessage(s_logger, QueueName); - + Log.RetrievingNextMessage(_logger, QueueName); + using var connection = _connectionProvider.GetConnection(); using var command = connection.CreateCommand(); if (timeOut != null && timeOut.Value != TimeSpan.Zero) @@ -420,7 +420,7 @@ FOR UPDATE SKIP LOCKED { messages.Add(HasLargeMessage ? ToLargeMessage(reader) : ToMessage(reader)); } - + if (messages.Count == 0) { messages.Add(new Message()); @@ -430,7 +430,7 @@ FOR UPDATE SKIP LOCKED } catch (Exception exception) { - Log.ErrorListeningToQueue(s_logger, exception, QueueName); + Log.ErrorListeningToQueue(_logger, exception, QueueName); throw; } } @@ -442,10 +442,10 @@ public bool Requeue(Message message, TimeSpan? delay = null) { return false; } - + try { - Log.RequeueingMessage(s_logger, message.Id.Value); + Log.RequeueingMessage(_logger, message.Id.Value); if (!message.Header.Bag.ContainsKey(Message.OriginalMessageIdHeaderName)) { @@ -461,18 +461,18 @@ public bool Requeue(Message message, TimeSpan? delay = null) command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = DbType }); command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); command.ExecuteNonQuery(); - - Log.RequeuedMessage(s_logger, message.Id.Value); + + Log.RequeuedMessage(_logger, message.Id.Value); return true; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value, receiptHandle, QueueName); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value, receiptHandle, QueueName); return false; } } - + /// public ValueTask DisposeAsync() { @@ -488,11 +488,11 @@ private static Message ToMessage(DbDataReader reader) var id = reader.GetInt64(0); var content = reader.GetFieldValue(3); var message = JsonSerializer.Deserialize(content, JsonSerialisationOptions.Options)!; - + message.Header.Bag["ReceiptHandle"] = id; return message; } - + private Message ToLargeMessage(DbDataReader reader) { var id = reader.GetInt64(0); @@ -503,13 +503,13 @@ private Message ToLargeMessage(DbDataReader reader) // Skipping the first by https://github.com/npgsql/npgsql/issues/6044 content.Position = 1; } - + var message = JsonSerializer.Deserialize(content, JsonSerialisationOptions.Options)!; - + message.Header.Bag["ReceiptHandle"] = id; return message; } - + private async Task ToLargeMessageAsync(DbDataReader reader, CancellationToken cancellationToken) { var id = reader.GetInt64(0); @@ -520,22 +520,23 @@ private async Task ToLargeMessageAsync(DbDataReader reader, Cancellatio // Skipping the first by https://github.com/npgsql/npgsql/issues/6044 content.Position = 1; } - + var message = await JsonSerializer.DeserializeAsync(content, JsonSerialisationOptions.Options, cancellationToken); - + message!.Header.Bag["ReceiptHandle"] = id; return message; } - - private static PostgresMessageProducer? CreateProducer(RelationalDatabaseConfiguration config, RoutingKey routingKey) + + private static PostgresMessageProducer? CreateProducer(RelationalDatabaseConfiguration config, RoutingKey routingKey, ILoggerFactory loggerFactory) { try { - return new PostgresMessageProducer(config, new PostgresPublication { Topic = routingKey }); + return new PostgresMessageProducer(config, new PostgresPublication { Topic = routingKey }, loggerFactory: loggerFactory); } catch (Exception e) { - Log.ErrorCreatingProducer(s_logger, e, routingKey.Value); + var logger = loggerFactory.CreateLogger(); + Log.ErrorCreatingProducer(logger, e, routingKey.Value); return null; } } @@ -546,7 +547,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea message.Header.Bag["rejectionTimestamp"] = DateTimeOffset.UtcNow.ToString("o"); message.Header.Bag["originalMessageType"] = message.Header.MessageType.ToString(); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -585,11 +587,11 @@ private void DeleteSourceMessage(object receiptHandle) command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"id\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); command.ExecuteNonQuery(); - Log.DeletedMessage(s_logger, "source", receiptHandle, QueueName); + Log.DeletedMessage(_logger, "source", receiptHandle, QueueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, "source", receiptHandle, QueueName); + Log.ErrorDeletingMessage(_logger, exception, "source", receiptHandle, QueueName); throw; } } @@ -603,11 +605,11 @@ private async Task DeleteSourceMessageAsync(object receiptHandle, CancellationTo command.CommandText = $"DELETE FROM \"{SchemaName}\".\"{TableName}\" WHERE \"id\" = $1"; command.Parameters.Add(new NpgsqlParameter { Value = receiptHandle }); await command.ExecuteNonQueryAsync(cancellationToken); - Log.DeletedMessage(s_logger, "source", receiptHandle, QueueName); + Log.DeletedMessage(_logger, "source", receiptHandle, QueueName); } catch (Exception exception) { - Log.ErrorDeletingMessage(s_logger, exception, "source", receiptHandle, QueueName); + Log.ErrorDeletingMessage(_logger, exception, "source", receiptHandle, QueueName); throw; } } @@ -616,16 +618,16 @@ private static partial class Log { [LoggerMessage(LogLevel.Information, "PostgresPullMessageConsumer: Deleted the message {Id} with receipt handle {ReceiptHandle} on the queue {QueueName}")] public static partial void DeletedMessage(ILogger logger, string id, object receiptHandle, string queueName); - + [LoggerMessage(LogLevel.Error, "PostgresPullMessageConsumer: Error during deleting the message {Id} with receipt handle {ReceiptHandle} on the queue {ChannelName}")] public static partial void ErrorDeletingMessage(ILogger logger, Exception exception, string id, object receiptHandle, string channelName); - + [LoggerMessage(LogLevel.Information, "PostgresPullMessageConsumer: Rejecting the message {Id} with receipt handle {ReceiptHandle} on the queue {ChannelName}")] public static partial void RejectingMessage(ILogger logger, string id, object? receiptHandle, string channelName); [LoggerMessage(LogLevel.Error, "PostgresPullMessageConsumer: Error during rejecting the message {Id} with receipt handle {ReceiptHandle} on the queue {ChannelName}")] public static partial void ErrorRejectingMessage(ILogger logger, Exception exception, string id, object? receiptHandle, string channelName); - + [LoggerMessage(LogLevel.Information, "PostgresPullMessageConsumer: Purging the queue {ChannelName}")] public static partial void PurgingQueue(ILogger logger, string channelName); @@ -637,10 +639,10 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "PostgresPullMessageConsumer: Preparing to retrieve next message from queue {TableName}")] public static partial void RetrievingNextMessage(ILogger logger, string tableName); - + [LoggerMessage(LogLevel.Error, "PostgresPullMessageConsumer: There was an error listening to queue {ChannelName}")] public static partial void ErrorListeningToQueue(ILogger logger, Exception exception, string channelName); - + [LoggerMessage(LogLevel.Information, "PostgresPullMessageConsumer: re-queueing the message {Id}")] public static partial void RequeueingMessage(ILogger logger, string id); diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducer.cs index 9491829b31..3db83d3ae4 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducer.cs @@ -7,7 +7,6 @@ using Npgsql; using NpgsqlTypes; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.PostgreSql; @@ -21,9 +20,10 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; public partial class PostgresMessageProducer( RelationalDatabaseConfiguration configuration, PostgresPublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentations = InstrumentationOptions.All) : IAmAMessageProducerAsync, IAmAMessageProducerSync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private readonly PostgreSqlConnectionProvider _connectionProvider = new(configuration); private PostgresPublication _publication = publication; @@ -31,9 +31,9 @@ public partial class PostgresMessageProducer( private string TableName => _publication.QueueStoreTable ?? configuration.QueueStoreTable; private string QueueName => _publication.Topic!.Value; private bool BinaryMessagePayload => _publication.BinaryMessagePayload ?? configuration.BinaryMessagePayload; - + private NpgsqlDbType MessagePayloadDbType => BinaryMessagePayload ? NpgsqlDbType.Jsonb : NpgsqlDbType.Json; - + /// public Publication Publication { @@ -43,10 +43,10 @@ public Publication Publication /// public Activity? Span { get; set; } - + /// public IAmAMessageScheduler? Scheduler { get; set; } - + /// public async Task SendAsync(Message message, CancellationToken cancellationToken = default) { @@ -54,19 +54,19 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken { throw new ConfigurationException("No publication specified for producer"); } - + BrighterTracer.WriteProducerEvent(Span, "postgres", message, instrumentations); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); - + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + await using var connection = await _connectionProvider.GetConnectionAsync(cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = $"INSERT INTO \"{SchemaName}\".\"{TableName}\"(\"visible_timeout\", \"queue\", \"content\") VALUES (CURRENT_TIMESTAMP, $1, $2) RETURNING \"id\""; command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); - command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType}); + command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType }); var id = await command.ExecuteScalarAsync(cancellationToken); - - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); + + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); } /// @@ -77,47 +77,47 @@ public async Task SendWithDelayAsync(Message message, TimeSpan? delay, Cancellat await SendAsync(message, cancellationToken); return; } - + if (_publication is null) { throw new ConfigurationException("No publication specified for producer"); } - + BrighterTracer.WriteProducerEvent(Span, "postgres", message, instrumentations); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); - + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + await using var connection = await _connectionProvider.GetConnectionAsync(cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = $"INSERT INTO \"{SchemaName}\".\"{TableName}\"(\"visible_timeout\", \"queue\", \"content\") VALUES (CURRENT_TIMESTAMP + $1, $2, $3) RETURNING \"id\""; command.Parameters.Add(new NpgsqlParameter { Value = delay.Value }); command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); - command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType}); + command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType }); var id = await command.ExecuteScalarAsync(cancellationToken); - - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); + + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); } - + /// public void Send(Message message) - { + { if (_publication is null) { throw new ConfigurationException("No publication specified for producer"); } - + BrighterTracer.WriteProducerEvent(Span, "postgres", message, instrumentations); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); - + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + using var connection = _connectionProvider.GetConnection(); using var command = connection.CreateCommand(); command.CommandText = $"INSERT INTO \"{SchemaName}\".\"{TableName}\"(\"visible_timeout\", \"queue\", \"content\") VALUES (CURRENT_TIMESTAMP, $1, $2) RETURNING \"id\""; command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); - command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType}); + command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType }); var id = command.ExecuteScalar(); - - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); + + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); } /// @@ -128,25 +128,25 @@ public void SendWithDelay(Message message, TimeSpan? delay) Send(message); return; } - + if (_publication is null) { throw new ConfigurationException("No publication specified for producer"); } - + BrighterTracer.WriteProducerEvent(Span, "postgres", message, instrumentations); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.Value, message.Body); - + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.Value, message.Body); + using var connection = _connectionProvider.GetConnection(); using var command = connection.CreateCommand(); command.CommandText = $"INSERT INTO \"{SchemaName}\".\"{TableName}\"(\"visible_timeout\", \"queue\", \"content\") VALUES (CURRENT_TIMESTAMP + $1, $2, $3) RETURNING \"id\""; command.Parameters.Add(new NpgsqlParameter { Value = delay.Value }); command.Parameters.Add(new NpgsqlParameter { Value = QueueName }); - command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType}); + command.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), NpgsqlDbType = MessagePayloadDbType }); var id = command.ExecuteScalar(); - - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); + + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.Value, Convert.ToInt64(id)); } @@ -156,7 +156,7 @@ public ValueTask DisposeAsync() Dispose(); return ValueTask.CompletedTask; } - + /// public void Dispose() => Span?.Dispose(); diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducerFactory.cs index d19f88e7c8..b5615fa577 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducerFactory.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Postgres; @@ -10,7 +11,7 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; /// ensures the underlying queue store exists for each publication, and creates a corresponding /// instance, keyed by the publication's topic. /// -public class PostgresMessageProducerFactory(PostgresMessagingGatewayConnection connection, IEnumerable publications) : PostgresMessagingGateway(connection), IAmAMessageProducerFactory +public class PostgresMessageProducerFactory(PostgresMessagingGatewayConnection connection, IEnumerable publications, ILoggerFactory loggerFactory) : PostgresMessagingGateway(connection), IAmAMessageProducerFactory { /// /// Creates a dictionary of in-memory message producers. @@ -31,7 +32,7 @@ public Dictionary Create() EnsureQueueStoreExists(schemaName, tableName, binaryMessagePayload, publication.MakeChannels); - var producer = new PostgresMessageProducer(Connection.Configuration, publication); + var producer = new PostgresMessageProducer(Connection.Configuration, publication, loggerFactory: loggerFactory); producer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); @@ -64,7 +65,7 @@ public async Task> CreateAsync() await EnsureQueueStoreExistsAsync(schemaName, tableName, binaryMessagePayload, publication.MakeChannels, CancellationToken.None); - var producer = new PostgresMessageProducer(Connection.Configuration, publication); + var producer = new PostgresMessageProducer(Connection.Configuration, publication, loggerFactory: loggerFactory); producer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); diff --git a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresProducerRegistryFactory.cs index e2291edd2e..9edd1b60c6 100644 --- a/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Postgres/PostgresProducerRegistryFactory.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Postgres; @@ -9,19 +10,19 @@ namespace Paramore.Brighter.MessagingGateway.Postgres; /// to publish messages to a PostgreSQL message queue. This factory takes a connection configuration and a collection /// of configurations to build the registry. /// -public class PostgresProducerRegistryFactory(PostgresMessagingGatewayConnection connection, IEnumerable publications) : IAmAProducerRegistryFactory +public class PostgresProducerRegistryFactory(PostgresMessagingGatewayConnection connection, IEnumerable publications, ILoggerFactory loggerFactory) : IAmAProducerRegistryFactory { /// public IAmAProducerRegistry Create() - { - var producerFactory = new PostgresMessageProducerFactory(connection, publications); + { + var producerFactory = new PostgresMessageProducerFactory(connection, publications, loggerFactory); return new ProducerRegistry(producerFactory.Create()); } /// public async Task CreateAsync(CancellationToken ct = default) { - var producerFactory = new PostgresMessageProducerFactory(connection, publications); + var producerFactory = new PostgresMessageProducerFactory(connection, publications, loggerFactory); return new ProducerRegistry(await producerFactory.CreateAsync()); } } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/ConnectionPolicyFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/ConnectionPolicyFactory.cs index bcc3ab3256..3d32b4fa08 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/ConnectionPolicyFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/ConnectionPolicyFactory.cs @@ -24,7 +24,6 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Polly; using RabbitMQ.Client.Exceptions; @@ -35,25 +34,30 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async /// public partial class ConnectionPolicyFactory { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// - public ConnectionPolicyFactory() - : this(new RmqMessagingGatewayConnection()) - {} + public ConnectionPolicyFactory(ILoggerFactory loggerFactory) + : this(new RmqMessagingGatewayConnection(), loggerFactory) + { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Use if you need to inject a test logger /// /// - public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection) + /// The used to create a logger. + public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { - if (connection.Exchange is null) throw new ConfigurationException("RabbitMQ Exchange is not set"); - if (connection.AmpqUri is null) throw new ConfigurationException("RabbitMQ Broker URL is not set"); - + _logger = loggerFactory.CreateLogger(); + + if (connection.Exchange is null) + throw new ConfigurationException("RabbitMQ Exchange is not set"); + if (connection.AmpqUri is null) + throw new ConfigurationException("RabbitMQ Broker URL is not set"); + var retries = connection.AmpqUri.ConnectionRetryCount; var retryWaitInMilliseconds = connection.AmpqUri.RetryWaitInMilliseconds; var circuitBreakerTimeout = connection.AmpqUri.CircuitBreakTimeInMilliseconds; @@ -68,13 +72,13 @@ public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection) { if (exception is BrokerUnreachableException) { - Log.BrokerUnreachableException(s_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri(), retries); + Log.BrokerUnreachableException(_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri(), retries); } else { - Log.ExceptionOnSubscription(s_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri()); + Log.ExceptionOnSubscription(_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri()); - throw new ChannelFailureException($"RMQMessagingGateway: Exception on subscription to queue { context["queueName"]} via exchange {connection.Exchange.Name} on subscription {connection.AmpqUri.GetSanitizedUri()}", exception); + throw new ChannelFailureException($"RMQMessagingGateway: Exception on subscription to queue {context["queueName"]} via exchange {connection.Exchange.Name} on subscription {connection.AmpqUri.GetSanitizedUri()}", exception); } }); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/PullConsumer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/PullConsumer.cs index eac9c84205..e1562ae1e1 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/PullConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/PullConsumer.cs @@ -28,15 +28,14 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Paramore.Brighter.MessagingGateway.RMQ.Async; -public partial class PullConsumer(IChannel channel) : AsyncDefaultBasicConsumer(channel) +public partial class PullConsumer(IChannel channel, ILoggerFactory loggerFactory) : AsyncDefaultBasicConsumer(channel) { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); //we do end up creating a second buffer to the Brighter Channel, but controlling the flow from RMQ depends //on us being able to buffer up to the set QoS and then pull. This matches other implementations. @@ -131,7 +130,7 @@ protected override async Task OnCancelAsync(string[] consumerTags, catch (Exception e) { //don't impede shutdown, just log - Log.NackUnhandledMessagesOnShutdownFailed(s_logger, e.Message); + Log.NackUnhandledMessagesOnShutdownFailed(_logger, e.Message); } await base.OnCancelAsync(consumerTags, cancellationToken); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumer.cs index e68a73eeab..3a3c502d94 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumer.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; using Polly.CircuitBreaker; using RabbitMQ.Client.Exceptions; @@ -47,7 +46,8 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; /// public partial class RmqMessageConsumer : RmqMessageGateway, IAmAMessageConsumerSync, IAmAMessageConsumerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly RmqMessageCreator _messageCreator; private PullConsumer? _consumer; private RmqMessageProducer? _requeueProducer; @@ -85,11 +85,13 @@ public partial class RmqMessageConsumer : RmqMessageGateway, IAmAMessageConsumer /// Should we validate, or create missing channels /// The type of queue to use - Classic or Quorum; defaults to Classic /// Optional scheduler for delayed requeue operations + /// The used to create a logger. public RmqMessageConsumer( RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, + ILoggerFactory loggerFactory, bool highAvailability = false, int batchSize = 1, ChannelName? deadLetterQueueName = null, @@ -99,7 +101,7 @@ public RmqMessageConsumer( OnMissingChannel makeChannels = OnMissingChannel.Create, QueueType queueType = QueueType.Classic, IAmAMessageScheduler? scheduler = null) - : this(connection, queueName, new RoutingKeys(routingKey), isDurable, highAvailability, + : this(connection, queueName, new RoutingKeys(routingKey), isDurable, loggerFactory, highAvailability, batchSize, deadLetterQueueName, deadLetterRoutingKey, ttl, maxQueueLength, makeChannels, queueType, scheduler) { } @@ -120,11 +122,13 @@ public RmqMessageConsumer( /// Should we validate or create missing channels /// The type of queue to use - Classic or Quorum; defaults to Classic /// Optional scheduler for delayed requeue operations + /// The used to create a logger. public RmqMessageConsumer( RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKeys routingKeys, bool isDurable, + ILoggerFactory loggerFactory, bool highAvailability = false, int batchSize = 1, ChannelName? deadLetterQueueName = null, @@ -134,8 +138,10 @@ public RmqMessageConsumer( OnMissingChannel makeChannels = OnMissingChannel.Create, QueueType queueType = QueueType.Classic, IAmAMessageScheduler? scheduler = null) - : base(connection) + : base(connection, loggerFactory) { + _logger = loggerFactory.CreateLogger(); + _messageCreator = new RmqMessageCreator(LoggerFactory.CreateLogger()); _queueName = queueName; _routingKeys = routingKeys; _isDurable = isDurable; @@ -165,7 +171,7 @@ public RmqMessageConsumer( /// Acknowledges the specified message. /// /// The message. - public void Acknowledge(Message message) => BrighterAsyncContext.Run(async () =>await AcknowledgeAsync(message)); + public void Acknowledge(Message message) => BrighterAsyncContext.Run(async () => await AcknowledgeAsync(message)); public async Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default) { @@ -173,15 +179,16 @@ public async Task AcknowledgeAsync(Message message, CancellationToken cancellati try { await EnsureBrokerAsync(cancellationToken: cancellationToken); - - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - - Log.AcknowledgingMessage(s_logger, message.Id.Value, deliveryTag); + + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + + Log.AcknowledgingMessage(_logger, message.Id.Value, deliveryTag); await Channel.BasicAckAsync(deliveryTag, false, cancellationToken); } catch (Exception exception) { - Log.ErrorAcknowledgingMessage(s_logger, exception, message.Id.Value, deliveryTag); + Log.ErrorAcknowledgingMessage(_logger, exception, message.Id.Value, deliveryTag); throw; } } @@ -197,10 +204,11 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) { //Why bind a queue? Because we use purge to initialize a queue for RPC await EnsureChannelAsync(cancellationToken); - - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - Log.PurgingChannel(s_logger, _queueName.Value); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + + Log.PurgingChannel(_logger, _queueName.Value); try { @@ -218,11 +226,11 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) } catch (Exception exception) { - Log.ErrorPurgingChannel(s_logger, exception, _queueName.Value); + Log.ErrorPurgingChannel(_logger, exception, _queueName.Value); throw; } } - + /// /// Receives the specified queue name. /// @@ -233,7 +241,7 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) /// The timeout in milliseconds. We retry on timeout 5 ms intervals, with a min of 5ms /// until the timeout value is reached. /// Message. - public Message[] Receive(TimeSpan? timeOut = null) => BrighterAsyncContext.Run(() => ReceiveAsync(timeOut)); + public Message[] Receive(TimeSpan? timeOut = null) => BrighterAsyncContext.Run(() => ReceiveAsync(timeOut)); /// /// Receives the specified queue name. @@ -250,27 +258,31 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) try { await EnsureChannelAsync(cancellationToken); - - if (_consumer is null) throw new ChannelFailureException($"RmwMessageConsumer: consumer for {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - Log.RetrievingNextMessage(s_logger, _queueName.Value, + if (_consumer is null) + throw new ChannelFailureException($"RmwMessageConsumer: consumer for {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + + Log.RetrievingNextMessage(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); - + var (resultCount, results) = await _consumer.DeQueue(timeOut.Value, _batchSize); - if (results is not null && results.Length == 0) return [_noopMessage]; - + if (results is not null && results.Length == 0) + return [_noopMessage]; + var messages = new Message[resultCount]; for (var i = 0; i < resultCount; i++) { - var message = RmqMessageCreator.CreateMessage(results![i]); + var message = _messageCreator.CreateMessage(results![i]); messages[i] = message; - Log.ReceivedMessage(s_logger, _queueName.Value, + Log.ReceivedMessage(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), @@ -300,7 +312,7 @@ exception is NotSupportedException || return [_noopMessage]; // Default return in case of exception } - + /// /// Nacks the specified message, releasing it back to RabbitMQ for redelivery. /// Sync over Async @@ -320,14 +332,15 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken { await EnsureBrokerAsync(cancellationToken: cancellationToken); - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - Log.NackingMessage(s_logger, message.Id.Value, deliveryTag); + Log.NackingMessage(_logger, message.Id.Value, deliveryTag); await Channel.BasicNackAsync(deliveryTag, false, true, cancellationToken); } catch (Exception exception) { - Log.ErrorNackingMessage(s_logger, exception, message.Id.Value, deliveryTag); + Log.ErrorNackingMessage(_logger, exception, message.Id.Value, deliveryTag); throw; } } @@ -350,21 +363,22 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea try { await EnsureBrokerAsync(_queueName, cancellationToken: cancellationToken); - - if (Channel is null) throw new InvalidOperationException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - + + if (Channel is null) + throw new InvalidOperationException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + var reasonString = reason is null ? nameof(RejectionReason.DeliveryError) : reason.RejectionReason.ToString(); var description = reason is null ? "unknown" : reason.Description ?? "unknown"; - - Log.NoAckMessage(s_logger, message.Id.Value, message.DeliveryTag, reasonString, description); - + + Log.NoAckMessage(_logger, message.Id.Value, message.DeliveryTag, reasonString, description); + //if we have a DLQ, this will force over to the DLQ await Channel.BasicRejectAsync(message.DeliveryTag, false, cancellationToken); return true; } catch (Exception exception) { - Log.ErrorNoAckMessage(s_logger, exception, message.Id.Value); + Log.ErrorNoAckMessage(_logger, exception, message.Id.Value); throw; } } @@ -423,18 +437,19 @@ public async Task RequeueAsync(Message message, TimeSpan? timeout = null, try { - Log.RequeueingMessage(s_logger, message.Id.Value, timeout.Value.TotalMilliseconds); + Log.RequeueingMessage(_logger, message.Id.Value, timeout.Value.TotalMilliseconds); await EnsureChannelAsync(cancellationToken); - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); // Step 1: Publish the message back to the queue first. // This ordering ensures at-least-once delivery: if publish fails, the original remains unacked. // timeout is guaranteed non-null here due to the ??= TimeSpan.Zero coalescing at the top of this method if (DelaySupported || timeout <= TimeSpan.Zero) { - var rmqMessagePublisher = new RmqMessagePublisher(Channel, Connection); + var rmqMessagePublisher = new RmqMessagePublisher(Channel, Connection, LoggerFactory); await rmqMessagePublisher.RequeueMessageAsync(message, _queueName, timeout.Value, cancellationToken); } else @@ -447,18 +462,18 @@ public async Task RequeueAsync(Message message, TimeSpan? timeout = null, // If this fails after a successful publish, the message may be duplicated (not lost). // Consumers should be idempotent to handle potential duplicates. var deliveryTag = message.DeliveryTag; - Log.DeletingMessage(s_logger, message.Id.Value, deliveryTag); + Log.DeletingMessage(_logger, message.Id.Value, deliveryTag); await Channel.BasicAckAsync(deliveryTag, false, cancellationToken); return true; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value); return false; } } - + protected virtual async Task EnsureChannelAsync(CancellationToken cancellationToken = default) { if (Channel == null || Channel.IsClosed) @@ -480,12 +495,15 @@ protected virtual async Task EnsureChannelAsync(CancellationToken cancellationTo } await CreateConsumerAsync(cancellationToken); - - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - Log.CreatedChannel(s_logger, Channel.ChannelNumber, _queueName.Value, + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + + Log.CreatedChannel(_logger, Channel.ChannelNumber, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); @@ -507,13 +525,17 @@ private async Task CancelConsumerAsync(CancellationToken cancellationToken) private async Task CreateConsumerAsync(CancellationToken cancellationToken) { - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - - _consumer = new PullConsumer(Channel); - if (_consumer is null) throw new InvalidOperationException($"RmqMessageConsumer: consumer for {_queueName.Value} is null"); - + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + + _consumer = new PullConsumer(Channel, LoggerFactory); + if (_consumer is null) + throw new InvalidOperationException($"RmqMessageConsumer: consumer for {_queueName.Value} is null"); + await _consumer.SetChannelBatchSizeAsync(_batchSize); await Channel.BasicConsumeAsync(_queueName.Value, @@ -525,7 +547,7 @@ await Channel.BasicConsumeAsync(_queueName.Value, _consumer, cancellationToken: cancellationToken); - Log.CreatedConsumer(s_logger, _queueName.Value, + Log.CreatedConsumer(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); @@ -533,14 +555,17 @@ await Channel.BasicConsumeAsync(_queueName.Value, private async Task CreateQueueAsync(CancellationToken cancellationToken) { - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - - Log.CreatingQueue(s_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + + Log.CreatingQueue(_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); await Channel.QueueDeclareAsync(_queueName.Value, _isDurable, false, false, SetQueueArguments(), cancellationToken: cancellationToken); - + if (_hasDlq) { await Channel.QueueDeclareAsync(_deadLetterQueueName!.Value, _isDurable, false, false, @@ -550,10 +575,13 @@ await Channel.QueueDeclareAsync(_deadLetterQueueName!.Value, _isDurable, false, private async Task BindQueueAsync(CancellationToken cancellationToken) { - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + foreach (var key in _routingKeys) { await Channel.QueueBindAsync(_queueName.Value, Connection.Exchange.Name, key.Value, @@ -569,25 +597,31 @@ await Channel.QueueBindAsync(_deadLetterQueueName!.Value, GetDeadletterExchangeN private async Task HandleExceptionAsync(Exception exception, bool resetConnection = false, CancellationToken cancellationToken = default) { - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null", exception); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null", exception); - - Log.ErrorListeningToQueue(s_logger, exception, _queueName.Value, + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null", exception); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null", exception); + + Log.ErrorListeningToQueue(_logger, exception, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); - - if (resetConnection) await ResetConnectionToBrokerAsync(cancellationToken); + + if (resetConnection) + await ResetConnectionToBrokerAsync(cancellationToken); throw new ChannelFailureException("Error connecting to RabbitMQ, see inner exception for details", exception); } private async Task ValidateQueueAsync(CancellationToken cancellationToken) { - if (Channel is null) throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - if (Connection.AmpqUri is null) throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageConsumer: channel {_queueName.Value} is null"); + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + if (Connection.AmpqUri is null) + throw new ConfigurationException($"RmqMessageConsumer: ampqUri for {_queueName.Value} is null"); - Log.ValidatingQueue(s_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); + Log.ValidatingQueue(_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); try { @@ -602,13 +636,13 @@ private async Task ValidateQueueAsync(CancellationToken cancellationToken) private Dictionary SetQueueArguments() { var arguments = new Dictionary(); - + // Set queue type for quorum queues if (_queueType == QueueType.Quorum) { arguments.Add("x-queue-type", "quorum"); } - + if (_highAvailability) { // Only work for RabbitMQ Server version before 3.0 @@ -641,7 +675,7 @@ private void EnsureProducer() { #pragma warning disable CS0420 // LazyInitializer handles the memory barrier for the volatile field LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, - ref _requeueProducerLock, () => new RmqMessageProducer(Connection) + ref _requeueProducerLock, () => new RmqMessageProducer(Connection, loggerFactory: LoggerFactory) { Scheduler = _scheduler }); @@ -651,8 +685,9 @@ private void EnsureProducer() private string GetDeadletterExchangeName() { //never likely to happen as caller will generally have asserted this - if (Connection.Exchange is null) throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); - + if (Connection.Exchange is null) + throw new ConfigurationException($"RmqMessageConsumer: exchange for {_queueName.Value} is null"); + return Connection.DeadLetterExchange is not null ? Connection.DeadLetterExchange.Name : Connection.Exchange.Name; } @@ -671,7 +706,8 @@ public override void Dispose() public override async ValueTask DisposeAsync() { await CancelConsumerAsync(CancellationToken.None); - if (_requeueProducer != null) await _requeueProducer.DisposeAsync(); + if (_requeueProducer != null) + await _requeueProducer.DisposeAsync(); await base.DisposeAsync(); GC.SuppressFinalize(this); } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumerFactory.cs index bb74d35498..010e7366f3 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumerFactory.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Toby Henderson @@ -22,11 +22,14 @@ THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.RMQ.Async { public class RmqMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly RmqMessagingGatewayConnection _rmqConnection; + private readonly ILoggerFactory _loggerFactory; private IAmAMessageScheduler? _scheduler; /// @@ -44,10 +47,12 @@ public IAmAMessageScheduler? Scheduler /// /// The subscription to the broker hosting the queue /// Optional scheduler for delayed requeue operations - public RmqMessageConsumerFactory(RmqMessagingGatewayConnection rmqConnection, IAmAMessageScheduler? scheduler = null) + /// The used to create loggers for the consumers + public RmqMessageConsumerFactory(RmqMessagingGatewayConnection rmqConnection, ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null) { _rmqConnection = rmqConnection; _scheduler = scheduler; + _loggerFactory = loggerFactory; } /// @@ -72,6 +77,7 @@ public IAmAMessageConsumerSync Create(Subscription subscription) rmqSubscription.ChannelName, //RMQ Queue Name rmqSubscription.RoutingKey, rmqSubscription.IsDurable, + _loggerFactory, rmqSubscription.HighAvailability, rmqSubscription.BufferSize, rmqSubscription.DeadLetterChannelName, @@ -94,6 +100,7 @@ public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) rmqSubscription.ChannelName, //RMQ Queue Name rmqSubscription.RoutingKey, rmqSubscription.IsDurable, + _loggerFactory, rmqSubscription.HighAvailability, rmqSubscription.BufferSize, rmqSubscription.DeadLetterChannelName, diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageCreator.cs index 9701cae16d..a72405350b 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageCreator.cs @@ -30,7 +30,6 @@ THE SOFTWARE. */ using System.Text; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -39,9 +38,14 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; internal sealed partial class RmqMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; - public static Message CreateMessage(BasicDeliverEventArgs fromQueue) + public RmqMessageCreator(ILogger logger) + { + _logger = logger; + } + + public Message CreateMessage(BasicDeliverEventArgs fromQueue) { var headers = fromQueue.BasicProperties.Headers ?? new Dictionary(); var topic = HeaderResult.Empty(); @@ -54,7 +58,7 @@ public static Message CreateMessage(BasicDeliverEventArgs fromQueue) messageId = ReadMessageId(fromQueue.BasicProperties.MessageId); var messageHeader = CreateMessageHeader(fromQueue, headers, topic, messageId); - var bodyType = new ContentType(fromQueue.BasicProperties.Type ?? MediaTypeNames.Text.Plain); + var bodyType = new ContentType(fromQueue.BasicProperties.Type ?? MediaTypeNames.Text.Plain); message = new Message(messageHeader, new MessageBody(fromQueue.Body, bodyType)); ProcessHeaderBag(headers, message); @@ -62,14 +66,14 @@ public static Message CreateMessage(BasicDeliverEventArgs fromQueue) } catch (Exception e) { - Log.FailedToCreateMessageFromAmqpMessage(s_logger, e); + Log.FailedToCreateMessageFromAmqpMessage(_logger, e); message = Message.FailureMessage(topic.Result, messageId.Result); } return message; } - private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue, IDictionary headers, + private MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue, IDictionary headers, HeaderResult topic, HeaderResult messageId) { var timeStamp = ReadTimeStamp(fromQueue.BasicProperties); @@ -92,8 +96,8 @@ private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue if (false == (messageType.Success && timeStamp.Success && handledCount.Success)) throw new InvalidOperationException("Required message header values are missing"); - - var contentType = new ContentType(fromQueue.BasicProperties.ContentType ?? MediaTypeNames.Text.Plain); + + var contentType = new ContentType(fromQueue.BasicProperties.ContentType ?? MediaTypeNames.Text.Plain); return new MessageHeader( messageId: messageId.Result ?? string.Empty, @@ -115,12 +119,12 @@ private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue ); } - private static void ProcessHeaderBag(IDictionary headers, Message message) + private void ProcessHeaderBag(IDictionary headers, Message message) { headers.Each(header => message.Header.Bag.Add(header.Key, ParseHeaderValue(header.Value))); } - private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message) + private void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message) { var deliveryTag = ReadDeliveryTag(fromQueue.DeliveryTag); var redelivered = ReadRedeliveredFlag(fromQueue.Redelivered); @@ -130,7 +134,7 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message.Persist = fromQueue.BasicProperties.DeliveryMode == DeliveryModes.Persistent; } - private static HeaderResult ReadHeader(IDictionary dict, string key, bool dieOnMissing = false) + private HeaderResult ReadHeader(IDictionary dict, string key, bool dieOnMissing = false) { if (false == dict.TryGetValue(key, out object? value)) { @@ -139,7 +143,7 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message if (!(value is byte[] bytes)) { - Log.HeaderValueCouldNotBeCastToByteArray(s_logger, key); + Log.HeaderValueCouldNotBeCastToByteArray(_logger, key); return new HeaderResult(null, false); } @@ -151,12 +155,12 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message catch (Exception e) { var firstTwentyBytes = BitConverter.ToString(bytes.Take(20).ToArray()); - Log.FailedToReadHeaderValueAsUtf8(s_logger, key, firstTwentyBytes, e); + Log.FailedToReadHeaderValueAsUtf8(_logger, key, firstTwentyBytes, e); return new HeaderResult(null, false); } } - private static HeaderResult ReadCorrelationId(IDictionary headers) + private HeaderResult ReadCorrelationId(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CORRELATION_ID, out object? correlationHeader)) { @@ -167,12 +171,12 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message return new HeaderResult(null, false); } - private static HeaderResult ReadDeliveryTag(ulong deliveryTag) + private HeaderResult ReadDeliveryTag(ulong deliveryTag) { return new HeaderResult(deliveryTag, true); } - private static HeaderResult ReadTimeStamp(IReadOnlyBasicProperties basicProperties) + private HeaderResult ReadTimeStamp(IReadOnlyBasicProperties basicProperties) { if (basicProperties.IsTimestampPresent()) { @@ -190,7 +194,7 @@ private static HeaderResult ReadTimeStamp(IReadOnlyBasicProperti return new HeaderResult(DateTimeOffset.UtcNow, true); } - private static HeaderResult ReadMessageType(IDictionary headers) + private HeaderResult ReadMessageType(IDictionary headers) { return ReadHeader(headers, HeaderNames.MESSAGE_TYPE) .Map(s => @@ -205,7 +209,7 @@ private static HeaderResult ReadMessageType(IDictionary ReadHandledCount(IDictionary headers) + private HeaderResult ReadHandledCount(IDictionary headers) { if (headers.TryGetValue(HeaderNames.HANDLED_COUNT, out object? header) == false) { @@ -215,10 +219,10 @@ private static HeaderResult ReadHandledCount(IDictionary h switch (header) { case byte[] value: - { - var val = int.TryParse(Encoding.UTF8.GetString(value), out var handledCount) ? handledCount : 0; - return new HeaderResult(val, true); - } + { + var val = int.TryParse(Encoding.UTF8.GetString(value), out var handledCount) ? handledCount : 0; + return new HeaderResult(val, true); + } case int value: return new HeaderResult(value, true); default: @@ -226,7 +230,7 @@ private static HeaderResult ReadHandledCount(IDictionary h } } - private static HeaderResult ReadDelay(IDictionary headers) + private HeaderResult ReadDelay(IDictionary headers) { if (headers.TryGetValue(HeaderNames.DELAYED_MILLISECONDS, out var delayedMsHeader) == false) { @@ -241,34 +245,34 @@ private static HeaderResult ReadDelay(IDictionary hea switch (delayedMsHeader) { case byte[] value: - { - if (!int.TryParse(Encoding.UTF8.GetString(value), out var handledCount)) - delayedMilliseconds = 0; - else { - if (handledCount < 0) - handledCount = Math.Abs(handledCount); - delayedMilliseconds = handledCount; + if (!int.TryParse(Encoding.UTF8.GetString(value), out var handledCount)) + delayedMilliseconds = 0; + else + { + if (handledCount < 0) + handledCount = Math.Abs(handledCount); + delayedMilliseconds = handledCount; + } + + break; } - - break; - } case int value: - { - if (value < 0) - value = Math.Abs(value); + { + if (value < 0) + value = Math.Abs(value); - delayedMilliseconds = value; - break; - } + delayedMilliseconds = value; + break; + } case long value: - { - if (value < 0) - value = Math.Abs(value); + { + if (value < 0) + value = Math.Abs(value); - delayedMilliseconds = (int)value; - break; - } + delayedMilliseconds = (int)value; + break; + } default: return new HeaderResult(TimeSpan.Zero, false); } @@ -276,7 +280,7 @@ private static HeaderResult ReadDelay(IDictionary hea return new HeaderResult(TimeSpan.FromMilliseconds(delayedMilliseconds), true); } - private static HeaderResult ReadTopic(BasicDeliverEventArgs fromQueue, IDictionary headers) + private HeaderResult ReadTopic(BasicDeliverEventArgs fromQueue, IDictionary headers) { var res = ReadHeader(headers, HeaderNames.TOPIC).Map(s => { @@ -288,28 +292,28 @@ private static HeaderResult ReadDelay(IDictionary hea { return res; } - + return new HeaderResult(new RoutingKey(fromQueue.RoutingKey), true); } - private static HeaderResult ReadMessageId(string? messageId) + private HeaderResult ReadMessageId(string? messageId) { if (string.IsNullOrEmpty(messageId)) { var newMessageId = Id.Random(); - Log.NoMessageIdFoundInMessage(s_logger, newMessageId.Value); + Log.NoMessageIdFoundInMessage(_logger, newMessageId.Value); return new HeaderResult(newMessageId, true); } return new HeaderResult(Id.Create(messageId), true); } - private static HeaderResult ReadRedeliveredFlag(bool redelivered) + private HeaderResult ReadRedeliveredFlag(bool redelivered) { return new HeaderResult(redelivered, true); } - private static HeaderResult ReadReplyTo(IReadOnlyBasicProperties basicProperties) + private HeaderResult ReadReplyTo(IReadOnlyBasicProperties basicProperties) { if (basicProperties.IsReplyToPresent()) { @@ -319,7 +323,7 @@ private static HeaderResult ReadRedeliveredFlag(bool redelivered) return new HeaderResult(null, true); } - private static HeaderResult ReadSource(IDictionary headers) + private HeaderResult ReadSource(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SOURCE, out var source) && source is byte[] val @@ -331,7 +335,7 @@ private static HeaderResult ReadSource(IDictionary headers return new HeaderResult(new Uri(MessageHeader.DefaultSource), true); } - private static HeaderResult ReadType(IDictionary headers) + private HeaderResult ReadType(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TYPE, out var type) && type is byte[] typeArray) @@ -342,7 +346,7 @@ private static HeaderResult ReadType(IDictionary(CloudEventsType.Empty, true); } - private static HeaderResult ReadSubject(IDictionary headers) + private HeaderResult ReadSubject(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SUBJECT, out var subject) && subject is byte[] subjectArray) @@ -353,7 +357,7 @@ private static HeaderResult ReadType(IDictionary(null, true); } - private static HeaderResult ReadDataSchema(IDictionary headers) + private HeaderResult ReadDataSchema(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_DATA_SCHEMA, out var dataSchema) && dataSchema is byte[] dataSchemaArray @@ -365,7 +369,7 @@ private static HeaderResult ReadType(IDictionary(null, true); } - private static HeaderResult ReadTraceParent(IDictionary headers) + private HeaderResult ReadTraceParent(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_PARENT, out var traceParent) && traceParent is byte[] traceParentArray) @@ -376,7 +380,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static HeaderResult ReadTraceState(IDictionary headers) + private HeaderResult ReadTraceState(IDictionary headers) { object? traceState = null; if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_STATE, out traceState) @@ -384,7 +388,7 @@ private static HeaderResult ReadType(IDictionary(Encoding.UTF8.GetString(traceParentArray), true); } - + #pragma warning disable CS0618 // Type or member is obsolete if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_STATE_DEPRECATED, out traceState) #pragma warning restore CS0618 // Type or member is obsolete @@ -396,7 +400,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static HeaderResult ReadBaggage(IDictionary headers) + private HeaderResult ReadBaggage(IDictionary headers) { if (headers.TryGetValue(HeaderNames.W3C_BAGGAGE, out var traceParent) && traceParent is byte[] traceParentArray) @@ -407,7 +411,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static object ParseHeaderValue(object? value) + private object ParseHeaderValue(object? value) { if (value == null) return string.Empty; diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGateway.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGateway.cs index 0d09049b12..f2135647e3 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGateway.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGateway.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; using Polly; using RabbitMQ.Client; @@ -54,11 +53,12 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; /// public partial class RmqMessageGateway : IDisposable, IAsyncDisposable { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly AsyncPolicy _circuitBreakerPolicy; private readonly ConnectionFactory _connectionFactory; private readonly AsyncPolicy _retryPolicy; private int _disposed; + protected readonly ILoggerFactory LoggerFactory; protected readonly RmqMessagingGatewayConnection Connection; protected IChannel? Channel; @@ -67,16 +67,20 @@ public partial class RmqMessageGateway : IDisposable, IAsyncDisposable /// Use if you need to inject a test logger /// /// The amqp uri and exchange to connect to - protected RmqMessageGateway(RmqMessagingGatewayConnection connection) + /// The used to create a logger. + protected RmqMessageGateway(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { + LoggerFactory = loggerFactory; + _logger = LoggerFactory.CreateLogger(); Connection = connection; - var connectionPolicyFactory = new ConnectionPolicyFactory(Connection); + var connectionPolicyFactory = new ConnectionPolicyFactory(Connection, LoggerFactory); _retryPolicy = connectionPolicyFactory.RetryPolicyAsync; _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicyAsync; - if (Connection.AmpqUri is null) throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); + if (Connection.AmpqUri is null) + throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); _connectionFactory = new ConnectionFactory { @@ -88,7 +92,8 @@ protected RmqMessageGateway(RmqMessagingGatewayConnection connection) // Configure SSL/TLS for mutual authentication if certificate is provided RmqTlsConfigurator.ConfigureIfEnabled(_connectionFactory, connection); - if (Connection.Exchange is null) throw new InvalidOperationException("RMQMessagingGateway: No Exchange specified"); + if (Connection.Exchange is null) + throw new InvalidOperationException("RMQMessagingGateway: No Exchange specified"); DelaySupported = Connection.Exchange.SupportDelay; } @@ -140,15 +145,16 @@ protected virtual async Task ConnectToBrokerAsync(OnMissingChannel makeExchange, { if (Channel == null || Channel.IsClosed) { - var connection = await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat) + var connection = await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory) .GetConnectionAsync(_connectionFactory, cancellationToken); - if (Connection.AmpqUri is null) throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); + if (Connection.AmpqUri is null) + throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); connection.ConnectionBlockedAsync += HandleBlockedAsync; connection.ConnectionUnblockedAsync += HandleUnBlockedAsync; - Log.OpeningChannelToRabbitMq(s_logger, Connection.AmpqUri.GetSanitizedUri()); + Log.OpeningChannelToRabbitMq(_logger, Connection.AmpqUri.GetSanitizedUri()); Channel = await connection.CreateChannelAsync( new CreateChannelOptions( @@ -163,24 +169,26 @@ protected virtual async Task ConnectToBrokerAsync(OnMissingChannel makeExchange, private Task HandleBlockedAsync(object sender, ConnectionBlockedEventArgs args) { - if (Connection.AmpqUri is null) throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); + if (Connection.AmpqUri is null) + throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); - Log.SubscriptionBlocked(s_logger, Connection.AmpqUri.GetSanitizedUri(), args.Reason); + Log.SubscriptionBlocked(_logger, Connection.AmpqUri.GetSanitizedUri(), args.Reason); return Task.CompletedTask; } private Task HandleUnBlockedAsync(object sender, AsyncEventArgs args) { - if (Connection.AmpqUri is null) throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); + if (Connection.AmpqUri is null) + throw new ConfigurationException("RMQMessagingGateway: No AMPQ URI specified"); - Log.SubscriptionUnblocked(s_logger, Connection.AmpqUri.GetSanitizedUri()); + Log.SubscriptionUnblocked(_logger, Connection.AmpqUri.GetSanitizedUri()); return Task.CompletedTask; } protected async Task ResetConnectionToBrokerAsync(CancellationToken cancellationToken = default) { - await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).ResetConnectionAsync(_connectionFactory, cancellationToken); + await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).ResetConnectionAsync(_connectionFactory, cancellationToken); } ~RmqMessageGateway() @@ -190,7 +198,8 @@ protected async Task ResetConnectionToBrokerAsync(CancellationToken cancellation public virtual async ValueTask DisposeAsync() { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; if (Channel != null) { @@ -199,12 +208,13 @@ public virtual async ValueTask DisposeAsync() Channel = null; } - await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).RemoveConnectionAsync(_connectionFactory); + await new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).RemoveConnectionAsync(_connectionFactory); } protected virtual void Dispose(bool disposing) { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; if (disposing) { @@ -212,7 +222,7 @@ protected virtual void Dispose(bool disposing) Channel?.Dispose(); Channel = null; - new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).RemoveConnectionAsync(_connectionFactory) + new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).RemoveConnectionAsync(_connectionFactory) .GetAwaiter() .GetResult(); } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGatewayConnectionPool.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGatewayConnectionPool.cs index 9d7c6b37be..e42348f087 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGatewayConnectionPool.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGatewayConnectionPool.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -39,12 +38,12 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; /// /// Class MessageGatewayConnectionPool. /// -public partial class RmqMessageGatewayConnectionPool(string connectionName, ushort connectionHeartbeat) +public partial class RmqMessageGatewayConnectionPool(string connectionName, ushort connectionHeartbeat, ILoggerFactory loggerFactory) { private static readonly Dictionary s_connectionPool = new(); private static readonly SemaphoreSlim s_lock = new SemaphoreSlim(1, 1); - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private static readonly Random jitter = new Random(); /// @@ -85,29 +84,29 @@ public async Task GetConnectionAsync(ConnectionFactory connectionFa } } - public async Task ResetConnectionAsync(ConnectionFactory connectionFactory, CancellationToken cancellationToken = default) - { - await s_lock.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - await DelayReconnectingAsync().ConfigureAwait(false); - - try - { - await CreateConnectionAsync(connectionFactory, cancellationToken).ConfigureAwait(false); - } - catch (BrokerUnreachableException exception) - { - Log.FailedToResetSubscriptionToRabbitMqEndpoint(s_logger, connectionFactory.Endpoint, exception); - } - } - finally - { - s_lock.Release(); - } - } - + public async Task ResetConnectionAsync(ConnectionFactory connectionFactory, CancellationToken cancellationToken = default) + { + await s_lock.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + await DelayReconnectingAsync().ConfigureAwait(false); + + try + { + await CreateConnectionAsync(connectionFactory, cancellationToken).ConfigureAwait(false); + } + catch (BrokerUnreachableException exception) + { + Log.FailedToResetSubscriptionToRabbitMqEndpoint(_logger, connectionFactory.Endpoint, exception); + } + } + finally + { + s_lock.Release(); + } + } + /// /// Remove the connection from the pool /// @@ -133,7 +132,7 @@ private async Task CreateConnectionAsync(ConnectionFactory con await TryRemoveConnectionAsync(connectionId).ConfigureAwait(false); - Log.CreatingSubscriptionToRabbitMqEndpoint(s_logger, connectionFactory.Endpoint); + Log.CreatingSubscriptionToRabbitMqEndpoint(_logger, connectionFactory.Endpoint); connectionFactory.RequestedHeartbeat = TimeSpan.FromSeconds(connectionHeartbeat); connectionFactory.RequestedConnectionTimeout = TimeSpan.FromMilliseconds(5000); @@ -142,12 +141,12 @@ private async Task CreateConnectionAsync(ConnectionFactory con var connection = await connectionFactory.CreateConnectionAsync(connectionName, cancellationToken).ConfigureAwait(false); - Log.NewConnectedToAddedToPool(s_logger, connection.Endpoint, connection.ClientProvidedName); + Log.NewConnectedToAddedToPool(_logger, connection.Endpoint, connection.ClientProvidedName); async Task ShutdownHandler(object sender, ShutdownEventArgs e) { - Log.SubscriptionHasBeenShutdown(s_logger, connection.Endpoint, e.ToString()); + Log.SubscriptionHasBeenShutdown(_logger, connection.Endpoint, e.ToString()); try { @@ -180,7 +179,7 @@ async Task ShutdownHandler(object sender, ShutdownEventArgs e) return pooledConnection; } - + private static async Task DelayReconnectingAsync() => await Task.Delay(jitter.Next(5, 100)).ConfigureAwait(false); private async Task TryRemoveConnectionAsync(string connectionId) diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducer.cs index 2fd7a78f57..1e6892758e 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducer.cs @@ -33,7 +33,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; using RabbitMQ.Client; @@ -49,7 +48,7 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; public partial class RmqMessageProducer : RmqMessageGateway, IAmAMessageProducerSync, IAmAMessageProducerAsync, ISupportPublishConfirmation, ISupportPublishConfirmationAsync { private readonly InstrumentationOptions _instrumentationOptions; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; // Used to bound the active-send wait when the user opts out of confirms (timeout=0). // Active sends in flight at dispose time should not be aborted: outbox would mark them Dispatched @@ -100,7 +99,7 @@ public Publication Publication /// The OTel Span we are writing Producer events too /// public Activity? Span { get; set; } - + /// /// The /// @@ -111,9 +110,10 @@ public Publication Publication /// /// The subscription information needed to talk to RMQ /// The for how deep should the instrumentation go? + /// The used to create a logger. /// Make Channels = Create - public RmqMessageProducer(RmqMessagingGatewayConnection connection, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) - : this(connection, new RmqPublication { MakeChannels = OnMissingChannel.Create }) + public RmqMessageProducer(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) + : this(connection, new RmqPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory) { _instrumentationOptions = instrumentationOptions; } @@ -125,9 +125,11 @@ public RmqMessageProducer(RmqMessagingGatewayConnection connection, Instrumentat /// How should we configure this producer. If not provided use default behaviours: /// Make Channels = Create /// - public RmqMessageProducer(RmqMessagingGatewayConnection connection, RmqPublication? publication) - : base(connection) + /// The used to create a logger. + public RmqMessageProducer(RmqMessagingGatewayConnection connection, RmqPublication? publication, ILoggerFactory loggerFactory) + : base(connection, loggerFactory) { + _logger = loggerFactory.CreateLogger(); _publication = publication ?? new RmqPublication { MakeChannels = OnMissingChannel.Create }; _waitForConfirmsTimeOutInMilliseconds = _publication.WaitForConfirmsTimeOutInMilliseconds; } @@ -158,7 +160,7 @@ public RmqMessageProducer(RmqMessagingGatewayConnection connection, RmqPublicati /// public async Task SendWithDelayAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken = default) => await SendWithDelayAsync(message, delay, true, cancellationToken); - + private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool useSchedulerAsync, CancellationToken cancellationToken = default) { // Capture the ambient publish context synchronously, before any await or child activity, so the @@ -175,17 +177,20 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use try { - if (Connection.Exchange is null) throw new ConfigurationException("RmqMessageProducer: Exchange is not set"); - if (Connection.AmpqUri is null) throw new ConfigurationException("RmqMessageProducer: Broker URL is not set"); + if (Connection.Exchange is null) + throw new ConfigurationException("RmqMessageProducer: Exchange is not set"); + if (Connection.AmpqUri is null) + throw new ConfigurationException("RmqMessageProducer: Broker URL is not set"); delay ??= TimeSpan.Zero; - Log.PreparingToSendAsync(s_logger, Connection.Exchange.Name); + Log.PreparingToSendAsync(_logger, Connection.Exchange.Name); var channelInitialized = Channel is not null; await EnsureBrokerAsync(makeExchange: _publication.MakeChannels, cancellationToken: cancellationToken); - if (Channel is null) throw new ChannelFailureException($"RmqMessageProducer: Channel is not set for {_publication.Topic}"); + if (Channel is null) + throw new ChannelFailureException($"RmqMessageProducer: Channel is not set for {_publication.Topic}"); if (!channelInitialized) { Channel.BasicAcksAsync += OnPublishSucceeded; @@ -196,12 +201,12 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use BrighterTracer.WriteProducerEvent(Span, MessagingSystem.RabbitMQ, message, _instrumentationOptions); - Log.PublishingMessageAsync(s_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay.Value.TotalMilliseconds, + Log.PublishingMessageAsync(_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay.Value.TotalMilliseconds, message.Header.Topic.Value, message.Persist, message.Id.Value, message.Body.Value); if (PublishesOnChannel(delay.Value)) { - var rmqMessagePublisher = new RmqMessagePublisher(Channel, Connection); + var rmqMessagePublisher = new RmqMessagePublisher(Channel, Connection, LoggerFactory); var deliveryTag = await Channel.GetNextPublishSequenceNumberAsync(cancellationToken); AddPendingConfirmation(deliveryTag, new PendingConfirmation(message.Id, message.Header.Topic, publishContext)); pendingDeliveryTag = deliveryTag; @@ -220,13 +225,13 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use schedulerSync.Schedule(message, delay.Value); } - Log.PublishedMessageAsync(s_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay, + Log.PublishedMessageAsync(_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay, message.Header.Topic.Value, message.Persist, message.Id.Value, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), DateTime.UtcNow); } catch (IOException io) { - Log.ErrorTalkingToSocketAsync(s_logger, io, Connection.AmpqUri!.GetSanitizedUri()); + Log.ErrorTalkingToSocketAsync(_logger, io, Connection.AmpqUri!.GetSanitizedUri()); ClearPendingConfirmations(); // ClearPendingConfirmations removed the orphan; suppress the per-tag cleanup in finally. pendingDeliveryTag = null; @@ -255,7 +260,8 @@ private async Task SendWithDelayAsync(Message message, TimeSpan? delay, bool use public sealed override void Dispose() { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; WaitForActiveSends(); WaitForPendingPublisherConfirmations(); @@ -280,7 +286,8 @@ public sealed override void Dispose() public sealed override async ValueTask DisposeAsync() { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; await WaitForActiveSendsAsync(); await WaitForPendingPublisherConfirmationsAsync(); @@ -368,7 +375,7 @@ private async Task WaitForActiveSendsAsync() if (activeSends == 0) return; - Log.FailedToAwaitActiveSends(s_logger, activeSends, waitMilliseconds); + Log.FailedToAwaitActiveSends(_logger, activeSends, waitMilliseconds); } private void WaitForPendingPublisherConfirmations() => BrighterAsyncContext.Run(WaitForPendingPublisherConfirmationsAsync); @@ -414,10 +421,10 @@ private async Task WaitForPendingPublisherConfirmationsAsync() } if (pendingConfirmations > 0) - Log.FailedToAwaitPublisherConfirms(s_logger, pendingConfirmations, waitMilliseconds); + Log.FailedToAwaitPublisherConfirms(_logger, pendingConfirmations, waitMilliseconds); if (inFlightCallbacks > 0) - Log.FailedToAwaitConfirmationCallbacks(s_logger, inFlightCallbacks, waitMilliseconds); + Log.FailedToAwaitConfirmationCallbacks(_logger, inFlightCallbacks, waitMilliseconds); } private void AddPendingConfirmation(ulong deliveryTag, PendingConfirmation confirmation) @@ -540,9 +547,9 @@ private async Task SettleConfirmationsAsync(ulong deliveryTag, bool multiple, bo foreach (var confirmation in RemovePendingConfirmations(deliveryTag, multiple, beginCallbacks: true)) { if (success) - Log.PublishedMessage(s_logger, confirmation.MessageId.Value); + Log.PublishedMessage(_logger, confirmation.MessageId.Value); else - Log.FailedToPublishMessageAsync(s_logger, confirmation.MessageId.Value); + Log.FailedToPublishMessageAsync(_logger, confirmation.MessageId.Value); raiseTasks.Add(RaiseConfirmationCallbacksAsync(new PublishConfirmationResult(success, confirmation.MessageId, confirmation.Topic, confirmation.Context))); } @@ -562,7 +569,7 @@ private async Task RaiseConfirmationCallbacksAsync(PublishConfirmationResult res } catch (Exception ex) { - Log.ConfirmationCallbackFault(s_logger, result.MessageId.Value, ex); + Log.ConfirmationCallbackFault(_logger, result.MessageId.Value, ex); } finally { @@ -583,7 +590,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "RmqMessageProducer: Error talking to the socket on {URL}, resetting subscription")] public static partial void ErrorTalkingToSocketAsync(ILogger logger, Exception exception, string url); - + [LoggerMessage(LogLevel.Debug, "Failed to publish message: {MessageId}")] public static partial void FailedToPublishMessageAsync(ILogger logger, string messageId); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducerFactory.cs index 4fc906555d..efffa9e673 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducerFactory.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.RMQ.Async { @@ -34,9 +35,11 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async /// /// The connection to use to connect to RabbitMQ /// The publications describing the RabbitMQ topics that we want to use + /// The used to create loggers for the producers public class RmqMessageProducerFactory( RmqMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) : IAmAMessageProducerFactory { /// @@ -51,7 +54,7 @@ public Dictionary Create() { if (publication.Topic is null) throw new ConfigurationException("RmqMessageProducerFactory.Create => An RmqPublication must have a topic/routing key"); - var messageProducer = new RmqMessageProducer(connection, publication); + var messageProducer = new RmqMessageProducer(connection, publication, loggerFactory); messageProducer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); if (producers.ContainsKey(producerKey)) diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessagePublisher.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessagePublisher.cs index 00400e3864..2bc147df9d 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessagePublisher.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessagePublisher.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using RabbitMQ.Client; namespace Paramore.Brighter.MessagingGateway.RMQ.Async; @@ -42,7 +41,7 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async; /// internal sealed partial class RmqMessagePublisher { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private static readonly HashSet _headersToReset = [ @@ -62,12 +61,13 @@ internal sealed partial class RmqMessagePublisher /// /// The channel. /// The exchange we want to talk to. + /// The used to create a logger. /// /// channel /// or /// exchangeName /// - public RmqMessagePublisher(IChannel channel, RmqMessagingGatewayConnection connection) + public RmqMessagePublisher(IChannel channel, RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { if (channel is null) { @@ -79,6 +79,8 @@ public RmqMessagePublisher(IChannel channel, RmqMessagingGatewayConnection conne throw new ArgumentNullException(nameof(connection)); } + _logger = loggerFactory.CreateLogger(); + _connection = connection; _channel = channel; @@ -131,7 +133,7 @@ public async Task RequeueMessageAsync(Message message, ChannelName queueName, Ti var messageId = Uuid.NewAsString(); const string deliveryTag = "1"; - Log.RegeneratingMessage(s_logger, message.Id.Value, deliveryTag, messageId, 1); + Log.RegeneratingMessage(_logger, message.Id.Value, deliveryTag, messageId, 1); Dictionary headers = AddCloudEventsHeaders(message); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqProducerRegistryFactory.cs index ecc786b6a3..06896ca26e 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqProducerRegistryFactory.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.RMQ.Async { @@ -10,7 +11,8 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Async /// public class RmqProducerRegistryFactory( RmqMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) : IAmAProducerRegistryFactory { /// @@ -19,7 +21,7 @@ public class RmqProducerRegistryFactory( /// A has of middleware clients by topic, for sending messages to the middleware public IAmAProducerRegistry Create() { - var producerFactory = new RmqMessageProducerFactory(connection, publications); + var producerFactory = new RmqMessageProducerFactory(connection, publications, loggerFactory); return new ProducerRegistry(producerFactory.Create()); } @@ -30,7 +32,7 @@ public IAmAProducerRegistry Create() /// A has of middleware clients by topic, for sending messages to the middleware public Task CreateAsync(CancellationToken ct = default) { - return Task.FromResult(Create()); + return Task.FromResult(Create()); } } } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/ConnectionPoolFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/ConnectionPoolFactory.cs index 9600423173..880e0c4358 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/ConnectionPoolFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/ConnectionPoolFactory.cs @@ -24,7 +24,6 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Polly; using RabbitMQ.Client.Exceptions; @@ -35,28 +34,31 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// public partial class ConnectionPolicyFactory { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// - public ConnectionPolicyFactory() - : this(new RmqMessagingGatewayConnection()) - {} + public ConnectionPolicyFactory(ILoggerFactory loggerFactory) + : this(new RmqMessagingGatewayConnection(), loggerFactory) + { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Use if you need to inject a test logger /// /// - public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection) + /// The used to create a logger. + public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { + _logger = loggerFactory.CreateLogger(); + if (connection.AmpqUri is null) throw new ConfigurationException("ConnectionPolicyFactory ctor: RmqMessagingGatewayConnection.AmpqUri is not set"); - + if (connection.Exchange is null) throw new ConfigurationException("ConnectionPolicyFactory ctor: RmqMessagingGatewayConnection.Exchange is not set"); - + var retries = connection.AmpqUri.ConnectionRetryCount; var retryWaitInMilliseconds = connection.AmpqUri.RetryWaitInMilliseconds; var circuitBreakerTimeout = connection.AmpqUri.CircuitBreakTimeInMilliseconds; @@ -71,13 +73,13 @@ public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection) { if (exception is BrokerUnreachableException) { - Log.BrokerUnreachableException(s_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri(), retries); + Log.BrokerUnreachableException(_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri(), retries); } else { - Log.ExceptionOnSubscription(s_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri()); + Log.ExceptionOnSubscription(_logger, exception, context["queueName"].ToString(), connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri()); - throw new ChannelFailureException($"RMQMessagingGateway: Exception on subscription to queue { context["queueName"]} via exchange {connection.Exchange.Name} on subscription {connection.AmpqUri.GetSanitizedUri()}", exception); + throw new ChannelFailureException($"RMQMessagingGateway: Exception on subscription to queue {context["queueName"]} via exchange {connection.Exchange.Name} on subscription {connection.AmpqUri.GetSanitizedUri()}", exception); } }); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/PullConsumer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/PullConsumer.cs index 5013a06af8..c9eaab18f2 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/PullConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/PullConsumer.cs @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Collections.Concurrent; using System.Threading; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -35,15 +34,17 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync { public partial class PullConsumer : DefaultBasicConsumer { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + private readonly ILogger _logger; + //we do end up creating a second buffer to the Brighter Channel, but controlling the flow from RMQ depends //on us being able to buffer up to the set QoS and then pull. This matches other implementations. private readonly ConcurrentQueue _messages = new ConcurrentQueue(); - public PullConsumer(IModel channel, ushort batchSize) + public PullConsumer(IModel channel, ushort batchSize, ILoggerFactory loggerFactory) : base(channel) { + _logger = loggerFactory.CreateLogger(); + //set the number of messages to fetch -- defaults to 1 unless set on subscription, no impact on //BasicGet, only works on BasicConsume channel.BasicQos(0, batchSize, false); @@ -60,12 +61,12 @@ public PullConsumer(IModel channel, ushort batchSize) var now = DateTime.UtcNow; var end = now.Add(timeOut); var pause = (timeOut > TimeSpan.FromMilliseconds(25)) ? Convert.ToInt32(timeOut.TotalMilliseconds) / 5 : 5; - - + + var buffer = new BasicDeliverEventArgs[bufferSize]; var bufferIndex = 0; - - + + while (now < end && bufferIndex < bufferSize) { if (_messages.TryDequeue(out BasicDeliverEventArgs? result)) @@ -82,21 +83,21 @@ public PullConsumer(IModel channel, ushort batchSize) return bufferIndex == 0 ? (0, null) : (bufferIndex, buffer); } - - public override void HandleBasicDeliver( - string consumerTag, - ulong deliveryTag, - bool redelivered, - string exchange, - string routingKey, - IBasicProperties properties, - ReadOnlyMemory body) + + public override void HandleBasicDeliver( + string consumerTag, + ulong deliveryTag, + bool redelivered, + string exchange, + string routingKey, + IBasicProperties properties, + ReadOnlyMemory body) { //We have to copy the body, before returning, as the memory in body is pooled and may be re-used after (see base class documentation) //See also https://docs.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines var payload = new byte[body.Length]; body.CopyTo(payload); - + _messages.Enqueue(new BasicDeliverEventArgs { BasicProperties = properties, @@ -122,9 +123,9 @@ public override void OnCancel(params string[] consumerTags) catch (Exception e) { //don't impede shutdown, just log - Log.NackUnhandledMessagesOnShutdownFailed(s_logger, e.Message); + Log.NackUnhandledMessagesOnShutdownFailed(_logger, e.Message); } - + base.OnCancel(); } @@ -133,6 +134,6 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Tried to nack unhandled messages on shutdown but failed for {ErrorMessage}")] public static partial void NackUnhandledMessagesOnShutdownFailed(ILogger logger, string errorMessage); } - } + } } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumer.cs index d09a39a5b7..88cd86af2a 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumer.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Polly.CircuitBreaker; using RabbitMQ.Client.Exceptions; @@ -49,7 +48,8 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// public partial class RmqMessageConsumer : RmqMessageGateway, IAmAMessageConsumerSync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly RmqMessageCreator _messageCreator; private PullConsumer? _consumer; private RmqMessageProducer? _requeueProducer; @@ -85,11 +85,13 @@ public partial class RmqMessageConsumer : RmqMessageGateway, IAmAMessageConsumer /// How lare can the buffer grow before we stop accepting new work? /// Should we validate, or create missing channels /// Optional scheduler for delayed message delivery when native delay is not supported + /// The used to create a logger. public RmqMessageConsumer( RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, + ILoggerFactory loggerFactory, bool highAvailability = false, int batchSize = 1, ChannelName? deadLetterQueueName = null, @@ -98,7 +100,7 @@ public RmqMessageConsumer( int? maxQueueLength = null, OnMissingChannel makeChannels = OnMissingChannel.Create, IAmAMessageScheduler? scheduler = null) - : this(connection, queueName, new RoutingKeys([routingKey]), isDurable, highAvailability, + : this(connection, queueName, new RoutingKeys([routingKey]), isDurable, loggerFactory, highAvailability, batchSize, deadLetterQueueName, deadLetterRoutingKey, ttl, maxQueueLength, makeChannels, scheduler) { } @@ -118,11 +120,13 @@ public RmqMessageConsumer( /// The maximum number of messages on the queue before we begin to reject publication of messages /// Should we validate or create missing channels /// Optional scheduler for delayed message delivery when native delay is not supported + /// The used to create a logger. public RmqMessageConsumer( RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKeys routingKeys, bool isDurable, + ILoggerFactory loggerFactory, bool highAvailability = false, int batchSize = 1, ChannelName? deadLetterQueueName = null, @@ -131,8 +135,10 @@ public RmqMessageConsumer( int? maxQueueLength = null, OnMissingChannel makeChannels = OnMissingChannel.Create, IAmAMessageScheduler? scheduler = null) - : base(connection) + : base(connection, loggerFactory) { + _logger = loggerFactory.CreateLogger(); + _messageCreator = new RmqMessageCreator(LoggerFactory.CreateLogger()); _queueName = queueName; _routingKeys = routingKeys; _isDurable = isDurable; @@ -159,13 +165,13 @@ public void Acknowledge(Message message) try { EnsureBroker(); - Log.AcknowledgingMessage(s_logger, message.Id.Value, deliveryTag); + Log.AcknowledgingMessage(_logger, message.Id.Value, deliveryTag); //NOTE: Ensure Broker will create a channel if it is not already created Channel!.BasicAck(deliveryTag, false); } catch (Exception exception) { - Log.ErrorAcknowledgingMessage(s_logger, exception, message.Id.Value, deliveryTag); + Log.ErrorAcknowledgingMessage(_logger, exception, message.Id.Value, deliveryTag); throw; } } @@ -179,24 +185,26 @@ public void Purge() { //Why bind a queue? Because we use purge to initialize a queue for RPC EnsureChannel(); - Log.PurgingChannel(s_logger, _queueName.Value); + Log.PurgingChannel(_logger, _queueName.Value); //NOTE: Ensure Broker will create a channel if it is not already created - try { Channel!.QueuePurge(_queueName.Value); } + try + { Channel!.QueuePurge(_queueName.Value); } catch (OperationInterruptedException operationInterruptedException) { - if (operationInterruptedException.ShutdownReason.ReplyCode == 404) { return; } + if (operationInterruptedException.ShutdownReason.ReplyCode == 404) + { return; } throw; } } catch (Exception exception) { - Log.ErrorPurgingChannel(s_logger, exception, _queueName.Value); + Log.ErrorPurgingChannel(_logger, exception, _queueName.Value); throw; } } - + /// /// Nacks the specified message, releasing it back to RabbitMQ for redelivery. /// @@ -207,12 +215,12 @@ public void Nack(Message message) try { EnsureBroker(); - Log.NackingMessage(s_logger, message.Id.Value, deliveryTag); + Log.NackingMessage(_logger, message.Id.Value, deliveryTag); Channel!.BasicNack(deliveryTag, false, true); } catch (Exception exception) { - Log.ErrorNackingMessage(s_logger, exception, message.Id.Value, deliveryTag); + Log.ErrorNackingMessage(_logger, exception, message.Id.Value, deliveryTag); throw; } } @@ -225,15 +233,15 @@ public void Nack(Message message) /// Message. public Message[] Receive(TimeSpan? timeOut = null) { - + if (Connection.Exchange is null) throw new InvalidOperationException("RmqMessageConsumer.Receive - value of Connection.Exchange cannot be null"); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RmqMessageConsumer.Receive - value of Connection.AmpqUri cannot be null"); - Log.PreparingToRetrieveMessage(s_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); - + Log.PreparingToRetrieveMessage(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); + timeOut ??= TimeSpan.FromMilliseconds(5); try @@ -248,17 +256,17 @@ public Message[] Receive(TimeSpan? timeOut = null) var messages = new Message[resultCount]; for (var i = 0; i < resultCount; i++) { - var message = RmqMessageCreator.CreateMessage(results[i]); + var message = _messageCreator.CreateMessage(results[i]); messages[i] = message; - Log.ReceivedMessage(s_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); + Log.ReceivedMessage(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), JsonSerializer.Serialize(message, JsonSerialisationOptions.Options)); } return messages; } else { - + return [_noopMessage]; } } @@ -282,7 +290,7 @@ exception is NotSupportedException || return [_noopMessage]; // Default return in case of exception } - + /// /// Rejects the specified message. /// @@ -295,16 +303,16 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) EnsureBroker(_queueName); var reasonString = reason is null ? nameof(RejectionReason.DeliveryError) : reason.RejectionReason.ToString(); var description = reason is null ? "unknown" : reason.Description ?? "unknown"; - - Log.NoAckMessage(s_logger, message.Id.Value, message.DeliveryTag, reasonString, description); - + + Log.NoAckMessage(_logger, message.Id.Value, message.DeliveryTag, reasonString, description); + //if we have a DLQ, this will force over to the DLQ Channel!.BasicReject(message.DeliveryTag, false); return true; } catch (Exception exception) { - Log.ErrorNoAckMessage(s_logger, exception, message.Id.Value); + Log.ErrorNoAckMessage(_logger, exception, message.Id.Value); throw; } } @@ -337,7 +345,7 @@ public bool Requeue(Message message, TimeSpan? timeout = null) try { - Log.RequeueingMessage(s_logger, message.Id.Value, timeout.Value.TotalMilliseconds); + Log.RequeueingMessage(_logger, message.Id.Value, timeout.Value.TotalMilliseconds); EnsureBroker(_queueName); // Step 1: Publish the message back to the queue first. @@ -345,7 +353,7 @@ public bool Requeue(Message message, TimeSpan? timeout = null) // timeout is guaranteed non-null here due to the ??= TimeSpan.Zero coalescing at the top of this method if (DelaySupported || timeout <= TimeSpan.Zero) { - var rmqMessagePublisher = new RmqMessagePublisher(Channel!, Connection); + var rmqMessagePublisher = new RmqMessagePublisher(Channel!, Connection, LoggerFactory); rmqMessagePublisher.RequeueMessage(message, _queueName, timeout.Value); } else @@ -358,15 +366,15 @@ public bool Requeue(Message message, TimeSpan? timeout = null) // If this fails after a successful publish, the message may be duplicated (not lost). // Consumers should be idempotent to handle potential duplicates. var deliveryTag = message.DeliveryTag; - Log.DeletingMessage(s_logger, message.Id.Value, deliveryTag); - + Log.DeletingMessage(_logger, message.Id.Value, deliveryTag); + Channel!.BasicAck(deliveryTag, false); return true; } catch (Exception exception) { - Log.ErrorRequeueingMessage(s_logger, exception, message.Id.Value); + Log.ErrorRequeueingMessage(_logger, exception, message.Id.Value); return false; } } @@ -377,7 +385,7 @@ private void EnsureProducer() { #pragma warning disable CS0420 // LazyInitializer handles the memory barrier for the volatile field LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, - ref _requeueProducerLock, () => new RmqMessageProducer(Connection) + ref _requeueProducerLock, () => new RmqMessageProducer(Connection, loggerFactory: LoggerFactory) { Scheduler = _scheduler }); @@ -389,10 +397,10 @@ protected virtual void EnsureChannel() { if (Connection.Exchange is null) throw new InvalidOperationException("RmqMessageConsumer.EnsureChannel - value of Connection.Exchange cannot be null"); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RmqMessageConsumer.EnsureChannel - value of Connection.AmpqUri cannot be null"); - + if (Channel == null || Channel.IsClosed) { EnsureBroker(_queueName); @@ -413,7 +421,7 @@ protected virtual void EnsureChannel() CreateConsumer(); - Log.CreatedChannel(s_logger, Channel!.ChannelNumber, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); + Log.CreatedChannel(_logger, Channel!.ChannelNumber, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); } } @@ -434,42 +442,43 @@ private void CreateConsumer() { if (Channel == null) throw new InvalidOperationException("RmqMessageConsumer.CreateConsumer - value of Channel cannot be null"); - + if (Connection.Exchange is null) throw new InvalidOperationException("RmqMessageConsumer.CreateConsumer - value of Connection.Exchange cannot be null"); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RmqMessageConsumer.CreateConsumer - value of Connection.AmpqUri cannot be null"); - - _consumer = new PullConsumer(Channel, _batchSize); + + _consumer = new PullConsumer(Channel, _batchSize, LoggerFactory); Channel.BasicConsume(_queueName.Value, false, _consumerTag, false, false, SetQueueArguments(), _consumer); - Log.CreatedConsumer(s_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); + Log.CreatedConsumer(_logger, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri()); } private void CreateQueue() { if (Channel == null) throw new InvalidOperationException("RmqMessageConsumer.CreateQueue - value of Channel cannot be null"); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RmqMessageConsumer.CreateQueue - value of Connection.AmpqUri cannot be null"); - - Log.CreatingQueue(s_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); + + Log.CreatingQueue(_logger, _queueName.Value, Connection.AmpqUri.GetSanitizedUri()); Channel.QueueDeclare(_queueName.Value, _isDurable, false, false, SetQueueArguments()); //NOTE: hasDlq cannot be true if _deadLetterQueuename is null - if (_hasDlq) Channel.QueueDeclare(_deadLetterQueueName!.Value, _isDurable, false, false, new Dictionary()); + if (_hasDlq) + Channel.QueueDeclare(_deadLetterQueueName!.Value, _isDurable, false, false, new Dictionary()); } private void BindQueue() { if (Channel == null) throw new InvalidOperationException("RmqMessageConsumer.BindQueue - value of Channel cannot be null"); - + if (Connection.Exchange is null) throw new InvalidOperationException("RmqMessageConsumer.BindQueue - value of Connection.Exchange cannot be null"); - + foreach (var key in _routingKeys) { Channel.QueueBind(_queueName.Value, Connection.Exchange.Name, key, new Dictionary()); @@ -482,17 +491,18 @@ private void BindQueue() private void HandleException(Exception exception, bool resetConnection = false) { - Log.ErrorListeningToQueue(s_logger, exception, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange?.Name ?? string.Empty, Connection.AmpqUri?.GetSanitizedUri() ?? string.Empty); - if (resetConnection) ResetConnectionToBroker(); + Log.ErrorListeningToQueue(_logger, exception, _queueName.Value, string.Join(";", _routingKeys.Select(rk => rk.Value)), Connection.Exchange?.Name ?? string.Empty, Connection.AmpqUri?.GetSanitizedUri() ?? string.Empty); + if (resetConnection) + ResetConnectionToBroker(); throw new ChannelFailureException("Error connecting to RabbitMQ, see inner exception for details", exception); } - + private void ValidateQueue() { if (Channel == null) throw new InvalidOperationException("RmqMessageConsumer.ValidateQueue - value of Channel cannot be null"); - - Log.ValidatingQueue(s_logger, _queueName.Value, Connection.AmpqUri!.GetSanitizedUri()); + + Log.ValidatingQueue(_logger, _queueName.Value, Connection.AmpqUri!.GetSanitizedUri()); try { @@ -612,7 +622,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "RmqMessageConsumer: There was an error listening to queue {ChannelName} via exchange {RoutingKeys} via exchange {ExchangeName} on subscription {URL}")] public static partial void ErrorListeningToQueue(ILogger logger, Exception exception, string channelName, string routingKeys, string exchangeName, string url); - + [LoggerMessage(LogLevel.Debug, "RmqMessageConsumer: Validating queue {ChannelName} on subscription {URL}")] public static partial void ValidatingQueue(ILogger logger, string channelName, string url); } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumerFactory.cs index 8dd8bfecee..02e8a84325 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumerFactory.cs @@ -22,11 +22,14 @@ THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.RMQ.Sync { public class RmqMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly RmqMessagingGatewayConnection _rmqConnection; + private readonly ILoggerFactory _loggerFactory; private IAmAMessageScheduler? _scheduler; /// @@ -44,10 +47,12 @@ public IAmAMessageScheduler? Scheduler /// /// The subscription to the broker hosting the queue /// The optional message scheduler for delayed requeue support - public RmqMessageConsumerFactory(RmqMessagingGatewayConnection rmqConnection, IAmAMessageScheduler? scheduler = null) + /// The used to create loggers for the consumers + public RmqMessageConsumerFactory(RmqMessagingGatewayConnection rmqConnection, ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null) { _rmqConnection = rmqConnection; _scheduler = scheduler; + _loggerFactory = loggerFactory; } /// @@ -57,15 +62,16 @@ public RmqMessageConsumerFactory(RmqMessagingGatewayConnection rmqConnection, IA /// IAmAMessageConsumerSync public IAmAMessageConsumerSync Create(Subscription subscription) { - RmqSubscription? rmqSubscription = subscription as RmqSubscription; + RmqSubscription? rmqSubscription = subscription as RmqSubscription; if (rmqSubscription == null) throw new ConfigurationException("We expect an SQSConnection or SQSConnection as a parameter"); - + return new RmqMessageConsumer( _rmqConnection, rmqSubscription.ChannelName, //RMQ Queue Name rmqSubscription.RoutingKey, rmqSubscription.IsDurable, + _loggerFactory, rmqSubscription.HighAvailability, rmqSubscription.BufferSize, rmqSubscription.DeadLetterChannelName, diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageCreator.cs index 5ba3d94fd2..020accedbc 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageCreator.cs @@ -30,7 +30,6 @@ THE SOFTWARE. */ using System.Text; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -39,9 +38,14 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync; internal sealed partial class RmqMessageCreator { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; - public static Message CreateMessage(BasicDeliverEventArgs fromQueue) + public RmqMessageCreator(ILogger logger) + { + _logger = logger; + } + + public Message CreateMessage(BasicDeliverEventArgs fromQueue) { var headers = fromQueue.BasicProperties.Headers ?? new Dictionary(); var topic = HeaderResult.Empty(); @@ -62,14 +66,14 @@ public static Message CreateMessage(BasicDeliverEventArgs fromQueue) } catch (Exception e) { - Log.FailedToCreateMessageFromAmqpMessage(s_logger, e); + Log.FailedToCreateMessageFromAmqpMessage(_logger, e); message = Message.FailureMessage(topic.Result, messageId.Result); } return message; } - private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue, IDictionary headers, + private MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue, IDictionary headers, HeaderResult topic, HeaderResult messageId) { var timeStamp = ReadTimeStamp(fromQueue.BasicProperties); @@ -102,7 +106,7 @@ private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue timeStamp: timeStamp.Success ? timeStamp.Result : DateTime.UtcNow, correlationId: correlationId.Result, replyTo: new RoutingKey(replyTo.Result?.Value ?? string.Empty), - contentType: new ContentType(fromQueue.BasicProperties.ContentType), + contentType: new ContentType(fromQueue.BasicProperties.ContentType), handledCount: handledCount.Result, dataSchema: dataSchema.Result, subject: subject.Result, @@ -113,12 +117,12 @@ private static MessageHeader CreateMessageHeader(BasicDeliverEventArgs fromQueue ); } - private static void ProcessHeaderBag(IDictionary headers, Message message) + private void ProcessHeaderBag(IDictionary headers, Message message) { headers.Each(header => message.Header.Bag.Add(header.Key, ParseHeaderValue(header.Value))); } - private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message) + private void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message) { var deliveryTag = ReadDeliveryTag(fromQueue.DeliveryTag); var redelivered = ReadRedeliveredFlag(fromQueue.Redelivered); @@ -128,7 +132,7 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message message.Persist = fromQueue.BasicProperties.DeliveryMode == 2; } - private static HeaderResult ReadHeader(IDictionary dict, string key, bool dieOnMissing = false) + private HeaderResult ReadHeader(IDictionary dict, string key, bool dieOnMissing = false) { if (false == dict.TryGetValue(key, out object? value)) { @@ -137,7 +141,7 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message if (!(value is byte[] bytes)) { - Log.HeaderValueCouldNotBeCastToByteArray(s_logger, key); + Log.HeaderValueCouldNotBeCastToByteArray(_logger, key); return new HeaderResult(null, false); } @@ -149,12 +153,12 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message catch (Exception e) { var firstTwentyBytes = BitConverter.ToString(bytes.Take(20).ToArray()); - Log.FailedToReadHeaderValueAsUtf8(s_logger, key, firstTwentyBytes, e); + Log.FailedToReadHeaderValueAsUtf8(_logger, key, firstTwentyBytes, e); return new HeaderResult(null, false); } } - private static HeaderResult ReadCorrelationId(IDictionary headers) + private HeaderResult ReadCorrelationId(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CORRELATION_ID, out object? correlationHeader)) { @@ -165,12 +169,12 @@ private static void SetMessageMetadata(BasicDeliverEventArgs fromQueue, Message return new HeaderResult(null, false); } - private static HeaderResult ReadDeliveryTag(ulong deliveryTag) + private HeaderResult ReadDeliveryTag(ulong deliveryTag) { return new HeaderResult(deliveryTag, true); } - private static HeaderResult ReadTimeStamp(IBasicProperties basicProperties) + private HeaderResult ReadTimeStamp(IBasicProperties basicProperties) { if (basicProperties.IsTimestampPresent()) { @@ -188,7 +192,7 @@ private static HeaderResult ReadTimeStamp(IBasicProperties basic return new HeaderResult(DateTimeOffset.UtcNow, true); } - private static HeaderResult ReadMessageType(IDictionary headers) + private HeaderResult ReadMessageType(IDictionary headers) { return ReadHeader(headers, HeaderNames.MESSAGE_TYPE) .Map(s => @@ -203,7 +207,7 @@ private static HeaderResult ReadMessageType(IDictionary ReadHandledCount(IDictionary headers) + private HeaderResult ReadHandledCount(IDictionary headers) { if (headers.TryGetValue(HeaderNames.HANDLED_COUNT, out object? header) == false) { @@ -213,10 +217,10 @@ private static HeaderResult ReadHandledCount(IDictionary h switch (header) { case byte[] value: - { - var val = int.TryParse(Encoding.UTF8.GetString(value), out var handledCount) ? handledCount : 0; - return new HeaderResult(val, true); - } + { + var val = int.TryParse(Encoding.UTF8.GetString(value), out var handledCount) ? handledCount : 0; + return new HeaderResult(val, true); + } case int value: return new HeaderResult(value, true); default: @@ -224,7 +228,7 @@ private static HeaderResult ReadHandledCount(IDictionary h } } - private static HeaderResult ReadDelay(IDictionary headers) + private HeaderResult ReadDelay(IDictionary headers) { if (headers.TryGetValue(HeaderNames.DELAYED_MILLISECONDS, out var delayedMsHeader) == false) { @@ -239,34 +243,34 @@ private static HeaderResult ReadDelay(IDictionary hea switch (delayedMsHeader) { case byte[] value: - { - if (!int.TryParse(Encoding.UTF8.GetString(value), out var handledCount)) - delayedMilliseconds = 0; - else { - if (handledCount < 0) - handledCount = Math.Abs(handledCount); - delayedMilliseconds = handledCount; + if (!int.TryParse(Encoding.UTF8.GetString(value), out var handledCount)) + delayedMilliseconds = 0; + else + { + if (handledCount < 0) + handledCount = Math.Abs(handledCount); + delayedMilliseconds = handledCount; + } + + break; } - - break; - } case int value: - { - if (value < 0) - value = Math.Abs(value); + { + if (value < 0) + value = Math.Abs(value); - delayedMilliseconds = value; - break; - } + delayedMilliseconds = value; + break; + } case long value: - { - if (value < 0) - value = Math.Abs(value); + { + if (value < 0) + value = Math.Abs(value); - delayedMilliseconds = (int)value; - break; - } + delayedMilliseconds = (int)value; + break; + } default: return new HeaderResult(TimeSpan.Zero, false); } @@ -274,7 +278,7 @@ private static HeaderResult ReadDelay(IDictionary hea return new HeaderResult(TimeSpan.FromMilliseconds(delayedMilliseconds), true); } - private static HeaderResult ReadTopic(BasicDeliverEventArgs fromQueue, IDictionary headers) + private HeaderResult ReadTopic(BasicDeliverEventArgs fromQueue, IDictionary headers) { var res = ReadHeader(headers, HeaderNames.TOPIC).Map(s => { @@ -286,28 +290,28 @@ private static HeaderResult ReadDelay(IDictionary hea { return res; } - + return new HeaderResult(new RoutingKey(fromQueue.RoutingKey), true); } - private static HeaderResult ReadMessageId(string? messageId) + private HeaderResult ReadMessageId(string? messageId) { if (string.IsNullOrEmpty(messageId)) { var newMessageId = Id.Random(); - Log.NoMessageIdFoundInMessage(s_logger, newMessageId.Value); + Log.NoMessageIdFoundInMessage(_logger, newMessageId.Value); return new HeaderResult(newMessageId, true); } return new HeaderResult(Id.Create(messageId), true); } - private static HeaderResult ReadRedeliveredFlag(bool redelivered) + private HeaderResult ReadRedeliveredFlag(bool redelivered) { return new HeaderResult(redelivered, true); } - private static HeaderResult ReadReplyTo(IBasicProperties basicProperties) + private HeaderResult ReadReplyTo(IBasicProperties basicProperties) { if (basicProperties.IsReplyToPresent()) { @@ -317,7 +321,7 @@ private static HeaderResult ReadRedeliveredFlag(bool redelivered) return new HeaderResult(null, true); } - private static HeaderResult ReadSource(IDictionary headers) + private HeaderResult ReadSource(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SOURCE, out var source) && source is byte[] val @@ -329,7 +333,7 @@ private static HeaderResult ReadSource(IDictionary headers return new HeaderResult(new Uri(MessageHeader.DefaultSource), true); } - private static HeaderResult ReadType(IDictionary headers) + private HeaderResult ReadType(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TYPE, out var type) && type is byte[] typeArray) @@ -340,7 +344,7 @@ private static HeaderResult ReadType(IDictionary(CloudEventsType.Empty, true); } - private static HeaderResult ReadSubject(IDictionary headers) + private HeaderResult ReadSubject(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SUBJECT, out var subject) && subject is byte[] subjectArray) @@ -351,7 +355,7 @@ private static HeaderResult ReadType(IDictionary(null, true); } - private static HeaderResult ReadDataSchema(IDictionary headers) + private HeaderResult ReadDataSchema(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_DATA_SCHEMA, out var dataSchema) && dataSchema is byte[] dataSchemaArray @@ -363,7 +367,7 @@ private static HeaderResult ReadType(IDictionary(null, true); } - private static HeaderResult ReadTraceParent(IDictionary headers) + private HeaderResult ReadTraceParent(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_PARENT, out var traceParent) && traceParent is byte[] traceParentArray) @@ -374,7 +378,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static HeaderResult ReadTraceState(IDictionary headers) + private HeaderResult ReadTraceState(IDictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_STATE, out var traceState) && traceState is byte[] traceParentArray) @@ -385,7 +389,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static HeaderResult ReadBaggage(IDictionary headers) + private HeaderResult ReadBaggage(IDictionary headers) { if (headers.TryGetValue(HeaderNames.W3C_BAGGAGE, out var traceParent) && traceParent is byte[] traceParentArray) @@ -396,7 +400,7 @@ private static HeaderResult ReadType(IDictionary(string.Empty, true); } - private static object ParseHeaderValue(object? value) + private object ParseHeaderValue(object? value) { if (value == null) return string.Empty; diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGateway.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGateway.cs index b1771e6389..4c4eaece04 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGateway.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGateway.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Polly; using RabbitMQ.Client; using RabbitMQ.Client.Events; @@ -51,10 +50,11 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// public partial class RmqMessageGateway : IDisposable { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly Policy _circuitBreakerPolicy; private readonly ConnectionFactory _connectionFactory; private readonly Policy _retryPolicy; + protected readonly ILoggerFactory LoggerFactory; protected readonly RmqMessagingGatewayConnection Connection; protected IModel? Channel; @@ -63,17 +63,20 @@ public partial class RmqMessageGateway : IDisposable /// Use if you need to inject a test logger /// /// The amqp uri and exchange to connect to - protected RmqMessageGateway(RmqMessagingGatewayConnection connection) + /// The used to create a logger. + protected RmqMessageGateway(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { + LoggerFactory = loggerFactory; + _logger = LoggerFactory.CreateLogger(); Connection = connection ?? throw new ArgumentNullException(nameof(connection)); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RMQMessagingGateway: Connection must have an AMPQ URI"); - + if (Connection.Exchange is null) throw new InvalidOperationException("RMQMessagingGateway: Connection must have an Exchange"); - var connectionPolicyFactory = new ConnectionPolicyFactory(Connection); + var connectionPolicyFactory = new ConnectionPolicyFactory(Connection, LoggerFactory); _retryPolicy = connectionPolicyFactory.RetryPolicy; _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy; @@ -114,7 +117,7 @@ public virtual void Dispose() protected void EnsureBroker(ChannelName? queueName = null, OnMissingChannel makeExchange = OnMissingChannel.Create) { queueName ??= new ChannelName("Producer Channel"); - + ConnectWithCircuitBreaker(queueName, makeExchange); } @@ -125,7 +128,7 @@ private void ConnectWithCircuitBreaker(ChannelName queueName, OnMissingChannel m private void ConnectWithRetry(ChannelName queueName, OnMissingChannel makeExchange) { - _retryPolicy.Execute((_) => ConnectToBroker(makeExchange), new Dictionary {{"queueName", queueName.Value}}); + _retryPolicy.Execute((_) => ConnectToBroker(makeExchange), new Dictionary { { "queueName", queueName.Value } }); } protected virtual void ConnectToBroker(OnMissingChannel makeExchange) @@ -134,19 +137,19 @@ protected virtual void ConnectToBroker(OnMissingChannel makeExchange) { if (Connection.Name is null) throw new InvalidOperationException("RMQMessagingGateway: Connection must have a name"); - + if (Connection.AmpqUri is null) throw new InvalidOperationException("RMQMessagingGateway: Connection must have an AMPQ URI"); - - var connection = new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).GetConnection(_connectionFactory); - + + var connection = new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).GetConnection(_connectionFactory); + if (connection is null) - throw new InvalidOperationException($"RMQMessagingGateway: Connection to {Connection.AmpqUri.GetSanitizedUri()} failed" ); + throw new InvalidOperationException($"RMQMessagingGateway: Connection to {Connection.AmpqUri.GetSanitizedUri()} failed"); connection.ConnectionBlocked += HandleBlocked; connection.ConnectionUnblocked += HandleUnBlocked; - Log.OpeningChannelToRabbitMq(s_logger, Connection.AmpqUri.GetSanitizedUri()); + Log.OpeningChannelToRabbitMq(_logger, Connection.AmpqUri.GetSanitizedUri()); Channel = connection.CreateModel(); @@ -157,12 +160,12 @@ protected virtual void ConnectToBroker(OnMissingChannel makeExchange) private void HandleBlocked(object? sender, ConnectionBlockedEventArgs args) { - Log.SubscriptionBlocked(s_logger, Connection.AmpqUri!.GetSanitizedUri(), args.Reason); + Log.SubscriptionBlocked(_logger, Connection.AmpqUri!.GetSanitizedUri(), args.Reason); } private void HandleUnBlocked(object? sender, EventArgs args) - { - Log.SubscriptionUnblocked(s_logger, Connection.AmpqUri!.GetSanitizedUri()); + { + Log.SubscriptionUnblocked(_logger, Connection.AmpqUri!.GetSanitizedUri()); } protected void ResetConnectionToBroker() @@ -170,7 +173,7 @@ protected void ResetConnectionToBroker() if (Connection.Name is null) throw new InvalidOperationException("RMQMessagingGateway: Connection must have a name"); - new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).ResetConnection(_connectionFactory); + new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).ResetConnection(_connectionFactory); } ~RmqMessageGateway() @@ -188,7 +191,7 @@ protected virtual void Dispose(bool disposing) Channel = null; if (Connection.Name is not null) - new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat).RemoveConnection(_connectionFactory); + new RmqMessageGatewayConnectionPool(Connection.Name, Connection.Heartbeat, LoggerFactory).RemoveConnection(_connectionFactory); } } diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGatewayConnectionPool.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGatewayConnectionPool.cs index ef4c1ed74a..c1041fd5aa 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGatewayConnectionPool.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGatewayConnectionPool.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Exceptions; @@ -39,17 +38,18 @@ public partial class RmqMessageGatewayConnectionPool { private readonly string _connectionName; private readonly ushort _connectionHeartbeat; + private readonly ILogger _logger; private static readonly Dictionary s_connectionPool = new Dictionary(); private static readonly object s_lock = new object(); - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); private static readonly Random jitter = new Random(); - public RmqMessageGatewayConnectionPool(string connectionName, ushort connectionHeartbeat) + public RmqMessageGatewayConnectionPool(string connectionName, ushort connectionHeartbeat, ILoggerFactory loggerFactory) { _connectionName = connectionName; _connectionHeartbeat = connectionHeartbeat; + _logger = loggerFactory.CreateLogger(); } - + /// /// Return matching RabbitMQ subscription if exist (match by amqp scheme) /// or create new subscription to RabbitMQ (thread-safe) @@ -85,7 +85,7 @@ public void ResetConnection(ConnectionFactory connectionFactory) } catch (BrokerUnreachableException exception) { - Log.FailedToResetSubscriptionToRabbitMqEndpoint(s_logger, connectionFactory.Endpoint, exception); + Log.FailedToResetSubscriptionToRabbitMqEndpoint(_logger, connectionFactory.Endpoint, exception); } } } @@ -96,7 +96,7 @@ private PooledConnection CreateConnection(ConnectionFactory connectionFactory) TryRemoveConnection(connectionId); - Log.CreatingSubscriptionToRabbitMqEndpoint(s_logger, connectionFactory.Endpoint); + Log.CreatingSubscriptionToRabbitMqEndpoint(_logger, connectionFactory.Endpoint); connectionFactory.RequestedHeartbeat = TimeSpan.FromSeconds(_connectionHeartbeat); connectionFactory.RequestedConnectionTimeout = TimeSpan.FromMilliseconds(5000); @@ -105,12 +105,12 @@ private PooledConnection CreateConnection(ConnectionFactory connectionFactory) var connection = connectionFactory.CreateConnection(_connectionName); - Log.NewConnectedToAddedToPool(s_logger, connection.Endpoint, connection.ClientProvidedName); + Log.NewConnectedToAddedToPool(_logger, connection.Endpoint, connection.ClientProvidedName); void ShutdownHandler(object? sender, ShutdownEventArgs e) { - Log.SubscriptionHasBeenShutdown(s_logger, connection.Endpoint, e.ToString()); + Log.SubscriptionHasBeenShutdown(_logger, connection.Endpoint, e.ToString()); lock (s_lock) { @@ -124,7 +124,7 @@ void ShutdownHandler(object? sender, ShutdownEventArgs e) connection.ConnectionShutdown += ShutdownHandler; - var pooledConnection = new PooledConnection{Connection = connection, ShutdownHandler = ShutdownHandler}; + var pooledConnection = new PooledConnection { Connection = connection, ShutdownHandler = ShutdownHandler }; s_connectionPool.Add(connectionId, pooledConnection); @@ -133,8 +133,9 @@ void ShutdownHandler(object? sender, ShutdownEventArgs e) private void TryRemoveConnection(string connectionId) { - if (!s_connectionPool.TryGetValue(connectionId, out PooledConnection? pooledConnection)) return; - + if (!s_connectionPool.TryGetValue(connectionId, out PooledConnection? pooledConnection)) + return; + //netstandard20 issue, if connectionfound is true, pooledConnection is not null pooledConnection.Connection!.ConnectionShutdown -= pooledConnection.ShutdownHandler; pooledConnection.Connection.Dispose(); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducer.cs index 108694d2fd..92d7362d80 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducer.cs @@ -32,7 +32,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; using RabbitMQ.Client.Events; @@ -51,7 +50,7 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync public partial class RmqMessageProducer : RmqMessageGateway, IAmAMessageProducerSync, IAmAMessageProducerAsync, ISupportPublishConfirmation, ISupportPublishConfirmationAsync { private readonly InstrumentationOptions _instrumentationOptions; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; static readonly object s_lock = new(); private RmqPublication _publication; @@ -103,9 +102,10 @@ public Publication Publication /// /// The subscription information needed to talk to RMQ /// The for how deep should the instrumentation go? + /// The used to create a logger. /// Make Channels = Create - public RmqMessageProducer(RmqMessagingGatewayConnection connection, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) - : this(connection, new RmqPublication { MakeChannels = OnMissingChannel.Create }) + public RmqMessageProducer(RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) + : this(connection, new RmqPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory) { _instrumentationOptions = instrumentationOptions; } @@ -117,9 +117,11 @@ public RmqMessageProducer(RmqMessagingGatewayConnection connection, Instrumentat /// How should we configure this producer. If not provided use default behaviours: /// Make Channels = Create /// - public RmqMessageProducer(RmqMessagingGatewayConnection connection, RmqPublication publication) - : base(connection) + /// The used to create a logger. + public RmqMessageProducer(RmqMessagingGatewayConnection connection, RmqPublication? publication, ILoggerFactory loggerFactory) + : base(connection, loggerFactory) { + _logger = loggerFactory.CreateLogger(); _publication = publication ?? new RmqPublication { MakeChannels = OnMissingChannel.Create }; _waitForConfirmsTimeOutInMilliseconds = _publication.WaitForConfirmsTimeOutInMilliseconds; } @@ -155,9 +157,9 @@ private void SendWithDelay(Message message, TimeSpan? delay, bool useSchedulerAs { EnsureBroker(makeExchange: _publication.MakeChannels); //NOTE: EnsureBroker will create a channel if one does not exist - Log.PreparingToSend(s_logger, Connection.Exchange!.Name); + Log.PreparingToSend(_logger, Connection.Exchange!.Name); - var rmqMessagePublisher = new RmqMessagePublisher(Channel!, Connection); + var rmqMessagePublisher = new RmqMessagePublisher(Channel!, Connection, LoggerFactory); message.Persist = Connection.PersistMessages; Channel!.BasicAcks += OnPublishSucceeded; @@ -167,34 +169,34 @@ private void SendWithDelay(Message message, TimeSpan? delay, bool useSchedulerAs BrighterTracer.WriteProducerEvent(Span, MessagingSystem.RabbitMQ, message, _instrumentationOptions); - Log.PublishingMessage(s_logger, Connection.Exchange.Name, Connection.AmpqUri!.GetSanitizedUri(), delay.Value.TotalMilliseconds, + Log.PublishingMessage(_logger, Connection.Exchange.Name, Connection.AmpqUri!.GetSanitizedUri(), delay.Value.TotalMilliseconds, message.Header.Topic.Value, message.Persist, message.Id.Value, message.Body.Value); _pendingConfirmations.TryAdd(Channel.NextPublishSeqNo, new PendingConfirmation(message.Id, message.Header.Topic, publishContext)); - if (delay == TimeSpan.Zero || DelaySupported || Scheduler == null) - { - rmqMessagePublisher.PublishMessage(message, delay.Value); - } - else if(useSchedulerAsync) - { - var schedulerAsync = (IAmAMessageSchedulerAsync)Scheduler!; - BrighterAsyncContext.Run(() => schedulerAsync.ScheduleAsync(message, delay.Value)); - } - else - { - var schedulerSync = (IAmAMessageSchedulerSync)Scheduler!; - schedulerSync.Schedule(message, delay.Value); - } - - Log.PublishedMessage(s_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay, + if (delay == TimeSpan.Zero || DelaySupported || Scheduler == null) + { + rmqMessagePublisher.PublishMessage(message, delay.Value); + } + else if (useSchedulerAsync) + { + var schedulerAsync = (IAmAMessageSchedulerAsync)Scheduler!; + BrighterAsyncContext.Run(() => schedulerAsync.ScheduleAsync(message, delay.Value)); + } + else + { + var schedulerSync = (IAmAMessageSchedulerSync)Scheduler!; + schedulerSync.Schedule(message, delay.Value); + } + + Log.PublishedMessage(_logger, Connection.Exchange.Name, Connection.AmpqUri.GetSanitizedUri(), delay, message.Header.Topic.Value, message.Persist, message.Id.Value, JsonSerializer.Serialize(message, JsonSerialisationOptions.Options), DateTime.UtcNow); } } catch (IOException io) { - Log.ErrorTalkingToSocket(s_logger, io, Connection.AmpqUri!.GetSanitizedUri()); + Log.ErrorTalkingToSocket(_logger, io, Connection.AmpqUri!.GetSanitizedUri()); ResetConnectionToBroker(); throw new ChannelFailureException("Error talking to the broker, see inner exception for details", io); } @@ -222,7 +224,7 @@ public sealed override void Dispose() Dispose(true); GC.SuppressFinalize(this); } - + public ValueTask DisposeAsync() { // The sync client has no async teardown, so dispose runs synchronously here; returning @@ -243,7 +245,7 @@ protected override void Dispose(bool disposing) //As we are disposing, just let that happen Channel.WaitForConfirms(TimeSpan.FromMilliseconds(_waitForConfirmsTimeOutInMilliseconds), out bool timedOut); if (timedOut) - Log.FailedToAwaitPublisherConfirms(s_logger); + Log.FailedToAwaitPublisherConfirms(_logger); } // WaitForConfirms drains the broker acks; the callbacks those acks spawned (including @@ -260,7 +262,7 @@ private void OnPublishFailed(object? sender, BasicNackEventArgs e) { RaisePublishConfirmation(new PublishConfirmationResult(false, confirmation.MessageId, confirmation.Topic, confirmation.Context)); _pendingConfirmations.TryRemove(e.DeliveryTag, out PendingConfirmation _); - Log.FailedToPublishMessage(s_logger, confirmation.MessageId.Value); + Log.FailedToPublishMessage(_logger, confirmation.MessageId.Value); } } @@ -270,7 +272,7 @@ private void OnPublishSucceeded(object? sender, BasicAckEventArgs e) { RaisePublishConfirmation(new PublishConfirmationResult(true, confirmation.MessageId, confirmation.Topic, confirmation.Context)); _pendingConfirmations.TryRemove(e.DeliveryTag, out PendingConfirmation _); - Log.PublishedMessageInformation(s_logger, confirmation.MessageId.Value); + Log.PublishedMessageInformation(_logger, confirmation.MessageId.Value); } } @@ -295,7 +297,7 @@ private void RaisePublishConfirmation(PublishConfirmationResult result) } catch (Exception ex) { - Log.ConfirmationCallbackFault(s_logger, result.MessageId.Value, ex); + Log.ConfirmationCallbackFault(_logger, result.MessageId.Value, ex); } finally { @@ -311,7 +313,7 @@ private void WaitForConfirmationCallbacks() return; if (!_confirmationCallbacks.TryWait(TimeSpan.FromMilliseconds(_waitForConfirmsTimeOutInMilliseconds), out int stillInFlight)) - Log.FailedToAwaitConfirmationCallbacks(s_logger, stillInFlight, _waitForConfirmsTimeOutInMilliseconds); + Log.FailedToAwaitConfirmationCallbacks(_logger, stillInFlight, _waitForConfirmsTimeOutInMilliseconds); } private static partial class Log @@ -321,7 +323,7 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "RmqMessageProducer: Publishing message to exchange {ExchangeName} on subscription {URL} with a delay of {Delay} and topic {Topic} and persisted {Persist} and id {Id} and body: {Request}")] public static partial void PublishingMessage(ILogger logger, string exchangeName, string url, double delay, string topic, bool persist, string id, string request); - + [LoggerMessage(LogLevel.Information, "RmqMessageProducer: Published message to exchange {ExchangeName} on broker {URL} with a delay of {Delay} and topic {Topic} and persisted {Persist} and id {Id} and message: {Request} at {Time}")] public static partial void PublishedMessage(ILogger logger, string exchangeName, string url, TimeSpan? delay, string topic, bool persist, string id, string request, DateTime time); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducerFactory.cs index 05569d19ce..cc65177ca5 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducerFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.RMQ.Sync { @@ -36,9 +37,11 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// /// The connection to use to connect to RabbitMQ /// The publications describing the RabbitMQ topics that we want to use + /// The used to create loggers for the producers public class RmqMessageProducerFactory( RmqMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) : IAmAMessageProducerFactory { /// @@ -53,7 +56,7 @@ public Dictionary Create() { if (publication.Topic is null) throw new ConfigurationException("RmqMessageProducerFactory.Create => An RmqPublication must have a topic/routing key"); - var messageProducer = new RmqMessageProducer(connection, publication); + var messageProducer = new RmqMessageProducer(connection, publication, loggerFactory); messageProducer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); if (producers.ContainsKey(producerKey)) diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessagePublisher.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessagePublisher.cs index 645315051c..4ca32b8ab5 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessagePublisher.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessagePublisher.cs @@ -29,7 +29,6 @@ THE SOFTWARE. */ using System.Net.Mime; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using RabbitMQ.Client; namespace Paramore.Brighter.MessagingGateway.RMQ.Sync @@ -39,7 +38,7 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// internal sealed partial class RmqMessagePublisher { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private static readonly HashSet _headersToReset = [ HeaderNames.DELAY_MILLISECONDS, @@ -58,15 +57,17 @@ internal sealed partial class RmqMessagePublisher /// /// The channel. /// The exchange we want to talk to. + /// The used to create a logger. /// /// channel /// or /// exchangeName /// - public RmqMessagePublisher(IModel channel, RmqMessagingGatewayConnection connection) + public RmqMessagePublisher(IModel channel, RmqMessagingGatewayConnection connection, ILoggerFactory loggerFactory) { _connection = connection ?? throw new ArgumentNullException(nameof(connection)); _channel = channel ?? throw new ArgumentNullException(nameof(channel)); + _logger = loggerFactory.CreateLogger(); } /// @@ -116,7 +117,7 @@ public void RequeueMessage(Message message, ChannelName queueName, TimeSpan time var messageId = Uuid.NewAsString(); const string deliveryTag = "1"; - Log.RequeueMessageInformation(s_logger, message.Id.Value, deliveryTag, messageId, 1); + Log.RequeueMessageInformation(_logger, message.Id.Value, deliveryTag, messageId, 1); Dictionary headers = AddCloudEventHeaders(message); diff --git a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqProducerRegistryFactory.cs index 925853c9c0..70bad0a571 100644 --- a/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqProducerRegistryFactory.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.RMQ.Sync { @@ -10,7 +11,8 @@ namespace Paramore.Brighter.MessagingGateway.RMQ.Sync /// public class RmqProducerRegistryFactory( RmqMessagingGatewayConnection connection, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) : IAmAProducerRegistryFactory { /// @@ -19,7 +21,7 @@ public class RmqProducerRegistryFactory( /// A has of middleware clients by topic, for sending messages to the middleware public IAmAProducerRegistry Create() { - var producerFactory = new RmqMessageProducerFactory(connection, publications); + var producerFactory = new RmqMessageProducerFactory(connection, publications, loggerFactory); return new ProducerRegistry(producerFactory.Create()); } diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumer.cs index 41b0c3a55f..38f16fe370 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumer.cs @@ -31,17 +31,18 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using ServiceStack.Redis; namespace Paramore.Brighter.MessagingGateway.Redis { public partial class RedisMessageConsumer : RedisMessageGateway, IAmAMessageConsumerSync, IAmAMessageConsumerAsync { - + /* see RedisMessageProducer to understand how we are using a dynamic recipient list model with Redis */ - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; + private readonly RedisMessageCreator _messageCreator; private const string QUEUES = "queues"; private readonly ChannelName _queueName; @@ -65,15 +66,20 @@ public partial class RedisMessageConsumer : RedisMessageGateway, IAmAMessageCons /// The topic that the list subscribes to /// The routing key for the dead letter queue, if using Brighter-managed DLQ /// The routing key for the invalid message queue, if using Brighter-managed invalid message handling + /// The used to create loggers for this consumer and the producers it creates public RedisMessageConsumer( RedisMessagingGatewayConfiguration redisMessagingGatewayConfiguration, ChannelName queueName, RoutingKey topic, + ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null) - :base(redisMessagingGatewayConfiguration, topic) + : base(redisMessagingGatewayConfiguration, topic) { + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); + _messageCreator = new RedisMessageCreator((_loggerFactory).CreateLogger()); _queueName = queueName; _redisConfiguration = redisMessagingGatewayConfiguration; _scheduler = scheduler; @@ -104,10 +110,10 @@ public RedisMessageConsumer( /// public void Acknowledge(Message message) { - Log.AcknowledgingMessage(s_logger, message.Id.Value); + Log.AcknowledgingMessage(_logger, message.Id.Value); _inflight.Remove(message.Id.Value); } - + /// /// Acknowledge the message, removing it from the queue /// @@ -171,7 +177,8 @@ public void Dispose() /// public async ValueTask DisposeAsync() { - if (_requeueProducer != null) await _requeueProducer.DisposeAsync(); + if (_requeueProducer != null) + await _requeueProducer.DisposeAsync(); if (_deadLetterProducer?.IsValueCreated == true && _deadLetterProducer.Value is IAsyncDisposable deadLetterAsync) await deadLetterAsync.DisposeAsync(); @@ -186,30 +193,30 @@ public async ValueTask DisposeAsync() await DisposePoolAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } - + /// /// Clear the queue /// public void Purge() { - Log.PurgingChannel(s_logger, _queueName); - + Log.PurgingChannel(_logger, _queueName); + using var client = GetClient(); if (client == null) throw new ChannelFailureException("RedisMessagingGateway: No Redis client available"); - + //This kills the queue, not the messages, which we assume expire client.RemoveAllFromList(_queueName); } - + /// /// Clear the queue /// /// The cancellation token public async Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken)) - { - Log.PurgingChannel(s_logger, _queueName); - + { + Log.PurgingChannel(_logger, _queueName); + await using var client = await GetClientAsync(cancellationToken); if (client == null) throw new ChannelFailureException("RedisMessagingGateway: No Redis client available"); @@ -225,46 +232,46 @@ public void Purge() /// The message read from the list public Message[] Receive(TimeSpan? timeOut = null) { - Log.RetrievingNextMessage(s_logger, _queueName, Topic); + Log.RetrievingNextMessage(_logger, _queueName, Topic); if (_inflight.Any()) { - Log.UnackedMessageInFlight(s_logger, _queueName); - throw new ChannelFailureException($"Unacked message still in flight with id: {_inflight.Keys.First()}"); + Log.UnackedMessageInFlight(_logger, _queueName); + throw new ChannelFailureException($"Unacked message still in flight with id: {_inflight.Keys.First()}"); } - + if (timeOut == null || timeOut.GetValueOrDefault().TotalSeconds < 1) { timeOut = TimeSpan.FromSeconds(1); } - + try { var client = GetClient(); if (client == null) throw new ChannelFailureException("RedisMessagingGateway: No Redis client available"); - + EnsureConnection(client); (string? msgId, string rawMsg) redisMessage = ReadMessage(client, timeOut.Value); if (redisMessage.msgId == null || string.IsNullOrEmpty(redisMessage.rawMsg)) return []; - - var message = RedisMessageCreator.CreateMessage(redisMessage.rawMsg); + + var message = _messageCreator.CreateMessage(redisMessage.rawMsg); if (message.Header.MessageType != MessageType.MT_NONE && message.Header.MessageType != MessageType.MT_UNACCEPTABLE) { _inflight.Add(message.Id.Value, redisMessage.msgId); } - + return [message]; } catch (TimeoutException te) { - Log.CouldNotConnectToRedisClient(s_logger, timeOut.Value.TotalMilliseconds.ToString(CultureInfo.CurrentCulture)); + Log.CouldNotConnectToRedisClient(_logger, timeOut.Value.TotalMilliseconds.ToString(CultureInfo.CurrentCulture)); throw new ChannelFailureException($"Could not connect to Redis client within {timeOut.Value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)} milliseconds", te); } catch (RedisException re) { - Log.CouldNotConnectToRedis(s_logger, re.Message); + Log.CouldNotConnectToRedis(_logger, re.Message); throw new ChannelFailureException("Could not connect to Redis client - see inner exception for details", re); } } @@ -277,12 +284,12 @@ public Message[] Receive(TimeSpan? timeOut = null) /// The message read from the list public async Task ReceiveAsync(TimeSpan? timeOut = null, CancellationToken cancellationToken = default(CancellationToken)) { - Log.RetrievingNextMessage(s_logger, _queueName, Topic); + Log.RetrievingNextMessage(_logger, _queueName, Topic); if (_inflight.Any()) { - Log.UnackedMessageInFlight(s_logger, _queueName); - throw new ChannelFailureException($"Unacked message still in flight with id: {_inflight.Keys.First()}"); + Log.UnackedMessageInFlight(_logger, _queueName); + throw new ChannelFailureException($"Unacked message still in flight with id: {_inflight.Keys.First()}"); } timeOut ??= TimeSpan.FromSeconds(1); @@ -291,13 +298,13 @@ public Message[] Receive(TimeSpan? timeOut = null) await using IRedisClientAsync? client = await GetClientAsync(cancellationToken); if (client == null) throw new ChannelFailureException("RedisMessagingGateway: No Redis client available"); - + await EnsureConnectionAsync(client); (string? msgId, string rawMsg) redisMessage = await ReadMessageAsync(client, timeOut.Value); if (redisMessage.msgId == null || string.IsNullOrEmpty(redisMessage.rawMsg)) return []; - - var message = RedisMessageCreator.CreateMessage(redisMessage.rawMsg); + + var message = _messageCreator.CreateMessage(redisMessage.rawMsg); if (message.Header.MessageType != MessageType.MT_NONE && message.Header.MessageType != MessageType.MT_UNACCEPTABLE) { @@ -308,12 +315,12 @@ public Message[] Receive(TimeSpan? timeOut = null) } catch (TimeoutException te) { - Log.CouldNotConnectToRedisClient(s_logger, timeOut.Value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)); + Log.CouldNotConnectToRedisClient(_logger, timeOut.Value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)); throw new ChannelFailureException($"Could not connect to Redis client within {timeOut.Value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)} milliseconds", te); } catch (RedisException re) { - Log.CouldNotConnectToRedis(s_logger, re.Message); + Log.CouldNotConnectToRedis(_logger, re.Message); throw new ChannelFailureException("Could not connect to Redis client - see inner exception for details", re); } } @@ -328,7 +335,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); _inflight.Remove(message.Id.Value); return true; @@ -348,7 +355,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -359,18 +366,18 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (producer != null) { producer.Send(message); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // DLQ send failed — the message was already popped from Redis so we cannot // requeue it. Remove from inflight to prevent blocking subsequent receives. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); _inflight.Remove(message.Id.Value); return true; } @@ -390,7 +397,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (_deadLetterProducer == null && _invalidMessageProducer == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); _inflight.Remove(message.Id.Value); return true; @@ -410,7 +417,7 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); if (routingKey == _invalidMessageRoutingKey) producer = _invalidMessageProducer?.Value; @@ -421,18 +428,18 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { // DLQ send failed — the message was already popped from Redis so we cannot // requeue it. Remove from inflight to prevent blocking subsequent receives. - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); _inflight.Remove(message.Id.Value); return true; } @@ -489,7 +496,7 @@ public bool Requeue(Message message, TimeSpan? delay = null) } else { - Log.MessageNotFoundInFlight(s_logger, message.Id.Value); + Log.MessageNotFoundInFlight(_logger, message.Id.Value); return false; } } @@ -543,17 +550,18 @@ public bool Requeue(Message message, TimeSpan? delay = null) } else { - Log.MessageNotFoundInFlight(s_logger, message.Id.Value); + Log.MessageNotFoundInFlight(_logger, message.Id.Value); return false; } } - + private void EnsureRequeueProducer() { LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, ref _requeueProducerLock, () => new RedisMessageProducer( _redisConfiguration, - new RedisMessagePublication { Topic = Topic }) + new RedisMessagePublication { Topic = Topic }, + loggerFactory: _loggerFactory) { Scheduler = _scheduler }); @@ -561,32 +569,36 @@ private void EnsureRequeueProducer() private RedisMessageProducer? CreateDeadLetterProducer() { - if (_deadLetterRoutingKey == null) return null; + if (_deadLetterRoutingKey == null) + return null; try { return new RedisMessageProducer(_redisConfiguration, - new RedisMessagePublication { Topic = _deadLetterRoutingKey }); + new RedisMessagePublication { Topic = _deadLetterRoutingKey }, + loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingDlqProducer(s_logger, e, _deadLetterRoutingKey.Value); + Log.ErrorCreatingDlqProducer(_logger, e, _deadLetterRoutingKey.Value); return null; } } private RedisMessageProducer? CreateInvalidMessageProducer() { - if (_invalidMessageRoutingKey == null) return null; + if (_invalidMessageRoutingKey == null) + return null; try { return new RedisMessageProducer(_redisConfiguration, - new RedisMessagePublication { Topic = _invalidMessageRoutingKey }); + new RedisMessagePublication { Topic = _invalidMessageRoutingKey }, + loggerFactory: _loggerFactory); } catch (Exception e) { - Log.ErrorCreatingInvalidMessageProducer(s_logger, e, _invalidMessageRoutingKey.Value); + Log.ErrorCreatingInvalidMessageProducer(_logger, e, _invalidMessageRoutingKey.Value); return null; } } @@ -597,7 +609,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea message.Header.Bag["rejectionTimestamp"] = DateTimeOffset.UtcNow.ToString("o"); message.Header.Bag["originalMessageType"] = message.Header.MessageType.ToString(); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -638,11 +651,11 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea { throw new ChannelFailureException("RedisMessagingGateway: Timeout on getting client from pool", te); } - catch(RedisException re) + catch (RedisException re) { throw new ChannelFailureException("RedisMessagingGateway: Error on getting client from pool", re); } - catch(ObjectDisposedException ode) + catch (ObjectDisposedException ode) { throw new ChannelFailureException("RedisMessagingGateway: Connection pool has been disposed", ode); } @@ -659,28 +672,28 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea { throw new ChannelFailureException("RedisMessagingGateway: Timeout on getting client from pool", te); } - catch(RedisException re) + catch (RedisException re) { throw new ChannelFailureException("RedisMessagingGateway: Error on getting client from pool", re); } - catch(ObjectDisposedException ode) + catch (ObjectDisposedException ode) { throw new ChannelFailureException("RedisMessagingGateway: Connection pool has been disposed", ode); } } - + private void EnsureConnection(IRedisClient client) { - Log.CreatingQueue(s_logger, _queueName); + Log.CreatingQueue(_logger, _queueName); //what is the queue list key var key = Topic + "." + QUEUES; //subscribe us client.AddItemToSet(key, _queueName); } - + private async Task EnsureConnectionAsync(IRedisClientAsync client) { - Log.CreatingQueue(s_logger, _queueName); + Log.CreatingQueue(_logger, _queueName); //what is the queue list key var key = Topic + "." + QUEUES; //subscribe us @@ -695,15 +708,15 @@ private async Task EnsureConnectionAsync(IRedisClientAsync client) { var key = Topic + "." + latestId; msg = client.GetValue(key); - Log.ReceivedMessageFromQueue(s_logger, _queueName, Topic, JsonSerializer.Serialize(msg, JsonSerialisationOptions.Options)); + Log.ReceivedMessageFromQueue(_logger, _queueName, Topic, JsonSerializer.Serialize(msg, JsonSerialisationOptions.Options)); } else { - Log.TimeoutWithoutReceivingMessage(s_logger, _queueName, Topic); + Log.TimeoutWithoutReceivingMessage(_logger, _queueName, Topic); } return (latestId, msg); } - + private async Task<(string? msgId, string rawMsg)> ReadMessageAsync(IRedisClientAsync client, TimeSpan timeOut) { var msg = string.Empty; @@ -718,18 +731,18 @@ private async Task EnsureConnectionAsync(IRedisClientAsync client) { var key = Topic + "." + latestId; msg = await client.GetValueAsync(key); - Log.ReceivedMessageFromQueue(s_logger, _queueName, Topic, JsonSerializer.Serialize(msg, JsonSerialisationOptions.Options)); + Log.ReceivedMessageFromQueue(_logger, _queueName, Topic, JsonSerializer.Serialize(msg, JsonSerialisationOptions.Options)); } } catch (OperationCanceledException) { - Log.TimeoutWithoutReceivingMessage(s_logger, _queueName, Topic); + Log.TimeoutWithoutReceivingMessage(_logger, _queueName, Topic); } catch (RedisException re) when (re.InnerException is OperationCanceledException) { - Log.TimeoutWithoutReceivingMessage(s_logger, _queueName, Topic); + Log.TimeoutWithoutReceivingMessage(_logger, _queueName, Topic); } - + return (latestId, msg); } @@ -740,28 +753,28 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "RedisMessageConsumer: Purging channel {ChannelName}")] public static partial void PurgingChannel(ILogger logger, ChannelName channelName); - + [LoggerMessage(LogLevel.Debug, "RedisMessageConsumer: Preparing to retrieve next message from queue {ChannelName} with routing key {Topic}")] public static partial void RetrievingNextMessage(ILogger logger, ChannelName channelName, RoutingKey topic); - + [LoggerMessage(LogLevel.Error, "RedisMessageConsumer: Preparing to retrieve next message from queue {ChannelName}, but have unacked or not rejected message")] public static partial void UnackedMessageInFlight(ILogger logger, ChannelName channelName); - + [LoggerMessage(LogLevel.Error, "Could not connect to Redis client within {Timeout} milliseconds")] public static partial void CouldNotConnectToRedisClient(ILogger logger, string timeout); - + [LoggerMessage(LogLevel.Error, "Could not connect to Redis: {ErrorMessage}")] public static partial void CouldNotConnectToRedis(ILogger logger, string errorMessage); - + [LoggerMessage(LogLevel.Debug, "RedisMessagingGateway: Creating queue {ChannelName}")] public static partial void CreatingQueue(ILogger logger, ChannelName channelName); - + [LoggerMessage(LogLevel.Information, "Redis: Received message from queue {ChannelName} with routing key {Topic}, message: {Request}")] public static partial void ReceivedMessageFromQueue(ILogger logger, ChannelName channelName, RoutingKey topic, string request); - + [LoggerMessage(LogLevel.Debug, "RedisMessageConsumer: Time out without receiving message from queue {ChannelName} with routing key {Topic}")] public static partial void TimeoutWithoutReceivingMessage(ILogger logger, ChannelName channelName, RoutingKey topic); - + [LoggerMessage(LogLevel.Error, "Expected to find message id {MessageId} in-flight but was not")] public static partial void MessageNotFoundInFlight(ILogger logger, string messageId); diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumerFactory.cs index 1b87556343..73d6e8594c 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumerFactory.cs @@ -22,11 +22,14 @@ THE SOFTWARE. */ #endregion +using Microsoft.Extensions.Logging; + namespace Paramore.Brighter.MessagingGateway.Redis { public class RedisMessageConsumerFactory : IAmAMessageConsumerFactory { private readonly RedisMessagingGatewayConfiguration _configuration; + private readonly ILoggerFactory _loggerFactory; private IAmAMessageScheduler? _scheduler; /// @@ -44,10 +47,12 @@ public IAmAMessageScheduler? Scheduler /// /// The Redis messaging gateway configuration /// The optional message scheduler for delayed requeue support - public RedisMessageConsumerFactory(RedisMessagingGatewayConfiguration configuration, IAmAMessageScheduler? scheduler = null) + /// The used to create loggers for the consumers + public RedisMessageConsumerFactory(RedisMessagingGatewayConfiguration configuration, ILoggerFactory loggerFactory, IAmAMessageScheduler? scheduler = null) { _configuration = configuration; _scheduler = scheduler; + _loggerFactory = loggerFactory; } @@ -67,6 +72,7 @@ public IAmAMessageConsumerSync Create(Subscription subscription) _configuration, subscription.ChannelName!, subscription.RoutingKey, + _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); @@ -94,6 +100,7 @@ public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) _configuration, subscription.ChannelName!, subscription.RoutingKey, + _loggerFactory, _scheduler, deadLetterRoutingKey, invalidMessageRoutingKey); diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageCreator.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageCreator.cs index b6ff8dd350..2911fe0b51 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageCreator.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageCreator.cs @@ -29,7 +29,6 @@ THE SOFTWARE. */ using System.Text.Json; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using ServiceStack; @@ -37,8 +36,13 @@ namespace Paramore.Brighter.MessagingGateway.Redis { public partial class RedisMessageCreator { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); - + private readonly ILogger _logger; + + public RedisMessageCreator(ILogger logger) + { + _logger = logger; + } + /// /// Create a Brighter Message from the Redis raw content /// Expected message shape is: @@ -72,7 +76,7 @@ public partial class RedisMessageCreator /// /// The raw message read from the wire /// - public static Message CreateMessage(string redisMessage) + public Message CreateMessage(string redisMessage) { var message = new Message(); if (redisMessage.IsNullOrEmpty()) @@ -84,53 +88,53 @@ public static Message CreateMessage(string redisMessage) var header = reader.ReadLine(); if (header is null || header.TrimEnd() != " /// The raw header JSON /// - private static MessageHeader ReadHeader(string? headersJson) + private MessageHeader ReadHeader(string? headersJson) { if (headersJson is null) return MessageHeader.FailureMessageHeader(RoutingKey.Empty, Id.Empty); - - var headers = JsonSerializer.Deserialize>(headersJson, JsonSerialisationOptions.Options); - + + var headers = JsonSerializer.Deserialize>(headersJson, JsonSerialisationOptions.Options); + if (headers is null) return MessageHeader.FailureMessageHeader(RoutingKey.Empty, Id.Empty); - + var messageId = ReadMessageId(headers); var timeStamp = ReadTimeStamp(headers); var topic = ReadTopic(headers); @@ -162,14 +166,14 @@ private static MessageHeader ReadHeader(string? headersJson) var replyTo = ReadReplyTo(headers); var contentType = ReadContentType(headers); var correlationId = ReadCorrelationId(headers); - var source = ReadSource(headers); + var source = ReadSource(headers); var type = ReadType(headers); var dataSchema = ReadDataSchema(headers); var subject = ReadSubject(headers); var traceParent = ReadTraceParent(headers); var traceState = ReadTraceState(headers); var baggage = ReadBaggage(headers); - + var messageHeader = new MessageHeader( messageId: messageId.Result, @@ -189,7 +193,8 @@ private static MessageHeader ReadHeader(string? headersJson) traceState: traceState.Result, baggage: baggage.Result); - if (!bag.Success) return messageHeader; + if (!bag.Success) + return messageHeader; var bagResult = bag.Result; foreach (var keyValue in bagResult) @@ -198,7 +203,7 @@ private static MessageHeader ReadHeader(string? headersJson) return messageHeader; } - private static HeaderResult ReadBaggage(Dictionary headers) + private HeaderResult ReadBaggage(Dictionary headers) { if (headers.TryGetValue(HeaderNames.W3C_BAGGAGE, out string? header)) { @@ -208,8 +213,8 @@ private static HeaderResult ReadBaggage(Dictionary head } return new HeaderResult(new Baggage(), false); } - - private static HeaderResult ReadContentType(Dictionary headers) + + private HeaderResult ReadContentType(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CONTENT_TYPE, out string? header)) { @@ -219,54 +224,54 @@ private static HeaderResult ReadBaggage(Dictionary head return new HeaderResult(null, false); } - private static HeaderResult ReadCorrelationId(Dictionary headers) + private HeaderResult ReadCorrelationId(Dictionary headers) { var newCorrelationId = string.Empty; - + if (headers.TryGetValue(HeaderNames.CORRELATION_ID, out string? correlatonId)) { return new HeaderResult(correlatonId, true); } - + return new HeaderResult(newCorrelationId, false); } - - private static HeaderResult ReadDataSchema(Dictionary headers) + + private HeaderResult ReadDataSchema(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_DATA_SCHEMA, out string? header) && Uri.TryCreate(header, UriKind.RelativeOrAbsolute, out Uri? dataSchema)) { return new HeaderResult(dataSchema, true); } - + return new HeaderResult(null, false); } - private static HeaderResult ReadDelay(Dictionary headers) + private HeaderResult ReadDelay(Dictionary headers) { if (headers.TryGetValue(HeaderNames.DELAYED_MILLISECONDS, out string? header)) { if (int.TryParse(header, out int delayedMilliseconds)) { - return new HeaderResult(TimeSpan.FromMilliseconds(delayedMilliseconds), true); + return new HeaderResult(TimeSpan.FromMilliseconds(delayedMilliseconds), true); } } return new HeaderResult(TimeSpan.Zero, true); - } - - private static HeaderResult ReadHandledCount(Dictionary headers) + } + + private HeaderResult ReadHandledCount(Dictionary headers) { if (headers.TryGetValue(HeaderNames.HANDLED_COUNT, out string? header)) { if (int.TryParse(header, out int handledCount)) { - return new HeaderResult(handledCount, true); + return new HeaderResult(handledCount, true); } } - + return new HeaderResult(0, true); } - + /// /// The bag is JSON dictionary, so we just need to serialize that dictionary and set values /// The one thing to watch for here is that we don't know about types in a bag, and as such @@ -275,21 +280,21 @@ private static HeaderResult ReadHandledCount(Dictionary hea /// /// The raw json /// A dictionary, either empty if key missing or matching contents if present (could be mepty) - private static HeaderResult> ReadMessageBag(Dictionary headers) + private HeaderResult> ReadMessageBag(Dictionary headers) { if (headers.TryGetValue(HeaderNames.BAG, out string? header)) { var bag = JsonSerializer.Deserialize>(header, JsonSerialisationOptions.Options); if (bag is null) return new HeaderResult>(new Dictionary(), false); - + return new HeaderResult>(bag, true); } return new HeaderResult>(new Dictionary(), false); } - private static HeaderResult ReadMessageType(Dictionary headers) + private HeaderResult ReadMessageType(Dictionary headers) { if (headers.TryGetValue(HeaderNames.MESSAGE_TYPE, out string? header)) { @@ -298,21 +303,21 @@ private static HeaderResult ReadMessageType(Dictionary(messageType, true); } } - + return new HeaderResult(MessageType.MT_EVENT, true); } - private static HeaderResult ReadMessageId(IDictionary headers) + private HeaderResult ReadMessageId(IDictionary headers) { if (headers.TryGetValue(HeaderNames.MESSAGE_ID, out string? header) && !string.IsNullOrEmpty(header)) { return new HeaderResult(Id.Create(header), true); } - + return new HeaderResult(Id.Random(), true); } - - private static HeaderResult ReadReplyTo(Dictionary headers) + + private HeaderResult ReadReplyTo(Dictionary headers) { if (headers.TryGetValue(HeaderNames.REPLY_TO, out string? header)) { @@ -320,8 +325,8 @@ private static HeaderResult ReadReplyTo(Dictionary h } return new HeaderResult(RoutingKey.Empty, false); } - - private static HeaderResult ReadSource(Dictionary headers) + + private HeaderResult ReadSource(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SOURCE, out string? header) && Uri.TryCreate(header, UriKind.RelativeOrAbsolute, out var source)) @@ -330,8 +335,8 @@ private static HeaderResult ReadReplyTo(Dictionary h } return new HeaderResult(new Uri(MessageHeader.DefaultSource), true); } - - private static HeaderResult ReadSubject(Dictionary headers) + + private HeaderResult ReadSubject(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_SUBJECT, out string? header)) { @@ -340,23 +345,23 @@ private static HeaderResult ReadSubject(Dictionary heade return new HeaderResult(string.Empty, false); } - /// + /// /// Note that RMQ uses a unix timestamp, we just System.Text's JSON date format in Redis /// /// The collection of headers /// The result, always a success because we don't break for missing timestamp, just use now - private static HeaderResult ReadTimeStamp(Dictionary headers) + private HeaderResult ReadTimeStamp(Dictionary headers) { if (headers.TryGetValue(HeaderNames.TIMESTAMP, out string? header) && DateTimeOffset.TryParse(header, out var timestamp)) { return new HeaderResult(timestamp, true); } - + return new HeaderResult(DateTimeOffset.UtcNow, true); } - - private static HeaderResult ReadTraceParent(Dictionary headers) + + private HeaderResult ReadTraceParent(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_PARENT, out string? header)) { @@ -365,7 +370,7 @@ private static HeaderResult ReadTraceParent(Dictionary(TraceParent.Empty, false); } - private static HeaderResult ReadTraceState(Dictionary headers) + private HeaderResult ReadTraceState(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TRACE_STATE, out string? header)) { @@ -373,8 +378,8 @@ private static HeaderResult ReadTraceState(Dictionary(TraceState.Empty, false); } - - private static HeaderResult ReadType(Dictionary headers) + + private HeaderResult ReadType(Dictionary headers) { if (headers.TryGetValue(HeaderNames.CLOUD_EVENTS_TYPE, out string? header)) { @@ -383,7 +388,7 @@ private static HeaderResult ReadType(Dictionary return new HeaderResult(CloudEventsType.Empty, false); } - private static HeaderResult ReadTopic(Dictionary headers) + private HeaderResult ReadTopic(Dictionary headers) { var topic = string.Empty; if (headers.TryGetValue(HeaderNames.TOPIC, out string? header)) @@ -410,5 +415,5 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Expected message to find end of BODY/>, but was {ErrorMessage}")] public static partial void ExpectedBodyEndError(ILogger logger, string errorMessage); } - } + } } diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducer.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducer.cs index 22276a5959..cf8aa824f9 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducer.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducer.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; using ServiceStack.Redis; @@ -56,12 +55,13 @@ We end with a public partial class RedisMessageProducer( RedisMessagingGatewayConfiguration redisMessagingGatewayConfiguration, RedisMessagePublication publication, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentation = InstrumentationOptions.All) : RedisMessageGateway(redisMessagingGatewayConfiguration, publication.Topic!), IAmAMessageProducerSync, IAmAMessageProducerAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - private Publication _publication = publication; + private readonly ILogger _logger = loggerFactory.CreateLogger(); + private Publication _publication = publication; private const string NEXT_ID = "nextid"; private const string QUEUES = "queues"; @@ -71,12 +71,12 @@ public partial class RedisMessageProducer( public Publication Publication { get { return _publication; } - set {_publication = value;} + set { _publication = value; } } /// public Activity? Span { get; set; } - + /// public IAmAMessageScheduler? Scheduler { get; set; } @@ -85,7 +85,7 @@ public void Dispose() DisposePool(); GC.SuppressFinalize(this); } - + public async ValueTask DisposeAsync() { await DisposePoolAsync(); @@ -109,7 +109,7 @@ public async Task SendAsync(Message message, CancellationToken cancellationToken { await SendWithDelayAsync(message, TimeSpan.Zero, cancellationToken); } - + /// /// Sends the specified message. /// @@ -144,18 +144,18 @@ public void SendWithDelay(Message message, TimeSpan? delay = null) Topic = message.Header.Topic; BrighterTracer.WriteProducerEvent(Span, "redis", message, instrumentation); - Log.PreparingToSend(s_logger); - + Log.PreparingToSend(_logger); + var redisMessage = CreateRedisMessage(message); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value); + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value); //increment a counter to get the next message id var nextMsgId = IncrementMessageCounter(client); //store the message, against that id StoreMessage(client, redisMessage, nextMsgId); //If there are subscriber queues, push the message to the subscriber queues var pushedTo = PushToQueues(client, nextMsgId); - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value, string.Join(", ", pushedTo)); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value, string.Join(", ", pushedTo)); } /// @@ -193,18 +193,18 @@ public async Task SendWithDelayAsync(Message message, TimeSpan? delay, Cancellat Topic = message.Header.Topic; BrighterTracer.WriteProducerEvent(Span, "redis", message, instrumentation); - Log.PreparingToSend(s_logger); + Log.PreparingToSend(_logger); var redisMessage = CreateRedisMessage(message); - Log.PublishingMessage(s_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value); + Log.PublishingMessage(_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value); //increment a counter to get the next message id var nextMsgId = await IncrementMessageCounterAsync(client, cancellationToken); //store the message, against that id await StoreMessageAsync(client, redisMessage, nextMsgId); //If there are subscriber queues, push the message to the subscriber queues var pushedTo = await PushToQueuesAsync(client, nextMsgId, cancellationToken); - Log.PublishedMessage(s_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value, string.Join(", ", pushedTo)); + Log.PublishedMessage(_logger, message.Header.Topic.Value, message.Id.ToString(), message.Body.Value, string.Join(", ", pushedTo)); } private HashSet PushToQueues(IRedisClient client, long nextMsgId) @@ -218,7 +218,7 @@ private HashSet PushToQueues(IRedisClient client, long nextMsgId) } return queues; } - + private async Task> PushToQueuesAsync(IRedisClientAsync client, long nextMsgId, CancellationToken cancellationToken = default) { var key = Topic + "." + QUEUES; @@ -238,7 +238,7 @@ private long IncrementMessageCounter(IRedisClient client) var key = Topic + "." + NEXT_ID; return client.IncrementValue(key); } - + private async Task IncrementMessageCounterAsync(IRedisClientAsync client, CancellationToken cancellationToken = default) { //This holds the next id for this topic; we use that to store message contents and signal to queue @@ -254,7 +254,7 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "RedisMessageProducer: Publishing message with topic {Topic} and id {Id} and body: {Request}")] public static partial void PublishingMessage(ILogger logger, string topic, string id, string request); - + [LoggerMessage(LogLevel.Debug, "RedisMessageProducer: Published message with topic {Topic} and id {Id} and body: {Request} to queues: {Queues}")] public static partial void PublishedMessage(ILogger logger, string topic, string id, string request, string queues); } diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducerFactory.cs index 3a240796d6..77f5e2a0da 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducerFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Redis { @@ -35,18 +36,22 @@ public class RedisMessageProducerFactory : IAmAMessageProducerFactory { private readonly RedisMessagingGatewayConfiguration _redisConfiguration; private readonly IEnumerable _publications; + private readonly ILoggerFactory _loggerFactory; /// /// Initializes a new instance of the class. /// /// The configuration settings for connecting to Redis. /// The collection of Redis message publications. + /// The used to create loggers for the producers. public RedisMessageProducerFactory( RedisMessagingGatewayConfiguration redisConfiguration, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) { _redisConfiguration = redisConfiguration; _publications = publications; + _loggerFactory = loggerFactory; } /// @@ -61,11 +66,11 @@ public Dictionary Create() foreach (var publication in _publications) { if (publication.Topic is null) - throw new ConfigurationException("RmqMessageProducerFactory.Create => An RmqPublication must have a topic/routing key"); + throw new ConfigurationException("RmqMessageProducerFactory.Create => An RmqPublication must have a topic/routing key"); - var messageProducer = new RedisMessageProducer(_redisConfiguration, publication); + var messageProducer = new RedisMessageProducer(_redisConfiguration, publication, loggerFactory: _loggerFactory); messageProducer.Publication = publication; - + var producerKey = new ProducerKey(publication.Topic, publication.Type); if (producers.ContainsKey(producerKey)) throw new ArgumentException($"A publication with the topic {publication.Topic} and {publication.Type} already exists in the producer registry. Each topic + type must be unique in the producer registry. If you did not set a type, we will match against an empty type, so you cannot have two publications with the same topic and no type in the producer registry."); diff --git a/src/Paramore.Brighter.MessagingGateway.Redis/RedisProducerRegistryFactory.cs b/src/Paramore.Brighter.MessagingGateway.Redis/RedisProducerRegistryFactory.cs index 00ae75887b..8fa304b289 100644 --- a/src/Paramore.Brighter.MessagingGateway.Redis/RedisProducerRegistryFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.Redis/RedisProducerRegistryFactory.cs @@ -1,12 +1,14 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter.MessagingGateway.Redis { public class RedisProducerRegistryFactory( RedisMessagingGatewayConfiguration redisConfiguration, - IEnumerable publications) + IEnumerable publications, + ILoggerFactory loggerFactory) : IAmAProducerRegistryFactory { /// @@ -15,7 +17,7 @@ public class RedisProducerRegistryFactory( /// A has of middleware clients by topic, for sending messages to the middleware public IAmAProducerRegistry Create() { - var producerFactory = new RedisMessageProducerFactory(redisConfiguration, publications); + var producerFactory = new RedisMessageProducerFactory(redisConfiguration, publications, loggerFactory); return new ProducerRegistry(producerFactory.Create()); } diff --git a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumer.cs index 75e4582dfc..07f37265cd 100644 --- a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumer.cs +++ b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumer.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using Org.Apache.Rocketmq; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; @@ -23,15 +22,17 @@ namespace Paramore.Brighter.MessagingGateway.RocketMQ; /// The gateway connection configuration, used for lazy DLQ producer creation. /// The routing key for the dead letter queue topic. /// The routing key for the invalid message topic. +/// The used to create the logger. public partial class RocketMessageConsumer(SimpleConsumer consumer, int bufferSize, TimeSpan invisibilityTimeout, + ILoggerFactory loggerFactory, RocketMessagingGatewayConnection? connection = null, RoutingKey? deadLetterRoutingKey = null, RoutingKey? invalidMessageRoutingKey = null) : IAmAMessageConsumerAsync, IAmAMessageConsumerSync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private readonly RocketMessagingGatewayConnection? _connection = connection; private readonly RoutingKey? _deadLetterRoutingKey = deadLetterRoutingKey; @@ -42,22 +43,22 @@ public partial class RocketMessageConsumer(SimpleConsumer consumer, private RocketMqMessageProducer? _invalidMessageProducer; /// - public void Acknowledge(Message message) + public void Acknowledge(Message message) => BrighterAsyncContext.Run(() => AcknowledgeAsync(message)); - + /// public async Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default) { if (!message.Header.Bag.TryGetValue("ReceiptHandle", out var handler) || handler is not MessageView view) { - return; + return; } - + await consumer.Ack(view); } - + /// - public void Purge() + public void Purge() => BrighterAsyncContext.Run(() => PurgeAsync()); /// @@ -70,11 +71,11 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) { break; } - + await messages.EachAsync(async message => await consumer.Ack(message)); } } - + /// public Message[] Receive(TimeSpan? timeOut = null) => BrighterAsyncContext.Run(() => ReceiveAsync(timeOut)); @@ -87,16 +88,16 @@ public Message[] Receive(TimeSpan? timeOut = null) { return [new Message()]; } - + var messages = new Message[messageView.Count]; for (int i = 0; i < messageView.Count; i++) { messages[i] = CreateMessage(messageView[i]); } - + return messages; } - + /// public void Nack(Message message) { @@ -123,12 +124,12 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea return false; } - Log.RejectingMessage(s_logger, message.Id.Value); + Log.RejectingMessage(_logger, message.Id.Value); if (_deadLetterRoutingKey == null && _invalidMessageRoutingKey == null) { if (reason != null) - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, reason.RejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, reason.RejectionReason.ToString()); await consumer.Ack(view); return true; @@ -147,7 +148,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea { message.Header.Topic = routingKey!; if (isFallingBackToDlq) - Log.FallingBackToDlq(s_logger, message.Id.Value); + Log.FallingBackToDlq(_logger, message.Id.Value); producer = await GetProducerForRouteAsync(routingKey!); } @@ -155,16 +156,16 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea if (producer != null) { await producer.SendAsync(message, cancellationToken); - Log.MessageSentToRejectionChannel(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.MessageSentToRejectionChannel(_logger, message.Id.Value, rejectionReason.ToString()); } else { - Log.NoChannelsConfiguredForRejection(s_logger, message.Id.Value, rejectionReason.ToString()); + Log.NoChannelsConfiguredForRejection(_logger, message.Id.Value, rejectionReason.ToString()); } } catch (Exception ex) { - Log.ErrorSendingToRejectionChannel(s_logger, ex, message.Id.Value, rejectionReason.ToString()); + Log.ErrorSendingToRejectionChannel(_logger, ex, message.Id.Value, rejectionReason.ToString()); return true; } finally @@ -174,7 +175,7 @@ public async Task RejectAsync(Message message, MessageRejectionReason? rea return true; } - + /// public bool Requeue(Message message, TimeSpan? delay = null) { @@ -182,7 +183,7 @@ public bool Requeue(Message message, TimeSpan? delay = null) { return false; } - + // Waiting for next RocketMQ C# version, due an issue on ChangeInvisibleDuration // consumer.ChangeInvisibleDuration(view, TimeSpan.Zero); return true; @@ -206,7 +207,7 @@ private async Task AckSourceMessageSafeAsync(MessageView view) } catch (Exception ackEx) { - Log.ErrorAckingSourceMessage(s_logger, ackEx); + Log.ErrorAckingSourceMessage(_logger, ackEx); return false; } } @@ -240,7 +241,7 @@ private async Task AckSourceMessageSafeAsync(MessageView view) } catch (Exception ex) { - Log.ErrorCreatingProducer(s_logger, ex, routingKey.Value); + Log.ErrorCreatingProducer(_logger, ex, routingKey.Value); return null; } } @@ -251,7 +252,8 @@ private static void RefreshMetadata(Message message, MessageRejectionReason? rea message.Header.Bag["rejectionTimestamp"] = DateTimeOffset.UtcNow.ToString("o"); message.Header.Bag["originalMessageType"] = message.Header.MessageType.ToString(); - if (reason == null) return; + if (reason == null) + return; message.Header.Bag["rejectionReason"] = reason.RejectionReason.ToString(); if (!string.IsNullOrEmpty(reason.Description)) @@ -300,7 +302,7 @@ private static Message CreateMessage(MessageView message) var traceParent = ReadTraceParent(message); var traceState = ReadTraceState(message); var baggage = ReadBaggage(message); - + var header = new MessageHeader( messageId: messageId, topic: topic, @@ -331,9 +333,9 @@ private static Message CreateMessage(MessageView message) } header.Bag["ReceiptHandle"] = message; - + var body = new MessageBody(message.Body, header.ContentType); - + return new Message(header, body); static RoutingKey ReadTopic(MessageView message) => new(message.Topic); @@ -346,12 +348,12 @@ static Id ReadMessageId(MessageView message) static DateTimeOffset ReadTimeStamp(MessageView message) { - if (message.Properties.TryGetValue(HeaderNames.TimeStamp, out var timestamp) + if (message.Properties.TryGetValue(HeaderNames.TimeStamp, out var timestamp) && DateTimeOffset.TryParse(timestamp, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out var datetime)) { return datetime; } - + if (message.DeliveryTimestamp != null) { return message.DeliveryTimestamp.Value; @@ -359,7 +361,7 @@ static DateTimeOffset ReadTimeStamp(MessageView message) return DateTimeOffset.UtcNow; } - + static MessageType ReadMessageType(MessageView message) { if (message.Properties.TryGetValue(HeaderNames.MessageType, out var type) && Enum.TryParse(type, true, out var messageType)) @@ -387,7 +389,7 @@ static MessageType ReadMessageType(MessageView message) { return null; } - + return new PartitionKey(message.MessageGroup); } @@ -409,7 +411,7 @@ static MessageType ReadMessageType(MessageView message) { return new ContentType(val); } - + val = message.Properties.GetValueOrDefault(HeaderNames.ContentType); if (!string.IsNullOrEmpty(val)) { @@ -421,7 +423,7 @@ static MessageType ReadMessageType(MessageView message) static int ReadHandledCount(MessageView message) { - if (message.Properties.TryGetValue(HeaderNames.HandledCount, out var handledCount) + if (message.Properties.TryGetValue(HeaderNames.HandledCount, out var handledCount) && int.TryParse(handledCount, out var count)) { return count; @@ -432,7 +434,7 @@ static int ReadHandledCount(MessageView message) static TimeSpan ReadDelay(MessageView message) { - if (message.Properties.TryGetValue(HeaderNames.HandledCount, out var delayString) + if (message.Properties.TryGetValue(HeaderNames.HandledCount, out var delayString) && TimeSpan.TryParse(delayString, out var delay)) { return delay; @@ -440,7 +442,7 @@ static TimeSpan ReadDelay(MessageView message) return TimeSpan.Zero; } - + static Uri ReadSource(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.Source); @@ -451,7 +453,7 @@ static Uri ReadSource(MessageView message) return new Uri(MessageHeader.DefaultSource); } - + static string ReadSpecVersion(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.SpecVersion); @@ -462,13 +464,13 @@ static string ReadSpecVersion(MessageView message) return MessageHeader.DefaultSpecVersion; } - + static CloudEventsType ReadType(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.Type); return string.IsNullOrEmpty(val) ? CloudEventsType.Empty : new CloudEventsType(val); } - + static Uri? ReadDataSchema(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.DataSchema); @@ -479,7 +481,7 @@ static CloudEventsType ReadType(MessageView message) return null; } - + static string? ReadSubject(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.Subject); @@ -490,7 +492,7 @@ static CloudEventsType ReadType(MessageView message) return null; } - + static string? ReadDataRef(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.DataRef); @@ -501,7 +503,7 @@ static CloudEventsType ReadType(MessageView message) return null; } - + static TraceParent? ReadTraceParent(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.TraceParent); @@ -512,7 +514,7 @@ static CloudEventsType ReadType(MessageView message) return null; } - + static TraceState? ReadTraceState(MessageView message) { var val = message.Properties.GetValueOrDefault(HeaderNames.TraceState); @@ -523,7 +525,7 @@ static CloudEventsType ReadType(MessageView message) return null; } - + static Baggage ReadBaggage(MessageView message) { var baggage = new Baggage(); diff --git a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumerFactory.cs index c328696c29..d199d5178e 100644 --- a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumerFactory.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Org.Apache.Rocketmq; using Paramore.Brighter.Tasks; @@ -9,14 +10,14 @@ namespace Paramore.Brighter.MessagingGateway.RocketMQ; /// RocketMQ message producer implementation for Brighter. /// Integrates RocketMQ's producer group pattern and transactional message support. /// -public class RocketMessageConsumerFactory(RocketMessagingGatewayConnection connection) : IAmAMessageConsumerFactory +public class RocketMessageConsumerFactory(RocketMessagingGatewayConnection connection, ILoggerFactory loggerFactory) : IAmAMessageConsumerFactory { /// public IAmAMessageConsumerSync Create(Subscription subscription) => BrighterAsyncContext.Run(() => CreateConsumerAsync(subscription)); /// - public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) + public IAmAMessageConsumerAsync CreateAsync(Subscription subscription) => BrighterAsyncContext.Run(() => CreateConsumerAsync(subscription)); internal async Task CreateConsumerAsync(Subscription subscription) @@ -27,7 +28,7 @@ internal async Task CreateConsumerAsync(Subscription subs } var builder = new SimpleConsumer.Builder(); - + builder.SetClientConfig(connection.ClientConfig) .SetConsumerGroup(rocketSubscription.ConsumerGroup) .SetAwaitDuration(rocketSubscription.ReceiveMessageTimeout) @@ -41,6 +42,6 @@ internal async Task CreateConsumerAsync(Subscription subs var consumer = await builder.Build(); return new RocketMessageConsumer(consumer, rocketSubscription.BufferSize, - rocketSubscription.InvisibilityTimeout, connection, deadLetterRoutingKey, invalidMessageRoutingKey); + rocketSubscription.InvisibilityTimeout, loggerFactory, connection, deadLetterRoutingKey, invalidMessageRoutingKey); } } diff --git a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageProducerFactory.cs b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageProducerFactory.cs index c13257969e..a3511b9666 100644 --- a/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageProducerFactory.cs +++ b/src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageProducerFactory.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Org.Apache.Rocketmq; -using Paramore.Brighter.Logging; using Paramore.Brighter.Tasks; namespace Paramore.Brighter.MessagingGateway.RocketMQ; @@ -12,12 +11,15 @@ namespace Paramore.Brighter.MessagingGateway.RocketMQ; /// Factory class for creating RocketMQ message producers in Brighter. /// Implements RocketMQ's producer group pattern and transactional message support. /// -public partial class RocketMessageProducerFactory(RocketMessagingGatewayConnection connection, IEnumerable publications) : IAmAMessageProducerFactory +/// The gateway connection configuration. +/// The publications to create producers for. +/// The used to create the logger. +public partial class RocketMessageProducerFactory(RocketMessagingGatewayConnection connection, IEnumerable publications, ILoggerFactory loggerFactory) : IAmAMessageProducerFactory { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - + private readonly ILogger _logger = loggerFactory.CreateLogger(); + /// - public Dictionary Create() + public Dictionary Create() => BrighterAsyncContext.Run(() => CreateAsync()); /// @@ -34,9 +36,9 @@ public async Task> CreateAsync() if (publication.MakeChannels == OnMissingChannel.Create) { - Log.CreateTopicIsNotSupported(s_logger, publication.Topic!.Value); + Log.CreateTopicIsNotSupported(_logger, publication.Topic!.Value); } - + producers[new ProducerKey(publication.Topic, publication.Type)] = new RocketMqMessageProducer(connection, rocketProducer, publication, @@ -51,7 +53,7 @@ private async Task CreateProducerAsync() builder.SetClientConfig(connection.ClientConfig) .SetMaxAttempts(connection.MaxAttempts) .SetTopics(publications - .Where(x => !RoutingKey.IsNullOrEmpty(x.Topic)) + .Where(x => !RoutingKey.IsNullOrEmpty(x.Topic)) .Select(x => x.Topic!.Value) .ToArray()); @@ -59,10 +61,10 @@ private async Task CreateProducerAsync() { builder.SetTransactionChecker(connection.Checker); } - - return await builder.Build(); + + return await builder.Build(); } - + private static partial class Log { [LoggerMessage(LogLevel.Warning, "RocketMQ doesn't support create topic via code ({Topic})")] diff --git a/src/Paramore.Brighter.MsSql/MsSqlConnectionProvider.cs b/src/Paramore.Brighter.MsSql/MsSqlConnectionProvider.cs index 9fb7dfaee8..8e3694897c 100644 --- a/src/Paramore.Brighter.MsSql/MsSqlConnectionProvider.cs +++ b/src/Paramore.Brighter.MsSql/MsSqlConnectionProvider.cs @@ -17,7 +17,7 @@ public class MsSqlConnectionProvider : RelationalDbConnectionProvider /// Create a connection provider for MSSQL using a connection string for Db access /// /// The configuration for this database - public MsSqlConnectionProvider(IAmARelationalDatabaseConfiguration configuration) + public MsSqlConnectionProvider(IAmARelationalDatabaseConfiguration? configuration) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) throw new ArgumentNullException(nameof(configuration.ConnectionString)); diff --git a/src/Paramore.Brighter.MsSql/MsSqlTransactionProvider.cs b/src/Paramore.Brighter.MsSql/MsSqlTransactionProvider.cs index c84cf631d4..9dcfc1d826 100644 --- a/src/Paramore.Brighter.MsSql/MsSqlTransactionProvider.cs +++ b/src/Paramore.Brighter.MsSql/MsSqlTransactionProvider.cs @@ -17,7 +17,7 @@ public class MsSqlTransactionProvider : RelationalDbTransactionProvider /// Create a connection provider for MSSQL using a connection string for Db access /// /// The configuration for this database - public MsSqlTransactionProvider(IAmARelationalDatabaseConfiguration configuration) + public MsSqlTransactionProvider(IAmARelationalDatabaseConfiguration? configuration) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) throw new ArgumentNullException(nameof(configuration.ConnectionString)); diff --git a/src/Paramore.Brighter.MySql/MySqlConnectionProvider.cs b/src/Paramore.Brighter.MySql/MySqlConnectionProvider.cs index 91b02e2a1e..d7ab66f005 100644 --- a/src/Paramore.Brighter.MySql/MySqlConnectionProvider.cs +++ b/src/Paramore.Brighter.MySql/MySqlConnectionProvider.cs @@ -43,7 +43,7 @@ public class MySqlConnectionProvider : RelationalDbConnectionProvider /// Initialise a new instance of MySql Connection provider from a connection string /// /// MySql Configuration - public MySqlConnectionProvider(IAmARelationalDatabaseConfiguration configuration) + public MySqlConnectionProvider(IAmARelationalDatabaseConfiguration? configuration) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) throw new ArgumentNullException(nameof(configuration.ConnectionString)); diff --git a/src/Paramore.Brighter.MySql/MySqlTransactionProvider.cs b/src/Paramore.Brighter.MySql/MySqlTransactionProvider.cs index 29ddc0c1fb..5ee03e5162 100644 --- a/src/Paramore.Brighter.MySql/MySqlTransactionProvider.cs +++ b/src/Paramore.Brighter.MySql/MySqlTransactionProvider.cs @@ -43,7 +43,7 @@ public class MySqlTransactionProvider : RelationalDbTransactionProvider /// Initialise a new instance of MySql Connection provider from a connection string /// /// MySql Configuration - public MySqlTransactionProvider(IAmARelationalDatabaseConfiguration configuration) + public MySqlTransactionProvider(IAmARelationalDatabaseConfiguration? configuration) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) throw new ArgumentNullException(nameof(configuration.ConnectionString)); diff --git a/src/Paramore.Brighter.Outbox.DynamoDB.V4/DynamoDbOutbox.cs b/src/Paramore.Brighter.Outbox.DynamoDB.V4/DynamoDbOutbox.cs index ae2066708e..8406650500 100644 --- a/src/Paramore.Brighter.Outbox.DynamoDB.V4/DynamoDbOutbox.cs +++ b/src/Paramore.Brighter.Outbox.DynamoDB.V4/DynamoDbOutbox.cs @@ -342,7 +342,7 @@ public IEnumerable DispatchedMessages( /// public async Task> DispatchedMessagesAsync( TimeSpan dispatchedSince, - RequestContext requestContext, + RequestContext? requestContext, int pageSize = 100, int pageNumber = 1, int outboxTimeout = -1, @@ -402,7 +402,7 @@ public Message Get(Id messageId, RequestContext requestContext, int outBoxTimeou /// public async Task GetAsync( Id messageId, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) @@ -437,7 +437,7 @@ public IEnumerable Get(IEnumerable messageIds, RequestContext reque /// public async Task> GetAsync( IEnumerable messageIds, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) @@ -478,7 +478,7 @@ public async Task> GetAsync( /// Allows the sender to cancel the request pipeline. Optional public async Task MarkDispatchedAsync( Id id, - RequestContext requestContext, + RequestContext? requestContext, DateTimeOffset? dispatchedAt = null, Dictionary? args = null, CancellationToken cancellationToken = default) diff --git a/src/Paramore.Brighter.Outbox.DynamoDB/DynamoDbOutbox.cs b/src/Paramore.Brighter.Outbox.DynamoDB/DynamoDbOutbox.cs index b9bb1c1c7a..f1446b60b7 100644 --- a/src/Paramore.Brighter.Outbox.DynamoDB/DynamoDbOutbox.cs +++ b/src/Paramore.Brighter.Outbox.DynamoDB/DynamoDbOutbox.cs @@ -329,7 +329,7 @@ public IEnumerable DispatchedMessages( /// public async Task> DispatchedMessagesAsync( TimeSpan dispatchedSince, - RequestContext requestContext, + RequestContext? requestContext, int pageSize = 100, int pageNumber = 1, int outboxTimeout = -1, @@ -389,7 +389,7 @@ public Message Get(Id messageId, RequestContext requestContext, int outBoxTimeou /// public async Task GetAsync( Id messageId, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) @@ -424,7 +424,7 @@ public IEnumerable Get(IEnumerable messageIds, RequestContext reque /// public async Task> GetAsync( IEnumerable messageIds, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) @@ -465,7 +465,7 @@ public async Task> GetAsync( /// Allows the sender to cancel the request pipeline. Optional public async Task MarkDispatchedAsync( Id id, - RequestContext requestContext, + RequestContext? requestContext, DateTimeOffset? dispatchedAt = null, Dictionary? args = null, CancellationToken cancellationToken = default) diff --git a/src/Paramore.Brighter.Outbox.Firestore/FirestoreOutbox.cs b/src/Paramore.Brighter.Outbox.Firestore/FirestoreOutbox.cs index d93cdbd859..60525cafef 100644 --- a/src/Paramore.Brighter.Outbox.Firestore/FirestoreOutbox.cs +++ b/src/Paramore.Brighter.Outbox.Firestore/FirestoreOutbox.cs @@ -1120,7 +1120,7 @@ public async Task> GetAsync(int pageSize = 100, int pageNum /// The Timeout of the outbox. /// /// A list of messages - public async Task> GetAsync(IEnumerable messageIds, RequestContext requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) + public async Task> GetAsync(IEnumerable messageIds, RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) { var ids = messageIds.Select(id => id.Value).ToArray(); diff --git a/src/Paramore.Brighter.Outbox.Hosting/HostedServiceCollectionExtensions.cs b/src/Paramore.Brighter.Outbox.Hosting/HostedServiceCollectionExtensions.cs index 4bee42857b..842f2191cf 100644 --- a/src/Paramore.Brighter.Outbox.Hosting/HostedServiceCollectionExtensions.cs +++ b/src/Paramore.Brighter.Outbox.Hosting/HostedServiceCollectionExtensions.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions.DependencyInjection; using Paramore.Brighter.Observability; @@ -43,7 +44,7 @@ public static IBrighterBuilder UseOutboxSweeper(this IBrighterBuilder brighterBu { var options = new TimedOutboxSweeperOptions(); timedOutboxSweeperOptionsAction?.Invoke(options); - + brighterBuilder.Services.TryAddSingleton(options); brighterBuilder.Services.AddHostedService(); return brighterBuilder; @@ -60,11 +61,12 @@ public static IBrighterBuilder UseOutboxArchiver(this IBrighterBui brighterBuilder.Services.TryAddSingleton(provider => new OutboxArchiver( provider.GetRequiredService(), provider.GetRequiredService(), + provider.GetRequiredService(), provider.GetService(), options.ArchiveBatchSize, provider.GetService(), options.Instrumentation)); - + brighterBuilder.Services.AddHostedService>(); return brighterBuilder; diff --git a/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxArchiver.cs b/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxArchiver.cs index 57549766d7..0fb88fd697 100644 --- a/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxArchiver.cs +++ b/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxArchiver.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2024 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; // ReSharper disable StaticMemberInGenericType namespace Paramore.Brighter.Outbox.Hosting @@ -37,7 +36,7 @@ namespace Paramore.Brighter.Outbox.Hosting /// public partial class TimedOutboxArchiver : IHostedService, IDisposable where TMessage : Message { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private Timer? _timer; private readonly OutboxArchiver _archiver; private readonly IDistributedLock _distributedLock; @@ -49,14 +48,17 @@ public partial class TimedOutboxArchiver : IHostedServic /// The archiver to use /// Used to ensure that only one instance of the is running /// The that control how the archiver runs, such as interval + /// The logger. public TimedOutboxArchiver( OutboxArchiver archiver, IDistributedLock distributedLock, - TimedOutboxArchiverOptions options) + TimedOutboxArchiverOptions options, + ILogger> logger) { _archiver = archiver; _distributedLock = distributedLock; _options = options; + _logger = logger; } private const string LockingResourceName = "Archiver"; @@ -68,9 +70,9 @@ public TimedOutboxArchiver( /// A completed task to allow other background services to run public Task StartAsync(CancellationToken cancellationToken) { - Log.OutboxArchiverServiceIsStarting(s_logger); + Log.OutboxArchiverServiceIsStarting(_logger); - _timer = new Timer(_ => Archive(cancellationToken).GetAwaiter().GetResult(), + _timer = new Timer(_ => Archive(cancellationToken).GetAwaiter().GetResult(), null, TimeSpan.Zero, TimeSpan.FromSeconds(_options.TimerInterval)); @@ -85,7 +87,7 @@ public Task StartAsync(CancellationToken cancellationToken) /// A completed task to allow other background services to run public Task StopAsync(CancellationToken cancellationToken) { - Log.OutboxArchiverServiceIsStopping(s_logger); + Log.OutboxArchiverServiceIsStopping(_logger); _timer?.Change(Timeout.Infinite, 0); @@ -107,11 +109,11 @@ private async Task Archive(CancellationToken cancellationToken) var lockId = await _distributedLock.ObtainLockAsync(LockingResourceName, cancellationToken); if (lockId == null) { - Log.OutboxArchiverIsStillRunningAbandoningAttempt(s_logger); + Log.OutboxArchiverIsStillRunningAbandoningAttempt(_logger); return; } - Log.OutboxArchiverLookingForMessagesToArchive(s_logger); + Log.OutboxArchiverLookingForMessagesToArchive(_logger); try { if (_archiver.HasAsyncOutbox()) @@ -119,7 +121,7 @@ private async Task Archive(CancellationToken cancellationToken) else if (_archiver.HasOutbox()) await Task.Run(() => _archiver.Archive(_options.MinimumAge, new RequestContext()), cancellationToken); else - Log.NoOutboxConfigured(s_logger); + Log.NoOutboxConfigured(_logger); } finally { @@ -128,11 +130,11 @@ private async Task Archive(CancellationToken cancellationToken) } catch (Exception e) { - Log.ErrorWhileSweepingTheOutbox(s_logger, e); + Log.ErrorWhileSweepingTheOutbox(_logger, e); } finally { - Log.OutboxSweeperSleeping(s_logger); + Log.OutboxSweeperSleeping(_logger); } } @@ -143,7 +145,7 @@ private static partial class Log [LoggerMessage(LogLevel.Information, "Outbox Archiver Service is stopping")] public static partial void OutboxArchiverServiceIsStopping(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Outbox Archiver looking for messages to Archive")] public static partial void OutboxArchiverLookingForMessagesToArchive(ILogger logger); diff --git a/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxSweeper.cs b/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxSweeper.cs index b35b1a43d7..85cdaa1f2e 100644 --- a/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxSweeper.cs +++ b/src/Paramore.Brighter.Outbox.Hosting/TimedOutboxSweeper.cs @@ -30,7 +30,6 @@ THE SOFTWARE. */ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Paramore.Brighter.Outbox.Hosting @@ -44,7 +43,7 @@ public partial class TimedOutboxSweeper : IHostedService, IDisposable private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IDistributedLock _distributedLock; private readonly TimedOutboxSweeperOptions _options; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private Timer? _timer; private const string LockingResourceName = "OutboxSweeper"; @@ -54,15 +53,18 @@ public partial class TimedOutboxSweeper : IHostedService, IDisposable /// Needed to create a scope within which to create a /// Used to ensure that only one instance of the is running /// The that can be used to configure how this runs, such as interval or age + /// The logger. public TimedOutboxSweeper( IServiceScopeFactory serviceScopeFactory, IDistributedLock distributedLock, - TimedOutboxSweeperOptions options + TimedOutboxSweeperOptions options, + ILogger logger ) { _serviceScopeFactory = serviceScopeFactory; _distributedLock = distributedLock; _options = options; + _logger = logger; } /// @@ -72,7 +74,7 @@ TimedOutboxSweeperOptions options /// A completed task to allow other background services to be run public Task StartAsync(CancellationToken cancellationToken) { - Log.OutboxSweeperServiceIsStarting(s_logger); + Log.OutboxSweeperServiceIsStarting(_logger); _timer = new Timer(Sweep, null, TimeSpan.Zero, TimeSpan.FromSeconds(_options.TimerInterval)); @@ -86,7 +88,7 @@ public Task StartAsync(CancellationToken cancellationToken) /// A completed task to allow other background services to be stopped public Task StopAsync(CancellationToken cancellationToken) { - Log.OutboxSweeperServiceIsStopping(s_logger); + Log.OutboxSweeperServiceIsStopping(_logger); _timer?.Change(Timeout.Infinite, 0); @@ -106,7 +108,7 @@ private async void Sweep(object? state) var lockId = await _distributedLock.ObtainLockAsync(LockingResourceName, CancellationToken.None); if (lockId != null) { - Log.OutboxSweeperLookingForUnsentMessages(s_logger); + Log.OutboxSweeperLookingForUnsentMessages(_logger); var scope = _serviceScopeFactory.CreateScope(); try @@ -120,23 +122,23 @@ private async void Sweep(object? state) _options.BatchSize, _options.UseBulk, _options.Args); - + await outBoxSweeper.SweepAsync(); } finally { //on a timer thread, so blocking is OK await _distributedLock.ReleaseLockAsync(LockingResourceName, lockId, CancellationToken.None); - + scope.Dispose(); } } else { - Log.OutboxSweeperIsStillRunningAbandoningAttempt(s_logger); + Log.OutboxSweeperIsStillRunningAbandoningAttempt(_logger); } - Log.OutboxSweeperSleeping(s_logger); + Log.OutboxSweeperSleeping(_logger); } private static partial class Log @@ -146,13 +148,13 @@ private static partial class Log [LoggerMessage(LogLevel.Information, "Outbox Sweeper Service is stopping.")] public static partial void OutboxSweeperServiceIsStopping(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Outbox Sweeper looking for unsent messages")] public static partial void OutboxSweeperLookingForUnsentMessages(ILogger logger); - + [LoggerMessage(LogLevel.Warning, "Outbox Sweeper is still running - abandoning attempt.")] public static partial void OutboxSweeperIsStillRunningAbandoningAttempt(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Outbox Sweeper sleeping")] public static partial void OutboxSweeperSleeping(ILogger logger); } diff --git a/src/Paramore.Brighter.Outbox.MsSql/MsSqlOutbox.cs b/src/Paramore.Brighter.Outbox.MsSql/MsSqlOutbox.cs index 5039260791..b73c062d9c 100644 --- a/src/Paramore.Brighter.Outbox.MsSql/MsSqlOutbox.cs +++ b/src/Paramore.Brighter.Outbox.MsSql/MsSqlOutbox.cs @@ -28,7 +28,7 @@ THE SOFTWARE. */ using System.Data.Common; using System.Linq; using Microsoft.Data.SqlClient; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging; using Paramore.Brighter.MsSql; using Paramore.Brighter.Observability; @@ -47,10 +47,12 @@ public class MsSqlOutbox : RelationDatabaseOutbox /// /// The configuration. /// The connection factory. + /// The logger to use. public MsSqlOutbox(IAmARelationalDatabaseConfiguration configuration, - IAmARelationalDbConnectionProvider connectionProvider) + IAmARelationalDbConnectionProvider connectionProvider, + ILogger logger) : base(DbSystem.MsSql, configuration, connectionProvider, - new MsSqlQueries(), ApplicationLogging.CreateLogger()) + new MsSqlQueries(), logger) { } @@ -58,8 +60,9 @@ public MsSqlOutbox(IAmARelationalDatabaseConfiguration configuration, /// Initializes a new instance of the class. /// /// The configuration. - public MsSqlOutbox(IAmARelationalDatabaseConfiguration configuration) : this(configuration, - new MsSqlConnectionProvider(configuration)) + /// The logger to use. + public MsSqlOutbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) : this(configuration, + new MsSqlConnectionProvider(configuration), logger) { } @@ -76,7 +79,7 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, obj { return new SqlParameter { ParameterName = parameterName, Value = dateTimeOffset.ToUniversalTime().DateTime }; } - + return new SqlParameter { ParameterName = parameterName, Value = value ?? DBNull.Value }; } @@ -87,31 +90,31 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, DbT { return new SqlParameter { ParameterName = parameterName, Value = dateTimeOffset.ToUniversalTime().DateTime, DbType = DbType.DateTime }; } - + return new SqlParameter { ParameterName = parameterName, Value = value ?? DBNull.Value, DbType = dbType }; } - - protected override IDbDataParameter[] CreatePagedOutstandingParameters(TimeSpan since, int pageSize, - int pageNumber, IDbDataParameter[] inParams) - { - var parameters = new IDbDataParameter[3]; - parameters[0] = new SqlParameter { ParameterName = "PageNumber", Value = pageNumber }; - parameters[1] = new SqlParameter { ParameterName = "PageSize", Value = pageSize }; - parameters[2] = CreateSqlParameter("DispatchedSince", DateTimeOffset.UtcNow.Subtract(since)); - - return parameters.Concat(inParams).ToArray(); + + protected override IDbDataParameter[] CreatePagedOutstandingParameters(TimeSpan since, int pageSize, + int pageNumber, IDbDataParameter[] inParams) + { + var parameters = new IDbDataParameter[3]; + parameters[0] = new SqlParameter { ParameterName = "PageNumber", Value = pageNumber }; + parameters[1] = new SqlParameter { ParameterName = "PageSize", Value = pageSize }; + parameters[2] = CreateSqlParameter("DispatchedSince", DateTimeOffset.UtcNow.Subtract(since)); + + return parameters.Concat(inParams).ToArray(); } - + protected override IDbDataParameter[] CreatePagedDispatchedParameters(TimeSpan dispatchedSince, int pageSize, int pageNumber) { var parameters = new IDbDataParameter[3]; parameters[0] = new SqlParameter { ParameterName = "PageNumber", Value = pageNumber }; parameters[1] = new SqlParameter { ParameterName = "PageSize", Value = pageSize }; parameters[2] = CreateSqlParameter("DispatchedSince", DateTimeOffset.UtcNow.Subtract(dispatchedSince)); - + return parameters; } - + protected override IDbDataParameter[] CreatePagedReadParameters(int pageSize, int pageNumber) { var parameters = new IDbDataParameter[2]; @@ -128,7 +131,7 @@ protected override DateTimeOffset GetTimeStamp(DbDataReader dr) return DateTimeOffset.UtcNow; } - + var dateTime = sql.GetDateTime(ordinal); return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } diff --git a/src/Paramore.Brighter.Outbox.MySql/MySqlOutbox.cs b/src/Paramore.Brighter.Outbox.MySql/MySqlOutbox.cs index e29b7c7091..7ad4366021 100644 --- a/src/Paramore.Brighter.Outbox.MySql/MySqlOutbox.cs +++ b/src/Paramore.Brighter.Outbox.MySql/MySqlOutbox.cs @@ -26,8 +26,8 @@ THE SOFTWARE. */ using System; using System.Data; using System.Data.Common; +using Microsoft.Extensions.Logging; using MySqlConnector; -using Paramore.Brighter.Logging; using Paramore.Brighter.MySql; using Paramore.Brighter.Observability; @@ -45,10 +45,12 @@ public class MySqlOutbox : RelationDatabaseOutbox /// /// The configuration to connect to this data store /// Provides a connection to the Db that allows us to enlist in an ambient transaction + /// The logger to use. public MySqlOutbox(IAmARelationalDatabaseConfiguration configuration, - IAmARelationalDbConnectionProvider connectionProvider) - : base(DbSystem.MySql, configuration, connectionProvider, - new MySqlQueries(), ApplicationLogging.CreateLogger()) + IAmARelationalDbConnectionProvider connectionProvider, + ILogger logger) + : base(DbSystem.MySql, configuration, connectionProvider, + new MySqlQueries(), logger) { } @@ -56,8 +58,9 @@ public MySqlOutbox(IAmARelationalDatabaseConfiguration configuration, /// Initializes a new instance of the class. /// /// The configuration to connect to this data store - public MySqlOutbox(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new MySqlConnectionProvider(configuration)) + /// The logger to use. + public MySqlOutbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new MySqlConnectionProvider(configuration), logger) { } @@ -78,7 +81,7 @@ protected override bool IsExceptionUniqueOrDuplicateIssue(Exception ex) { return ex is MySqlException { Number: MySqlDuplicateKeyError }; } - + /// protected override DateTimeOffset GetTimeStamp(DbDataReader dr) { @@ -89,7 +92,7 @@ protected override DateTimeOffset GetTimeStamp(DbDataReader dr) var reader = (MySqlDataReader)dr; var dataTime = reader.GetDateTimeOffset(ordinal); - return dataTime; + return dataTime; } } } diff --git a/src/Paramore.Brighter.Outbox.PostgreSql/PostgreSqlOutbox.cs b/src/Paramore.Brighter.Outbox.PostgreSql/PostgreSqlOutbox.cs index e4240b5a7a..9f07822e23 100644 --- a/src/Paramore.Brighter.Outbox.PostgreSql/PostgreSqlOutbox.cs +++ b/src/Paramore.Brighter.Outbox.PostgreSql/PostgreSqlOutbox.cs @@ -26,8 +26,8 @@ THE SOFTWARE. */ using System; using System.Data; using System.Linq; +using Microsoft.Extensions.Logging; using Npgsql; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.PostgreSql; @@ -43,11 +43,13 @@ public class PostgreSqlOutbox : RelationDatabaseOutbox /// /// The configuration to connect to this data store /// Provides a connection to the Db that allows us to enlist in an ambient transaction + /// The logger to use. public PostgreSqlOutbox( IAmARelationalDatabaseConfiguration configuration, - IAmARelationalDbConnectionProvider connectionProvider) - : base(DbSystem.Postgresql, configuration, connectionProvider, - new PostgreSqlQueries(), ApplicationLogging.CreateLogger()) + IAmARelationalDbConnectionProvider connectionProvider, + ILogger logger) + : base(DbSystem.Postgresql, configuration, connectionProvider, + new PostgreSqlQueries(), logger) { } @@ -58,10 +60,12 @@ public PostgreSqlOutbox( /// From v7.0 Npgsql uses an Npgsql data source, leave null to have Brighter manage /// connections; Brighter will not manage type mapping for you in this case so you must register them /// globally + /// The logger to use. public PostgreSqlOutbox( IAmARelationalDatabaseConfiguration configuration, + ILogger logger, NpgsqlDataSource? dataSource = null) - : this(configuration, new PostgreSqlConnectionProvider(configuration, dataSource)) + : this(configuration, new PostgreSqlConnectionProvider(configuration, dataSource), logger) { } diff --git a/src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs b/src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs index a4fd10bfde..dd67684549 100644 --- a/src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs +++ b/src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs @@ -6,7 +6,6 @@ using Google.Cloud.Spanner.Data; using Grpc.Core; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Spanner; @@ -29,11 +28,9 @@ namespace Paramore.Brighter.Outbox.Spanner; /// encapsulates the Spanner-specific SQL queries for outbox operations. /// /// -public class SpannerOutbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider) - : RelationDatabaseOutbox(DbSystem.Spanner, configuration, connectionProvider, new SpannerQueries(), s_logger) +public class SpannerOutbox(IAmARelationalDatabaseConfiguration configuration, IAmARelationalDbConnectionProvider connectionProvider, ILogger logger) + : RelationDatabaseOutbox(DbSystem.Spanner, configuration, connectionProvider, new SpannerQueries(), logger) { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); - /// /// Initializes a new instance of the class with only /// the database configuration. This constructor internally creates a default @@ -41,12 +38,13 @@ public class SpannerOutbox(IAmARelationalDatabaseConfiguration configuration, IA /// /// The configuration settings specific to the relational database, /// including connection string, database name, and outbox table name. - public SpannerOutbox(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new SpannerConnectionProvider(configuration)) + /// The logger to use. + public SpannerOutbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new SpannerConnectionProvider(configuration), logger) { - + } - + /// protected override DbCommand CreateCommand(DbConnection connection, string sqlText, int outBoxTimeout, params IDbDataParameter[] parameters) @@ -90,7 +88,7 @@ protected override IDbDataParameter[] CreatePagedOutstandingParameters(TimeSpan } /// - protected override bool IsExceptionUniqueOrDuplicateIssue(Exception ex) + protected override bool IsExceptionUniqueOrDuplicateIssue(Exception ex) => ex is SpannerException se && se.RpcException.StatusCode == StatusCode.AlreadyExists; /// @@ -107,7 +105,7 @@ protected override IDbDataParameter CreateSqlParameter(string parameterName, DbT { value = dateTimeOffset.DateTime; } - + return new SpannerParameter(parameterName, spannerType, value ?? DBNull.Value); } @@ -115,7 +113,7 @@ private static SpannerDbType ToSpannerDbType(DbType dbType) { return dbType switch { - DbType.String => SpannerDbType.String, + DbType.String => SpannerDbType.String, DbType.DateTimeOffset => SpannerDbType.Timestamp, DbType.Binary => SpannerDbType.Bytes, DbType.Int32 => SpannerDbType.Int64, diff --git a/src/Paramore.Brighter.Outbox.Sqlite/SqliteOutbox.cs b/src/Paramore.Brighter.Outbox.Sqlite/SqliteOutbox.cs index 4ab1a4b746..3dc193a86f 100644 --- a/src/Paramore.Brighter.Outbox.Sqlite/SqliteOutbox.cs +++ b/src/Paramore.Brighter.Outbox.Sqlite/SqliteOutbox.cs @@ -28,7 +28,7 @@ THE SOFTWARE. */ using System.Data.Common; using System.Globalization; using Microsoft.Data.Sqlite; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Sqlite; @@ -47,12 +47,14 @@ public class SqliteOutbox : RelationDatabaseOutbox /// /// The configuration to connect to this data store /// Provides a connection to the Db that allows us to enlist in an ambient transaction + /// The logger to use. public SqliteOutbox( IAmARelationalDatabaseConfiguration configuration, - IAmARelationalDbConnectionProvider connectionProvider + IAmARelationalDbConnectionProvider connectionProvider, + ILogger logger ) - : base(DbSystem.Sqlite, configuration, connectionProvider, - new SqliteQueries(), ApplicationLogging.CreateLogger()) + : base(DbSystem.Sqlite, configuration, connectionProvider, + new SqliteQueries(), logger) { } @@ -60,8 +62,9 @@ IAmARelationalDbConnectionProvider connectionProvider /// Initializes a new instance of the class. /// /// The configuration to connect to this data store - public SqliteOutbox(IAmARelationalDatabaseConfiguration configuration) - : this(configuration, new SqliteConnectionProvider(configuration)) + /// The logger to use. + public SqliteOutbox(IAmARelationalDatabaseConfiguration configuration, ILogger logger) + : this(configuration, new SqliteConnectionProvider(configuration), logger) { } @@ -93,6 +96,6 @@ protected override DateTimeOffset GetTimeStamp(DbDataReader dr) var reader = (SqliteDataReader)dr; var dataTime = reader.GetDateTimeOffset(ordinal); - return dataTime; + return dataTime; } } diff --git a/src/Paramore.Brighter.PostgreSql/PostgreSqlConnectionProvider.cs b/src/Paramore.Brighter.PostgreSql/PostgreSqlConnectionProvider.cs index 262f55ff54..e9a3201317 100644 --- a/src/Paramore.Brighter.PostgreSql/PostgreSqlConnectionProvider.cs +++ b/src/Paramore.Brighter.PostgreSql/PostgreSqlConnectionProvider.cs @@ -22,7 +22,7 @@ public class PostgreSqlConnectionProvider : RelationalDbConnectionProvider /// connections; Brighter will not manage type mapping for you in this case so you must register them /// globally public PostgreSqlConnectionProvider( - IAmARelationalDatabaseConfiguration configuration, + IAmARelationalDatabaseConfiguration? configuration, NpgsqlDataSource? dataSource = null) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) diff --git a/src/Paramore.Brighter.PostgreSql/PostgreSqlTransactionProvider.cs b/src/Paramore.Brighter.PostgreSql/PostgreSqlTransactionProvider.cs index f2f1e5b0e0..e7f3301446 100644 --- a/src/Paramore.Brighter.PostgreSql/PostgreSqlTransactionProvider.cs +++ b/src/Paramore.Brighter.PostgreSql/PostgreSqlTransactionProvider.cs @@ -23,7 +23,7 @@ public class PostgreSqlTransactionProvider : RelationalDbTransactionProvider /// connections; Brighter will not manage type mapping for you in this case so you must register them /// globally public PostgreSqlTransactionProvider( - IAmARelationalDatabaseConfiguration configuration, + IAmARelationalDatabaseConfiguration? configuration, NpgsqlDataSource? dataSource = null) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) diff --git a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs b/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs index baf866b108..351a82165e 100644 --- a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions.DependencyInjection; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.ServiceActivator.Validation; using Paramore.Brighter.Validation; @@ -14,7 +13,7 @@ namespace Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection /// /// Extension methods for adding a service activator to the .NET IoC container /// - public static class ServiceActivatorServiceCollectionExtensions + public static class ServiceActivatorServiceCollectionExtensions { /// /// Adds a service activator to the .NET IoC Container, used to register one or more message pump for a subscription to messages on an external bus @@ -32,16 +31,16 @@ public static IBrighterBuilder AddConsumers( { if (services == null) throw new ArgumentNullException(nameof(services)); - + var options = new ConsumersOptions(); configure?.Invoke(options); services.TryAddSingleton(options); services.TryAddSingleton(options); - + services.TryAdd(new ServiceDescriptor(typeof(IDispatcher), BuildDispatcher, ServiceLifetime.Singleton)); - + services.TryAddSingleton(options.InboxConfiguration); var inbox = options.InboxConfiguration.Inbox; if (inbox is IAmAnInboxSync) @@ -56,7 +55,7 @@ public static IBrighterBuilder AddConsumers( new ServiceDescriptor( typeof(IAmAnInboxAsync), BuildInbox, ServiceLifetime.Singleton)); } - + services.Configure(o => o.ConsumerOwnsValidation = true); RegisterConsumerValidationSpecs(services); @@ -135,28 +134,27 @@ public static IBrighterBuilder AddConsumers( private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider) { - var loggerFactory = serviceProvider.GetService(); - //if not supplied, use the default logger factory, which has no providers - if (loggerFactory != null) - ApplicationLogging.LoggerFactory = loggerFactory; - + //Resolve the container's logger factory and flow it through the builder as an instance, + //rather than copying it into a process-wide static (which would be disposed with the container). + var loggerFactory = serviceProvider.GetRequiredService(); + var options = serviceProvider.GetRequiredService(); - + var commandProcessor = serviceProvider.GetRequiredService(); - + var requestContextFactory = serviceProvider.GetService() ?? new InMemoryRequestContextFactory(); - + var dispatcherBuilder = DispatchBuilder .StartNew() .CommandProcessor(commandProcessor, requestContextFactory); - + var messageMapperRegistry = ServiceCollectionExtensions.MessageMapperRegistry(serviceProvider); var messageTransformFactory = ServiceCollectionExtensions.TransformFactory(serviceProvider); var messageTransformFactoryAsync = ServiceCollectionExtensions.TransformFactoryAsync(serviceProvider); - + var tracer = serviceProvider.GetService(); - var channelFactory = options.DefaultChannelFactory ?? new InMemoryChannelFactory(new InternalBus(), TimeProvider.System); + var channelFactory = options.DefaultChannelFactory ?? new InMemoryChannelFactory(new InternalBus(), TimeProvider.System, loggerFactory); var scheduler = serviceProvider.GetService(); if (channelFactory is IAmAChannelFactoryWithScheduler schedulerAwareFactory) { @@ -180,6 +178,7 @@ private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider) .ChannelFactory(channelFactory) .Subscriptions(options.Subscriptions) .ConfigureInstrumentation(tracer, options.InstrumentationOptions) + .ConfigureLogging(loggerFactory) .Build(ownsRegistry: true, ownsTransformerFactories: true, shutdownTimeout: options.ShutdownTimeout); } diff --git a/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs b/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs index 27d343c6a8..3644774ebe 100644 --- a/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs +++ b/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs @@ -23,6 +23,7 @@ THE SOFTWARE. */ #endregion using System; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.ServiceActivator @@ -40,6 +41,7 @@ internal sealed class ConsumerFactory : IConsumerFactory private readonly IAmAMessageMapperRegistryAsync? _messageMapperRegistryAsync; private readonly IAmAMessageTransformerFactoryAsync? _messageTransformerFactoryAsync; private readonly Func _mapRequestType; + private readonly ILoggerFactory _loggerFactory; public ConsumerFactory( IAmACommandProcessor commandProcessor, @@ -48,6 +50,7 @@ public ConsumerFactory( IAmAMessageTransformerFactory? messageTransformerFactory, IAmARequestContextFactory requestContextFactory, IAmABrighterTracer? tracer, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { _commandProcessor = commandProcessor; @@ -58,9 +61,10 @@ public ConsumerFactory( _requestContextFactory = requestContextFactory; _tracer = tracer; _instrumentationOptions = instrumentationOptions; + _loggerFactory = loggerFactory; _consumerName = new ConsumerName($"{_subscription.Name}-{Uuid.NewAsString()}"); } - + public ConsumerFactory( IAmACommandProcessor commandProcessor, Subscription subscription, @@ -68,6 +72,7 @@ public ConsumerFactory( IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync, IAmARequestContextFactory requestContextFactory, IAmABrighterTracer? tracer, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { _commandProcessor = commandProcessor; @@ -78,6 +83,7 @@ public ConsumerFactory( _requestContextFactory = requestContextFactory; _tracer = tracer; _instrumentationOptions = instrumentationOptions; + _loggerFactory = loggerFactory; _consumerName = new ConsumerName($"{_subscription.Name}-{Uuid.NewAsString()}"); } @@ -93,13 +99,13 @@ private Consumer CreateReactor() { if (_messageMapperRegistry is null || _messageTransformerFactory is null) throw new ArgumentException("Message Mapper Registry and Transform factory must be set"); - + if (_subscription.ChannelFactory is null) throw new ArgumentException("Subscription must have a Channel Factory in order to create a consumer."); - + var channel = _subscription.ChannelFactory.CreateSyncChannel(_subscription); - var messagePump = new Reactor(_commandProcessor, _mapRequestType, _messageMapperRegistry, - _messageTransformerFactory, _requestContextFactory, channel, _tracer, _instrumentationOptions) + var messagePump = new Reactor(_commandProcessor, _mapRequestType, _messageMapperRegistry, + _messageTransformerFactory, _requestContextFactory, channel, _loggerFactory, _tracer, _instrumentationOptions) { Channel = channel, TimeOut = _subscription.TimeOut, @@ -120,10 +126,10 @@ private Consumer CreateProactor() if (_subscription.ChannelFactory is null) throw new ArgumentException("Subscription must have a Channel Factory in order to create a consumer."); - + var channel = _subscription.ChannelFactory.CreateAsyncChannel(_subscription); - var messagePump = new Proactor(_commandProcessor, _mapRequestType, _messageMapperRegistryAsync, - _messageTransformerFactoryAsync, _requestContextFactory, channel, _tracer, _instrumentationOptions) + var messagePump = new Proactor(_commandProcessor, _mapRequestType, _messageMapperRegistryAsync, + _messageTransformerFactoryAsync, _requestContextFactory, channel, _loggerFactory, _tracer, _instrumentationOptions) { Channel = channel, TimeOut = _subscription.TimeOut, diff --git a/src/Paramore.Brighter.ServiceActivator/ConsumerName.cs b/src/Paramore.Brighter.ServiceActivator/ConsumerName.cs index 1a2ddf38ac..07d153e7d4 100644 --- a/src/Paramore.Brighter.ServiceActivator/ConsumerName.cs +++ b/src/Paramore.Brighter.ServiceActivator/ConsumerName.cs @@ -66,7 +66,7 @@ public override string ToString() /// /// The RHS. /// The result of the conversion. - public static implicit operator string?(ConsumerName rhs) + public static implicit operator string?(ConsumerName? rhs) { return rhs?.ToString(); } diff --git a/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs b/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs index 4cfda394d0..7b8e179738 100644 --- a/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs +++ b/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Transactions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.CircuitBreaker; using Paramore.Brighter.Extensions; using Paramore.Brighter.Observability; @@ -58,6 +59,12 @@ public class ControlBusReceiverBuilder : INeedADispatcher, INeedAProducerRegistr private IAmAChannelFactory? _channelFactory; private IDispatcher? _dispatcher; private IAmAProducerRegistryFactory? _producerRegistryFactory; + private readonly ILoggerFactory _loggerFactory; + + private ControlBusReceiverBuilder(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory; + } /// /// We need a dispatcher to pull messages off the control bus and dispatch them out to control bus handlers. @@ -110,9 +117,9 @@ public IAmADispatchBuilder ChannelFactory(IAmAChannelFactory channelFactory) /// Begins the progressive interface. /// /// INeedALogger. - public static INeedADispatcher With() + public static INeedADispatcher With(ILoggerFactory loggerFactory) { - return new ControlBusReceiverBuilder(); + return new ControlBusReceiverBuilder(loggerFactory); } /// @@ -127,7 +134,7 @@ public Dispatcher Build(string hostName) // an internal HandlerFactory to build these for you. // We also need to pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage // the injection of the dependency as part of our handler factory - + var retryPolicy = Policy .Handle() .WaitAndRetry( @@ -151,11 +158,11 @@ public Dispatcher Build(string hostName) var resiliencePipeline = new ResiliencePipelineRegistry() .AddBrighterDefault(); - + var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register(); subscriberRegistry.Register(); - + var incomingMessageMapperRegistry = new MessageMapperRegistry( new ControlBusMessageMapperFactory(), null ); @@ -169,36 +176,39 @@ public Dispatcher Build(string hostName) if (_producerRegistryFactory is null) throw new ArgumentException("Producer Registry Factory must not be null."); - + var producerRegistry = _producerRegistryFactory.Create(); var outbox = new SinkOutboxSync(); - + var mediator = new OutboxProducerMediator( producerRegistry: producerRegistry, resiliencePipelineRegistry: new ResiliencePipelineRegistry().AddBrighterDefault(), mapperRegistry: outgoingMessageMapperRegistry, messageTransformerFactory: new EmptyMessageTransformerFactory(), - messageTransformerFactoryAsync: new EmptyMessageTransformerFactoryAsync(), + messageTransformerFactoryAsync: new EmptyMessageTransformerFactoryAsync(), tracer: new BrighterTracer(), //TODO: Do we need to pass in a tracer? outbox: outbox, outboxCircuitBreaker: new InMemoryOutboxCircuitBreaker(), - publicationFinder: _publicationFinder + publicationFinder: _publicationFinder, + loggerFactory: _loggerFactory ); - if (_dispatcher is null) throw new ArgumentException("Dispatcher must not be null"); + if (_dispatcher is null) + throw new ArgumentException("Dispatcher must not be null"); CommandProcessor? commandProcessor = null; - + commandProcessor = CommandProcessorBuilder.StartNew() - .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactorySync(_dispatcher, () => commandProcessor))) + .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactorySync(_dispatcher, () => commandProcessor, _loggerFactory))) .Resilience(resiliencePipeline, policyRegistry) .ExternalBus(ExternalBusType.FireAndForget, mediator) .ConfigureInstrumentation(null, InstrumentationOptions.None) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(_loggerFactory)) + .ConfigureLogging(_loggerFactory) .Build(); - + // These are the control bus channels, we hardcode them because we want to know they exist, but we use // a base naming scheme to allow centralized management. var subscriptions = new Subscription[] @@ -213,15 +223,17 @@ public Dispatcher Build(string hostName) routingKey: new RoutingKey($"{hostName}.{HEARTBEAT}")) }; - if (_channelFactory is null) throw new ArgumentException("Channel Factory must not be null"); - + if (_channelFactory is null) + throw new ArgumentException("Channel Factory must not be null"); + return DispatchBuilder.StartNew() .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(incomingMessageMapperRegistry, null, null, null) - .ChannelFactory(_channelFactory) + .ChannelFactory(_channelFactory) .Subscriptions(subscriptions) .NoInstrumentation() + .ConfigureLogging(_loggerFactory) .Build(); } @@ -231,8 +243,8 @@ public Dispatcher Build(string hostName) /// private sealed class SinkOutboxSync : IAmAnOutboxSync { - public IAmABrighterTracer? Tracer { private get; set; } - + public IAmABrighterTracer? Tracer { private get; set; } + public void Add(Message message, RequestContext requestContext, int outBoxTimeout = -1, IAmABoxTransactionProvider? transactionProvider = null) { //discard message @@ -240,9 +252,9 @@ public void Add(Message message, RequestContext requestContext, int outBoxTimeou public void Add(IEnumerable messages, RequestContext? requestContext, int outBoxTimeout = -1, IAmABoxTransactionProvider? transactionProvider = null) { - //discard message + //discard message } - + public void Delete(Id[] messageIds, RequestContext? requestContext, Dictionary? args = null) { //ignore @@ -250,7 +262,7 @@ public void Delete(Id[] messageIds, RequestContext? requestContext, Dictionary? args = null) { - return new Message(){Header = new MessageHeader("",new RoutingKey(""), MessageType.MT_NONE)}; + return new Message() { Header = new MessageHeader("", new RoutingKey(""), MessageType.MT_NONE) }; } public IEnumerable Get(IEnumerable messageId, RequestContext requestContext, int outBoxTimeout = -1, Dictionary? args = null) @@ -264,11 +276,11 @@ public void MarkDispatched(Id id, RequestContext requestContext, DateTimeOffset? } public IEnumerable DispatchedMessages( - TimeSpan millisecondsDispatchedSince, + TimeSpan millisecondsDispatchedSince, RequestContext requestContext, - int pageSize = 100, + int pageSize = 100, int pageNumber = 1, - int outboxTimeout = -1, + int outboxTimeout = -1, Dictionary? args = null ) { @@ -276,20 +288,20 @@ public IEnumerable DispatchedMessages( } public IEnumerable OutstandingMessages( - TimeSpan dispatchedSince, + TimeSpan dispatchedSince, RequestContext? requestContext, - int pageSize = 100, + int pageSize = 100, int pageNumber = 1, IEnumerable? trippedTopics = null, Dictionary? args = null) { - return []; + return []; } public IEnumerable OutstandingMessages(TimeSpan dispatchedSince) { - return []; + return []; } public int GetOutstandingMessageCount(TimeSpan dispatchedSince, RequestContext? requestContext, int maxCount = 100, Dictionary? args = null) diff --git a/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs b/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs index 99ae473eb3..843d4f2689 100644 --- a/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs +++ b/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.ServiceActivator @@ -47,6 +48,7 @@ public class DispatchBuilder : INeedACommandProcessor, INeedAChannelFactory, INe private IAmARequestContextFactory? _requestContextFactory; private IAmABrighterTracer? _tracer; private InstrumentationOptions _instrumentationOptions; + private ILoggerFactory? _loggerFactory; private DispatchBuilder() { } @@ -88,16 +90,16 @@ public INeedAChannelFactory MessageMappers( IAmAMessageMapperRegistry messageMapperRegistry, IAmAMessageMapperRegistryAsync? messageMapperRegistryAsync, IAmAMessageTransformerFactory? messageTransformerFactory, - IAmAMessageTransformerFactoryAsync? messageTransformFactoryAsync) + IAmAMessageTransformerFactoryAsync? messageTransformFactoryAsync) { _messageMapperRegistry = messageMapperRegistry; _messageMapperRegistryAsync = messageMapperRegistryAsync; _messageTransformerFactory = messageTransformerFactory; _messageTransformerFactoryAsync = messageTransformFactoryAsync; - + if (messageMapperRegistry is null && messageMapperRegistryAsync is null) throw new ConfigurationException("You must provide a message mapper registry or an async message mapper registry"); - + return this; } @@ -113,7 +115,7 @@ public INeedAListOfSubcriptions ChannelFactory(IAmAChannelFactory defaultChannel _defaultChannelFactory = defaultChannelFactory; return this; } - + /// /// Configures OpenTelemetry for the Dispatcher /// @@ -122,11 +124,11 @@ public INeedAListOfSubcriptions ChannelFactory(IAmAChannelFactory defaultChannel /// INeedAListOfSubcriptions public IAmADispatchBuilder ConfigureInstrumentation(IAmABrighterTracer? tracer, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { - _tracer = tracer; - _instrumentationOptions = instrumentationOptions; - return this; + _tracer = tracer; + _instrumentationOptions = instrumentationOptions; + return this; } - + public IAmADispatchBuilder NoInstrumentation() { _tracer = null; @@ -134,6 +136,13 @@ public IAmADispatchBuilder NoInstrumentation() return this; } + /// + public IAmADispatchBuilder ConfigureLogging(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + return this; + } + /// /// A list of subscriptions i.e. mappings of channels to commands or events /// @@ -150,7 +159,7 @@ public INeedObservability Subscriptions(IEnumerable subscriptions) return this; } - + /// /// Builds this instance. /// @@ -174,11 +183,13 @@ public Dispatcher Build(bool ownsRegistry = false, bool ownsTransformerFactories if (_commandProcessor is null || _subscriptions is null) throw new ArgumentException("Command Processor Factory and Subscription are required."); - return new Dispatcher(_commandProcessor, _subscriptions, _messageMapperRegistry, - _messageMapperRegistryAsync, _messageTransformerFactory, _messageTransformerFactoryAsync, - _requestContextFactory, _tracer, _instrumentationOptions, ownsRegistry, ownsTransformerFactories, - shutdownTimeout - ); + var loggerFactory = _loggerFactory ?? throw new ConfigurationException( + "A logger factory is required. Call ConfigureLogging before Build."); + + return new Dispatcher(_commandProcessor, _subscriptions, loggerFactory, + _messageMapperRegistry, _messageMapperRegistryAsync, _messageTransformerFactory, + _messageTransformerFactoryAsync, _requestContextFactory, _tracer, _instrumentationOptions, + ownsRegistry, ownsTransformerFactories, shutdownTimeout); } @@ -220,7 +231,7 @@ INeedAChannelFactory MessageMappers( IAmAMessageMapperRegistry messageMapperRegistry, IAmAMessageMapperRegistryAsync? messageMapperRegistryAsync, IAmAMessageTransformerFactory? messageTransformerFactory, - IAmAMessageTransformerFactoryAsync? messageTransformFactoryAsync); + IAmAMessageTransformerFactoryAsync? messageTransformFactoryAsync); } /// /// Interface INeedAChannelFactory @@ -264,19 +275,27 @@ public interface INeedObservability /// /// IAmADispatchBuilder IAmADispatchBuilder ConfigureInstrumentation(IAmABrighterTracer? tracer, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All); - + /// /// We do not need any instrumentation for the Dispatcher /// /// IAmADispatchBuilder IAmADispatchBuilder NoInstrumentation(); - } + } /// /// Interface IAmADispatchBuilder /// public interface IAmADispatchBuilder { + /// + /// Supplies the used to create instance-scoped loggers for the + /// and the message pumps it constructs. If not called, a no-op logger factory is used. + /// + /// The logger factory. + /// IAmADispatchBuilder. + IAmADispatchBuilder ConfigureLogging(ILoggerFactory loggerFactory); + /// /// Builds this instance. /// diff --git a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs index a4a239f7aa..e70af0f0ed 100644 --- a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs +++ b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs @@ -31,7 +31,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.ServiceActivator.Status; using BindingFlags = System.Reflection.BindingFlags; @@ -46,7 +45,8 @@ namespace Paramore.Brighter.ServiceActivator /// public partial class Dispatcher : IDispatcher, IDisposable, IAsyncDisposable { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private Task? _controlTask; //an int rather than a bool so Dispose can claim it with a single atomic Interlocked.Exchange, @@ -70,7 +70,7 @@ public partial class Dispatcher : IDispatcher, IDisposable, IAsyncDisposable /// /// The command processor. public IAmACommandProcessor CommandProcessor { get; private set; } - + /// /// Gets the connections. /// @@ -137,10 +137,11 @@ public partial class Dispatcher : IDispatcher, IDisposable, IAsyncDisposable public Dispatcher( IAmACommandProcessor commandProcessor, IEnumerable subscriptions, + ILoggerFactory loggerFactory, IAmAMessageMapperRegistry? messageMapperRegistry = null, IAmAMessageMapperRegistryAsync? messageMapperRegistryAsync = null, IAmAMessageTransformerFactory? messageTransformerFactory = null, - IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync= null, + IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync = null, IAmARequestContextFactory? requestContextFactory = null, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All, @@ -150,7 +151,9 @@ public Dispatcher( { CommandProcessor = commandProcessor; ShutdownTimeout = shutdownTimeout ?? TimeSpan.FromSeconds(10); - + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); + Subscriptions = subscriptions; _messageMapperRegistry = messageMapperRegistry; _messageMapperRegistryAsync = messageMapperRegistryAsync; @@ -164,7 +167,7 @@ public Dispatcher( if (messageMapperRegistry is null && messageMapperRegistryAsync is null) throw new ConfigurationException("You must provide a message mapper registry or an async message mapper registry"); - + //not all pipelines need a transformer factory _messageTransformerFactory ??= new EmptyMessageTransformerFactory(); _messageTransformerFactoryAsync ??= new EmptyMessageTransformerFactoryAsync(); @@ -224,11 +227,11 @@ public void Dispose() try { if (!End().Wait(ShutdownTimeout)) - Log.ShutdownDrainTimedOut(s_logger, ShutdownTimeout.TotalMilliseconds); + Log.ShutdownDrainTimedOut(_logger, ShutdownTimeout.TotalMilliseconds); } catch (Exception e) { - Log.FailedToDrainPumpsOnShutdown(s_logger, e); + Log.FailedToDrainPumpsOnShutdown(_logger, e); } //dispose only what this Dispatcher owns, and each owned factory independently so one factory's fault @@ -253,10 +256,11 @@ public void Dispose() //Disposes a member if it is IDisposable, swallowing and logging any failure so one factory's fault //cannot skip the remaining disposals in the teardown chain. - private static void DisposeQuietly(object? member) + private void DisposeQuietly(object? member) { - try { (member as IDisposable)?.Dispose(); } - catch (Exception e) { Log.FailedToDisposeOwnedResource(s_logger, member?.GetType().Name ?? "null", e); } + try + { (member as IDisposable)?.Dispose(); } + catch (Exception e) { Log.FailedToDisposeOwnedResource(_logger, member?.GetType().Name ?? "null", e); } } /// @@ -290,13 +294,13 @@ public async ValueTask DisposeAsync() { var drain = End(); if (await Task.WhenAny(drain, Task.Delay(ShutdownTimeout)).ConfigureAwait(false) != drain) - Log.ShutdownDrainTimedOut(s_logger, ShutdownTimeout.TotalMilliseconds); + Log.ShutdownDrainTimedOut(_logger, ShutdownTimeout.TotalMilliseconds); else await drain.ConfigureAwait(false); //observe any fault the drain surfaced } catch (Exception e) { - Log.FailedToDrainPumpsOnShutdown(s_logger, e); + Log.FailedToDrainPumpsOnShutdown(_logger, e); } //dispose only what this Dispatcher owns, each independently, preferring the async path. Mirrors the @@ -317,7 +321,7 @@ public async ValueTask DisposeAsync() //Disposes a member through IAsyncDisposable when it offers one, else IDisposable, swallowing and logging //any failure so one factory's fault cannot skip the remaining disposals in the teardown chain. - private static async ValueTask DisposeQuietlyAsync(object? member) + private async ValueTask DisposeQuietlyAsync(object? member) { try { @@ -331,7 +335,7 @@ private static async ValueTask DisposeQuietlyAsync(object? member) break; } } - catch (Exception e) { Log.FailedToDisposeOwnedResource(s_logger, member?.GetType().Name ?? "null", e); } + catch (Exception e) { Log.FailedToDisposeOwnedResource(_logger, member?.GetType().Name ?? "null", e); } } /// @@ -342,7 +346,7 @@ public Task End() { if (State == DispatcherState.DS_RUNNING) { - Log.StoppingDispatcher(s_logger); + Log.StoppingDispatcher(_logger); Consumers.Each(consumer => consumer.Shut(consumer.Subscription.RoutingKey)); } @@ -364,7 +368,7 @@ public void Open(SubscriptionName subscriptionName) /// The subscription. public void Open(Subscription subscription) { - Log.OpeningSubscription(s_logger, subscription.Name.Value); + Log.OpeningSubscription(_logger, subscription.Name.Value); AddSubscriptionToSubscriptions(subscription); var addedConsumers = CreateConsumers([subscription]); @@ -423,7 +427,7 @@ public void Shut(Subscription subscription) { if (State == DispatcherState.DS_RUNNING) { - Log.StoppingSubscription(s_logger, subscription.Name.Value); + Log.StoppingSubscription(_logger, subscription.Name.Value); var consumersForConnection = Consumers.Where(consumer => consumer.Subscription.Name == subscription.Name).ToArray(); var noOfConsumers = consumersForConnection.Length; for (int i = 0; i < noOfConsumers; ++i) @@ -446,7 +450,7 @@ public void SetActivePerformers(string connectionName, int numberOfPerformers) { var subscription = Subscriptions.Single(c => c.Name == connectionName); var currentPerformers = subscription?.NoOfPerformers; - if(currentPerformers == numberOfPerformers) + if (currentPerformers == numberOfPerformers) return; if (subscription is null) throw new ArgumentException("Cannot find Subscription."); @@ -498,7 +502,7 @@ private void RunControlLoop(TaskCompletionSource startup) return; } - Log.DispatcherStarting(s_logger); + Log.DispatcherStarting(_logger); try { @@ -508,17 +512,17 @@ private void RunControlLoop(TaskCompletionSource startup) } catch (Exception ex) { - Log.ErrorOnConsumer(s_logger, ex); + Log.ErrorOnConsumer(_logger, ex); startup.TrySetException(ex); throw; } - Log.DispatcherStartingPerformers(s_logger, _tasks.Count); + Log.DispatcherStartingPerformers(_logger, _tasks.Count); WaitForPerformersToStop(); State = DispatcherState.DS_STOPPED; - Log.DispatcherStopped(s_logger); + Log.DispatcherStopped(_logger); } private void OpenConsumers() @@ -543,7 +547,7 @@ private void WaitForPerformersToStop() { ae.Handle(ex => { - Log.ErrorOnConsumer(s_logger, ex); + Log.ErrorOnConsumer(_logger, ex); return true; }); } @@ -555,7 +559,7 @@ private void HandleNextStoppedPerformer() var runningTasks = _tasks.Values.ToArray(); var index = Task.WaitAny(runningTasks); var stoppingConsumer = runningTasks[index]; - Log.PerformerStopped(s_logger, stoppingConsumer.Status); + Log.PerformerStopped(_logger, stoppingConsumer.Status); RemoveConsumerForTask(stoppingConsumer); @@ -573,7 +577,7 @@ private void RemoveConsumerForTask(Task stoppingConsumer) if (consumer is null) return; - Log.RemovingConsumer(s_logger, consumer.Name.Value); + Log.RemovingConsumer(_logger, consumer.Name.Value); if (_consumers.TryRemove(consumer.Name.Value, out consumer)) { @@ -593,18 +597,18 @@ private IEnumerable CreateConsumers(IEnumerable subscrip }); return list; } - + private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) { - Log.CreatingConsumer(s_logger, consumerNumber, subscription.Name.Value); - + Log.CreatingConsumer(_logger, consumerNumber, subscription.Name.Value); + if (subscription.MessagePumpType == MessagePumpType.Reactor) { if (_messageMapperRegistry is null) throw new ConfigurationException("You must provide a message mapper registry for the Dispatcher to work"); - - var consumerFactory = new ConsumerFactory(CommandProcessor, subscription, _messageMapperRegistry, _messageTransformerFactory, - _requestContextFactory, _tracer, _instrumentationOptions); + + var consumerFactory = new ConsumerFactory(CommandProcessor, subscription, _messageMapperRegistry, _messageTransformerFactory, + _requestContextFactory, _tracer, _loggerFactory, _instrumentationOptions); return consumerFactory.Create(); } @@ -612,9 +616,9 @@ private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) { if (_messageMapperRegistryAsync is null) throw new ConfigurationException("You must provide a message mapper registry for the Dispatcher to work"); - - var consumerFactory = new ConsumerFactory(CommandProcessor, subscription, _messageMapperRegistryAsync, _messageTransformerFactoryAsync, - _requestContextFactory, _tracer, _instrumentationOptions); + + var consumerFactory = new ConsumerFactory(CommandProcessor, subscription, _messageMapperRegistryAsync, _messageTransformerFactoryAsync, + _requestContextFactory, _tracer, _loggerFactory, _instrumentationOptions); return consumerFactory.Create(); } @@ -627,7 +631,7 @@ private static partial class Log [LoggerMessage(LogLevel.Information, "Dispatcher: Opening subscription {ChannelName}")] public static partial void OpeningSubscription(ILogger logger, string channelName); - + [LoggerMessage(LogLevel.Information, "Dispatcher: Stopping subscription {ChannelName}")] public static partial void StoppingSubscription(ILogger logger, string channelName); @@ -648,7 +652,7 @@ private static partial class Log [LoggerMessage(LogLevel.Information, "Dispatcher: Dispatcher stopped")] public static partial void DispatcherStopped(ILogger logger); - + [LoggerMessage(LogLevel.Information, "Dispatcher: Creating consumer number {ConsumerNumber} for subscription: {ChannelName}")] public static partial void CreatingConsumer(ILogger logger, int? consumerNumber, string channelName); diff --git a/src/Paramore.Brighter.ServiceActivator/HostName.cs b/src/Paramore.Brighter.ServiceActivator/HostName.cs index c7ba8d4df7..eb1a9912f7 100644 --- a/src/Paramore.Brighter.ServiceActivator/HostName.cs +++ b/src/Paramore.Brighter.ServiceActivator/HostName.cs @@ -68,7 +68,7 @@ public override string ToString() /// /// The RHS. /// The result of the conversion. - public static implicit operator string?(HostName rhs) + public static implicit operator string?(HostName? rhs) { return rhs?.ToString(); } diff --git a/src/Paramore.Brighter.ServiceActivator/MessagePump.cs b/src/Paramore.Brighter.ServiceActivator/MessagePump.cs index 9138c2e49f..ce6127786a 100644 --- a/src/Paramore.Brighter.ServiceActivator/MessagePump.cs +++ b/src/Paramore.Brighter.ServiceActivator/MessagePump.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter.ServiceActivator @@ -49,8 +48,8 @@ public enum MessagePumpStatus /// The message pump terminated because the unacceptable message was breached within its window MP_LIMIT_EXCEEDED, } - - + + /// /// The message pump is the heart of a consumer. It runs a loop that performs the following: /// - Gets a message from a queue/stream @@ -67,7 +66,13 @@ public enum MessagePumpStatus /// public abstract partial class MessagePump { - internal static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + protected readonly record struct MessagePumpConfiguration( + ILoggerFactory LoggerFactory, + IAmABrighterTracer? Tracer, + InstrumentationOptions InstrumentationOptions, + TimeProvider? TimeProvider); + + protected readonly ILogger _logger; protected const string NoMessageReceivedDescription = "Could not receive message. Note that should return an MT_NONE from an empty queue on timeout"; @@ -79,7 +84,7 @@ public abstract partial class MessagePump protected readonly Dictionary UnWrapPipelineFactoryCache = new(); protected readonly Dictionary DispatchMethodCache = new(); protected DateTimeOffset? UnacceptableMessageWindowOpenedA = null; - + /// /// The delay to wait when the channel has failed /// @@ -95,12 +100,12 @@ public abstract partial class MessagePump /// The delay to wait when the channel is empty /// public TimeSpan EmptyChannelDelay { get; set; } - + /// /// The of this message pump; indicates Reactor or Proactor /// public abstract MessagePumpType MessagePumpType { get; } - + /// /// Sets the used by the pump. Defaults to TimeProviderSystem /// @@ -108,7 +113,7 @@ public abstract partial class MessagePump /// Allows you to override the time provider, intended for testing purposes. /// public TimeProvider PumpTimeProvider { get; set; } - + /// /// How many times to requeue a message before discarding it /// @@ -118,12 +123,12 @@ public abstract partial class MessagePump /// How long to wait before requeuing a message /// public TimeSpan RequeueDelay { get; set; } - + /// /// The of the pump /// public MessagePumpStatus Status { get; set; } - + /// /// How long to wait for a message before timing out /// @@ -133,12 +138,12 @@ public abstract partial class MessagePump /// The number of unacceptable messages to receive before stopping the message pump /// public int UnacceptableMessageLimit { get; set; } - + /// /// Gets the window in which we monitor the unacceptable message count. The count resets at the end of the window. /// If null, the count never resets. /// - public TimeSpan? UnacceptableMessageLimitWindow { get; set; } + public TimeSpan? UnacceptableMessageLimitWindow { get; set; } /// /// Constructs a message pump. The message pump is the heart of a consumer. It runs a loop that performs the following: @@ -149,22 +154,18 @@ public abstract partial class MessagePump /// /// Provides a correctly scoped command processor /// Provides a request synchronizationHelper - /// What is the we will use for telemetry - /// - /// When creating a span for operations how noisy should the attributes be - /// Allows you to override the time provider, for testing purposes + /// Logging, tracing, instrumentation, and time configuration for the pump. protected MessagePump( - IAmACommandProcessor commandProcessor, + IAmACommandProcessor commandProcessor, IAmARequestContextFactory requestContextFactory, - IAmABrighterTracer? tracer, - InstrumentationOptions instrumentationOptions = InstrumentationOptions.All, - TimeProvider? timeProvider = null) + MessagePumpConfiguration configuration) { CommandProcessor = commandProcessor; RequestContextFactory = requestContextFactory; - Tracer = tracer; - InstrumentationOptions = instrumentationOptions; - PumpTimeProvider = timeProvider ?? TimeProvider.System; + Tracer = configuration.Tracer; + InstrumentationOptions = configuration.InstrumentationOptions; + PumpTimeProvider = configuration.TimeProvider ?? TimeProvider.System; + _logger = configuration.LoggerFactory.CreateLogger(); } @@ -177,7 +178,7 @@ protected void IncrementUnacceptableMessageCount() { if (UnacceptableMessageWindowOpenedA is null) UnacceptableMessageWindowOpenedA = PumpTimeProvider.GetUtcNow(); - + var timeSinceWindowOpened = PumpTimeProvider.GetUtcNow() - UnacceptableMessageWindowOpenedA.Value; if (UnacceptableMessageLimitWindow.HasValue && timeSinceWindowOpened > UnacceptableMessageLimitWindow) { @@ -192,12 +193,12 @@ protected void ValidateMessageType(MessageType messageType, IRequest request) { if (messageType == MessageType.MT_COMMAND && request is IEvent) { - Log.MessageMismatchCommand(s_logger, request.Id.Value, MessageType.MT_COMMAND); + Log.MessageMismatchCommand(_logger, request.Id.Value, MessageType.MT_COMMAND); } if (messageType == MessageType.MT_EVENT && request is ICommand) { - Log.MessageMismatchEvent(s_logger, request.Id.Value, MessageType.MT_EVENT); + Log.MessageMismatchEvent(_logger, request.Id.Value, MessageType.MT_EVENT); } } @@ -209,6 +210,6 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Message {MessageId} mismatch. Message type is '{MessageType}' yet mapper produced message of type ICommand")] public static partial void MessageMismatchEvent(ILogger logger, string messageId, MessageType messageType); } - } + } } diff --git a/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs b/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs index fa715dedf2..0452371dcf 100644 --- a/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs +++ b/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs @@ -1,4 +1,5 @@ -using System; +using System; +using Microsoft.Extensions.Logging; using Paramore.Brighter.ServiceActivator.Ports.Handlers; namespace Paramore.Brighter.ServiceActivator.Ports @@ -6,12 +7,17 @@ namespace Paramore.Brighter.ServiceActivator.Ports internal sealed class ControlBusHandlerFactorySync : IAmAHandlerFactorySync { private readonly Func _commandProcessorFactory; + private readonly ILoggerFactory _loggerFactory; private readonly IDispatcher _worker; - public ControlBusHandlerFactorySync(IDispatcher worker, Func commandProcessorFactory) + public ControlBusHandlerFactorySync( + IDispatcher worker, + Func commandProcessorFactory, + ILoggerFactory loggerFactory) { _worker = worker; _commandProcessorFactory = commandProcessorFactory; + _loggerFactory = loggerFactory; } /// @@ -23,7 +29,9 @@ public ControlBusHandlerFactorySync(IDispatcher worker, Func()); if (handlerType == typeof(HeartbeatRequestCommandHandler)) return new HeartbeatRequestCommandHandler(_commandProcessorFactory(), _worker); diff --git a/src/Paramore.Brighter.ServiceActivator/Ports/Handlers/ConfigurationCommandHandler.cs b/src/Paramore.Brighter.ServiceActivator/Ports/Handlers/ConfigurationCommandHandler.cs index 9f5777f385..10c8579d4c 100644 --- a/src/Paramore.Brighter.ServiceActivator/Ports/Handlers/ConfigurationCommandHandler.cs +++ b/src/Paramore.Brighter.ServiceActivator/Ports/Handlers/ConfigurationCommandHandler.cs @@ -24,7 +24,6 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.ServiceActivator.Ports.Commands; namespace Paramore.Brighter.ServiceActivator.Ports.Handlers @@ -34,7 +33,7 @@ namespace Paramore.Brighter.ServiceActivator.Ports.Handlers /// public partial class ConfigurationCommandHandler : RequestHandler { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly IDispatcher _dispatcher; @@ -42,9 +41,11 @@ public partial class ConfigurationCommandHandler : RequestHandler class. /// /// - public ConfigurationCommandHandler(IDispatcher dispatcher) + /// The logger. + public ConfigurationCommandHandler(IDispatcher dispatcher, ILogger logger) { _dispatcher = dispatcher; + _logger = logger; } /// @@ -54,34 +55,34 @@ public ConfigurationCommandHandler(IDispatcher dispatcher) /// TRequest. public override ConfigurationCommand Handle(ConfigurationCommand configurationCommand) { - Log.HandlingConfigurationCommand(s_logger, configurationCommand.Type); + Log.HandlingConfigurationCommand(_logger, configurationCommand.Type); switch (configurationCommand.Type) { case ConfigurationCommandType.CM_STOPALL: - Log.StoppingAllConsumersBegin(s_logger, DateTime.UtcNow.ToString("o")); - Log.LogSeparator(s_logger); - Log.LogEllipsis(s_logger); + Log.StoppingAllConsumersBegin(_logger, DateTime.UtcNow.ToString("o")); + Log.LogSeparator(_logger); + Log.LogEllipsis(_logger); _dispatcher.End().Wait(); - Log.AllConsumersStopped(s_logger, DateTime.UtcNow.ToString("o")); - Log.LogSeparator(s_logger); + Log.AllConsumersStopped(_logger, DateTime.UtcNow.ToString("o")); + Log.LogSeparator(_logger); break; case ConfigurationCommandType.CM_STARTALL: - Log.LogSeparator(s_logger); - Log.StartingAllConsumersBegin(s_logger, DateTime.UtcNow.ToString("o")); - Log.LogSeparator(s_logger); + Log.LogSeparator(_logger); + Log.StartingAllConsumersBegin(_logger, DateTime.UtcNow.ToString("o")); + Log.LogSeparator(_logger); _dispatcher.Receive(); break; case ConfigurationCommandType.CM_STOPCHANNEL: - Log.LogSeparator(s_logger); - Log.StoppingChannel(s_logger, configurationCommand.SubscriptionName.Value); - Log.LogSeparator(s_logger); + Log.LogSeparator(_logger); + Log.StoppingChannel(_logger, configurationCommand.SubscriptionName.Value); + Log.LogSeparator(_logger); _dispatcher.Shut(new SubscriptionName(configurationCommand.SubscriptionName.Value)); break; case ConfigurationCommandType.CM_STARTCHANNEL: - Log.LogSeparator(s_logger); - Log.StartingChannel(s_logger, configurationCommand.SubscriptionName.Value); - Log.LogSeparator(s_logger); + Log.LogSeparator(_logger); + Log.StartingChannel(_logger, configurationCommand.SubscriptionName.Value); + Log.LogSeparator(_logger); _dispatcher.Open(new SubscriptionName(configurationCommand.SubscriptionName.Value)); break; default: @@ -110,10 +111,10 @@ private static partial class Log [LoggerMessage(LogLevel.Debug, "Configuration Command received and now starting channel {ChannelName}")] public static partial void StartingChannel(ILogger logger, string channelName); - + [LoggerMessage(LogLevel.Debug, "--------------------------------------------------------------------------")] public static partial void LogSeparator(ILogger logger); - + [LoggerMessage(LogLevel.Debug, "...")] public static partial void LogEllipsis(ILogger logger); } diff --git a/src/Paramore.Brighter.ServiceActivator/Proactor.cs b/src/Paramore.Brighter.ServiceActivator/Proactor.cs index 109c4223cf..df3ec4c502 100644 --- a/src/Paramore.Brighter.ServiceActivator/Proactor.cs +++ b/src/Paramore.Brighter.ServiceActivator/Proactor.cs @@ -60,17 +60,19 @@ public partial class Proactor : MessagePump, IAmAMessagePump public Proactor( IAmACommandProcessor commandProcessor, Func mapRequestType, - IAmAMessageMapperRegistryAsync messageMapperRegistry, + IAmAMessageMapperRegistryAsync messageMapperRegistry, IAmAMessageTransformerFactoryAsync messageTransformerFactory, IAmARequestContextFactory requestContextFactory, IAmAChannelAsync channel, + ILoggerFactory loggerFactory, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All, - TimeProvider? timeProvider = null) - : base(commandProcessor, requestContextFactory, tracer, instrumentationOptions, timeProvider) + TimeProvider? timeProvider = null) + : base(commandProcessor, requestContextFactory, + new MessagePumpConfiguration(loggerFactory, tracer, instrumentationOptions, timeProvider)) { _mapRequestType = mapRequestType; - _transformPipelineBuilder = new TransformPipelineBuilderAsync(messageMapperRegistry, messageTransformerFactory, instrumentationOptions); + _transformPipelineBuilder = new TransformPipelineBuilderAsync(messageMapperRegistry, messageTransformerFactory, loggerFactory, instrumentationOptions); Channel = channel; } @@ -78,12 +80,12 @@ public Proactor( /// The channel to receive messages from /// public IAmAChannelAsync Channel { get; set; } - + /// /// The of this message pump; indicates Reactor or Proactor /// public override MessagePumpType MessagePumpType => MessagePumpType.Proactor; - + /// /// Runs the message pump, performing the following: /// - Gets a message from a queue/stream @@ -101,35 +103,35 @@ public void Run() private async Task Acknowledge(Message message) { - Log.AcknowledgeMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.AcknowledgeMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); await Channel.AcknowledgeAsync(message); } - + private async Task DispatchRequest(MessageHeader messageHeader, TRequest request, RequestContext requestContext) where TRequest : class, IRequest { - Log.DispatchingMessage(s_logger, request.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name); + Log.DispatchingMessage(_logger, request.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name); requestContext.Span?.AddEvent(new ActivityEvent("Dispatch Message")); var messageType = messageHeader.MessageType; - + ValidateMessageType(messageType, request); switch (messageType) { case MessageType.MT_COMMAND: - { - await CommandProcessor - .SendAsync(request,requestContext, continueOnCapturedContext: true, default); - break; - } + { + await CommandProcessor + .SendAsync(request, requestContext, continueOnCapturedContext: true, default); + break; + } case MessageType.MT_DOCUMENT: case MessageType.MT_EVENT: - { - await CommandProcessor - .PublishAsync(request, requestContext, continueOnCapturedContext: true, default); - break; - } + { + await CommandProcessor + .PublishAsync(request, requestContext, continueOnCapturedContext: true, default); + break; + } } } @@ -148,7 +150,7 @@ private async Task EventLoop() break; } - Log.ReceivingMessagesFromChannel(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ReceivingMessagesFromChannel(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); // receive span covers only the broker call so its Duration reflects broker latency, not dispatch Activity? receiveSpan = null; @@ -169,7 +171,7 @@ private async Task EventLoop() } catch (ChannelFailureException ex) when (ex.InnerException is BrokenCircuitException) { - Log.BrokenCircuitExceptionMessages(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.BrokenCircuitExceptionMessages(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); await Task.Delay(ChannelFailureDelay); @@ -177,7 +179,7 @@ private async Task EventLoop() } catch (ChannelFailureException ex) { - Log.ChannelFailureExceptionMessages(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ChannelFailureExceptionMessages(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); await Task.Delay(ChannelFailureDelay); @@ -185,7 +187,7 @@ private async Task EventLoop() } catch (Exception ex) { - Log.ExceptionReceivingMessages(s_logger, ex, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ExceptionReceivingMessages(_logger, ex, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); } @@ -208,7 +210,7 @@ private async Task EventLoop() // failed to parse a message from the incoming data if (message.Header.MessageType == MessageType.MT_UNACCEPTABLE) { - Log.FailedToParseMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToParseMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); var description = $"MessagePump: Failed to parse a message from the incoming message with id {message.Id} from {Channel.Name} on thread # {Environment.CurrentManagedThreadId}"; receiveSpan?.SetStatus(ActivityStatusCode.Error, description); IncrementUnacceptableMessageCount(); @@ -220,7 +222,7 @@ private async Task EventLoop() // QUIT command if (message.Header.MessageType == MessageType.MT_QUIT) { - Log.QuitReceivingMessages(s_logger, Channel.Name, Environment.CurrentManagedThreadId); + Log.QuitReceivingMessages(_logger, Channel.Name, Environment.CurrentManagedThreadId); await Channel.DisposeAsync(); Status = MessagePumpStatus.MP_STOPPED; break; @@ -255,7 +257,7 @@ private async Task EventLoop() { if (exception is ConfigurationException configurationException) { - Log.StoppingReceivingMessages(s_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.StoppingReceivingMessages(_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); stop = true; Status = MessagePumpStatus.MP_ERROR; break; @@ -287,12 +289,12 @@ private async Task EventLoop() continue; } - Log.FailedToDispatchMessage(s_logger, exception, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToDispatchMessage(_logger, exception, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); } if (deferAction != null) { - Log.DeferringMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DeferringMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Deferring message {message.Id} for later action"); if (await RequeueMessage(message, deferAction.Delay)) continue; @@ -300,9 +302,9 @@ private async Task EventLoop() if (dontAck != null) { - Log.NotAcknowledgingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.NotAcknowledgingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); if (dontAck.InnerException != null) - Log.DontAckActionInnerException(s_logger, dontAck.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DontAckActionInnerException(_logger, dontAck.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Don't Ack Thrown. Not acknowledging message {message.Id}"); await Channel.NackAsync(message); IncrementUnacceptableMessageCount(); @@ -338,8 +340,8 @@ private async Task EventLoop() } catch (ConfigurationException configurationException) { - Log.StoppingReceivingMessages2(s_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); - await RejectMessage(message, new MessageRejectionReason(RejectionReason.DeliveryError,$"Not processed due to configuration exception: {configurationException.Message}")); + Log.StoppingReceivingMessages2(_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + await RejectMessage(message, new MessageRejectionReason(RejectionReason.DeliveryError, $"Not processed due to configuration exception: {configurationException.Message}")); processSpan?.SetStatus(ActivityStatusCode.Error, $"MessagePump: Stopping receiving of messages from {Channel.Name} on thread # {Environment.CurrentManagedThreadId}"); await Channel.DisposeAsync(); Status = MessagePumpStatus.MP_ERROR; @@ -347,17 +349,18 @@ private async Task EventLoop() } catch (DeferMessageAction deferAction) { - Log.DeferringMessage2(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DeferringMessage2(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Deferring message {message.Id} for later action"); - if (await RequeueMessage(message, deferAction.Delay)) continue; + if (await RequeueMessage(message, deferAction.Delay)) + continue; } catch (DontAckAction dontAckAction) { - Log.NotAcknowledgingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.NotAcknowledgingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); if (dontAckAction.InnerException != null) - Log.DontAckActionInnerException(s_logger, dontAckAction.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DontAckActionInnerException(_logger, dontAckAction.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Don't Ack Thrown. Not acknowledging message {message.Id}"); await Channel.NackAsync(message); IncrementUnacceptableMessageCount(); @@ -382,7 +385,7 @@ private async Task EventLoop() catch (MessageMappingException messageMappingException) { var description = $"MessagePump: Failed to map message {message.Id} from {Channel.Name} with {Channel.RoutingKey} on thread # {Thread.CurrentThread.ManagedThreadId}"; - Log.FailedToMapMessage(s_logger, messageMappingException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToMapMessage(_logger, messageMappingException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); IncrementUnacceptableMessageCount(); processSpan?.SetStatus(ActivityStatusCode.Error, description); await RejectMessage(message, new MessageRejectionReason(RejectionReason.Unacceptable, description)); @@ -390,9 +393,9 @@ private async Task EventLoop() } catch (Exception e) { - Log.FailedToDispatchMessage2(s_logger, e, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToDispatchMessage2(_logger, e, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); IncrementUnacceptableMessageCount(); - processSpan?.SetStatus(ActivityStatusCode.Error,$"MessagePump: Failed to dispatch message '{message.Id}' from {Channel.Name} with {Channel.RoutingKey} on thread # {Environment.CurrentManagedThreadId}"); + processSpan?.SetStatus(ActivityStatusCode.Error, $"MessagePump: Failed to dispatch message '{message.Id}' from {Channel.Name} with {Channel.RoutingKey} on thread # {Environment.CurrentManagedThreadId}"); } finally { @@ -403,7 +406,7 @@ private async Task EventLoop() } while (true); - Log.FinishedRunningMessageLoop(s_logger, Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); + Log.FinishedRunningMessageLoop(_logger, Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); } finally { @@ -486,12 +489,12 @@ private RequestContext InitRequestContext(Activity? span, Message message) return context; } - private Task RejectMessage(Message message, MessageRejectionReason reason ) + private Task RejectMessage(Message message, MessageRejectionReason reason) { - Log.RejectingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); - + Log.RejectingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + message.Header.Bag[Message.RejectionReasonHeaderName] = $"Message rejected reason: {reason.RejectionReason} Description: {reason.Description}"; - + return Channel.RejectAsync(message, reason); } @@ -505,7 +508,7 @@ private Task RequeueMessage(Message message, TimeSpan? delay = null) { var originalMessageId = message.Header.Bag.TryGetValue(Message.OriginalMessageIdHeaderName, out object? value) ? value.ToString() : null; - Log.DroppingMessage(s_logger, RequeueCount, message.Id.Value, string.IsNullOrEmpty(originalMessageId) + Log.DroppingMessage(_logger, RequeueCount, message.Id.Value, string.IsNullOrEmpty(originalMessageId) ? string.Empty : $" (original message id {originalMessageId})", Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); @@ -517,19 +520,19 @@ private Task RequeueMessage(Message message, TimeSpan? delay = null) } } - Log.ReQueueingMessage(s_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name, Channel.RoutingKey.Value); + Log.ReQueueingMessage(_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name, Channel.RoutingKey.Value); return Channel.RequeueAsync(message, delay ?? RequeueDelay); } - + private async Task TranslateMessage(Message message, RequestContext requestContext, CancellationToken cancellationToken = default) { - Log.TranslateMessage(s_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId); + Log.TranslateMessage(_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId); requestContext.Span?.AddEvent(new ActivityEvent("Translate Message")); var requestType = _mapRequestType(message); if (requestType == null) - throw new MessageMappingException($"Failed to find request type for message {message.Id} ", + throw new MessageMappingException($"Failed to find request type for message {message.Id} ", new ArgumentNullException(nameof(requestType), "The request type cannot be null.")); object? pipeline = null; @@ -588,7 +591,7 @@ private async Task TranslateMessage(Message message, RequestContext re } catch (Exception releaseException) { - Log.FailedToReleasePipeline(s_logger, releaseException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToReleasePipeline(_logger, releaseException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); } } } @@ -596,11 +599,13 @@ private async Task TranslateMessage(Message message, RequestContext re private bool UnacceptableMessageLimitReached() { - if (UnacceptableMessageLimit <= 0) return false; - if (UnacceptableMessageCount < UnacceptableMessageLimit) return false; - - Log.UnacceptableMessageLimitReached(s_logger, UnacceptableMessageLimit, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); - + if (UnacceptableMessageLimit <= 0) + return false; + if (UnacceptableMessageCount < UnacceptableMessageLimit) + return false; + + Log.UnacceptableMessageLimitReached(_logger, UnacceptableMessageLimit, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + return true; } @@ -608,67 +613,67 @@ private static partial class Log { [LoggerMessage(LogLevel.Debug, "MessagePump: Acknowledge message {Id} read from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void AcknowledgeMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Dispatching message {Id} from {ChannelName} on thread # {ManagementThreadId}")] public static partial void DispatchingMessage(ILogger logger, string id, int managementThreadId, string? channelName); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Receiving messages from channel {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void ReceivingMessagesFromChannel(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: BrokenCircuitException messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void BrokenCircuitExceptionMessages(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: ChannelFailureException messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void ChannelFailureExceptionMessages(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Exception receiving messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void ExceptionReceivingMessages(ILogger logger, Exception ex, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to parse a message from the incoming message with id {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void FailedToParseMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Information, "MessagePump: Quit receiving messages from {ChannelName} on thread #{ManagementThreadId}")] public static partial void QuitReceivingMessages(ILogger logger, string? channelName, int managementThreadId); - + [LoggerMessage(LogLevel.Critical, "MessagePump: Stopping receiving of messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void StoppingReceivingMessages(ILogger logger, Exception ex, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Failed to dispatch message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void FailedToDispatchMessage(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Deferring message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void DeferringMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Critical, "MessagePump: Stopping receiving of messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void StoppingReceivingMessages2(ILogger logger, ConfigurationException ex, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Deferring message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void DeferringMessage2(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to map message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void FailedToMapMessage(ILogger logger, MessageMappingException ex, string id, string? channelName, string routingKey, int managementThreadId); [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to release the transform pipeline for message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}; the message was mapped successfully and is unaffected")] public static partial void FailedToReleasePipeline(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Failed to dispatch message '{Id}' from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void FailedToDispatchMessage2(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Information, "MessagePump0: Finished running message loop, no longer receiving messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void FinishedRunningMessageLoop(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Translate message {Id} on thread # {ManagementThreadId}")] public static partial void TranslateMessage(ILogger logger, string id, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Rejecting message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] public static partial void RejectingMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); [LoggerMessage(LogLevel.Error, "MessagePump: Have tried {RequeueCount} times to handle this message {Id}{OriginalMessageId} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}, dropping message.")] public static partial void DroppingMessage(ILogger logger, int requeueCount, string id, string originalMessageId, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Re-queueing message {Id} from {ManagementThreadId} on thread # {ChannelName} with {RoutingKey}")] public static partial void ReQueueingMessage(ILogger logger, string id, int managementThreadId, ChannelName channelName, string routingKey); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Not acknowledging message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void NotAcknowledgingMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); @@ -680,4 +685,3 @@ private static partial class Log } } } - diff --git a/src/Paramore.Brighter.ServiceActivator/Reactor.cs b/src/Paramore.Brighter.ServiceActivator/Reactor.cs index 7d2e75f8b0..d3d71cd95e 100644 --- a/src/Paramore.Brighter.ServiceActivator/Reactor.cs +++ b/src/Paramore.Brighter.ServiceActivator/Reactor.cs @@ -60,17 +60,19 @@ public partial class Reactor : MessagePump, IAmAMessagePump public Reactor( IAmACommandProcessor commandProcessor, Func mapRequestType, - IAmAMessageMapperRegistry messageMapperRegistry, + IAmAMessageMapperRegistry messageMapperRegistry, IAmAMessageTransformerFactory messageTransformerFactory, IAmARequestContextFactory requestContextFactory, IAmAChannelSync channel, + ILoggerFactory loggerFactory, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All, - TimeProvider? timeProvider = null) - : base(commandProcessor, requestContextFactory, tracer, instrumentationOptions, timeProvider) + TimeProvider? timeProvider = null) + : base(commandProcessor, requestContextFactory, + new MessagePumpConfiguration(loggerFactory, tracer, instrumentationOptions, timeProvider)) { _mapRequestType = mapRequestType; - _transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, messageTransformerFactory, instrumentationOptions); + _transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, messageTransformerFactory, loggerFactory, instrumentationOptions); Channel = channel; } @@ -78,7 +80,7 @@ public Reactor( /// The channel to receive messages from /// public IAmAChannelSync Channel { get; set; } - + /// /// The of this message pump; indicates Reactor or Proactor /// @@ -107,7 +109,7 @@ public void Run() break; } - Log.ReceivingMessages(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ReceivingMessages(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); // receive span covers only the broker call so its Duration reflects broker latency, not dispatch Activity? receiveSpan = null; @@ -128,7 +130,7 @@ public void Run() } catch (ChannelFailureException ex) when (ex.InnerException is BrokenCircuitException) { - Log.BrokenCircuitException(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.BrokenCircuitException(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); Thread.Sleep(ChannelFailureDelay); //-- pause pump; blocks consuming thread on empty queue; @@ -136,7 +138,7 @@ public void Run() } catch (ChannelFailureException ex) { - Log.ChannelFailureException(s_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ChannelFailureException(_logger, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); Thread.Sleep(ChannelFailureDelay); //-- pause pump; blocks consuming thread on empty queue; @@ -144,7 +146,7 @@ public void Run() } catch (Exception ex) { - Log.ExceptionReceivingMessages(s_logger, ex, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.ExceptionReceivingMessages(_logger, ex, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); receiveSpan?.AddException(ex); receiveSpan?.SetStatus(ActivityStatusCode.Error, ex.Message); } @@ -167,7 +169,7 @@ public void Run() // failed to parse a message from the incoming data if (message.Header.MessageType == MessageType.MT_UNACCEPTABLE) { - Log.FailedToParseMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToParseMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); var description = $"MessagePump: Failed to parse a message from the incoming message with id {message.Id} from {Channel.Name} on thread # {Environment.CurrentManagedThreadId}"; receiveSpan?.SetStatus(ActivityStatusCode.Error, description); IncrementUnacceptableMessageCount(); @@ -179,7 +181,7 @@ public void Run() // QUIT command if (message.Header.MessageType == MessageType.MT_QUIT) { - Log.QuitReceivingMessages(s_logger, Channel.Name, Environment.CurrentManagedThreadId); + Log.QuitReceivingMessages(_logger, Channel.Name, Environment.CurrentManagedThreadId); Channel.Dispose(); Status = MessagePumpStatus.MP_STOPPED; break; @@ -214,7 +216,7 @@ public void Run() { if (exception is ConfigurationException configurationException) { - Log.StoppingReceivingMessages(s_logger, configurationException, Channel.Name, + Log.StoppingReceivingMessages(_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); stop = true; rejectReason = configurationException.Message; @@ -248,13 +250,13 @@ public void Run() continue; } - Log.FailedToDispatchMessage(s_logger, exception, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, + Log.FailedToDispatchMessage(_logger, exception, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); } if (deferAction != null) { - Log.DeferringMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value,Environment.CurrentManagedThreadId); + Log.DeferringMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Deferring message {message.Id} for later action"); if (RequeueMessage(message, deferAction.Delay)) continue; @@ -262,9 +264,9 @@ public void Run() if (dontAck != null) { - Log.NotAcknowledgingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.NotAcknowledgingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); if (dontAck.InnerException != null) - Log.DontAckActionInnerException(s_logger, dontAck.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DontAckActionInnerException(_logger, dontAck.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Don't Ack Thrown. Not acknowledging message {message.Id}"); Channel.Nack(message); IncrementUnacceptableMessageCount(); @@ -303,7 +305,7 @@ public void Run() } catch (ConfigurationException configurationException) { - Log.StoppingReceivingMessages2(s_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, + Log.StoppingReceivingMessages2(_logger, configurationException, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); IncrementUnacceptableMessageCount(); RejectMessage(message, new MessageRejectionReason(RejectionReason.DeliveryError, $"Not processed due to configuration exception: {configurationException.Message}")); @@ -315,15 +317,16 @@ public void Run() } catch (DeferMessageAction deferAction) { - Log.DeferringMessage2(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DeferringMessage2(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Deferring message {message.Id} for later action"); - if (RequeueMessage(message, deferAction.Delay)) continue; + if (RequeueMessage(message, deferAction.Delay)) + continue; } catch (DontAckAction dontAckAction) { - Log.NotAcknowledgingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.NotAcknowledgingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); if (dontAckAction.InnerException != null) - Log.DontAckActionInnerException(s_logger, dontAckAction.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.DontAckActionInnerException(_logger, dontAckAction.InnerException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); processSpan?.SetStatus(ActivityStatusCode.Error, $"Don't Ack Thrown. Not acknowledging message {message.Id}"); Channel.Nack(message); IncrementUnacceptableMessageCount(); @@ -347,7 +350,7 @@ public void Run() catch (MessageMappingException messageMappingException) { var description = $"MessagePump: Failed to map message {message.Id} from {Channel.Name} with {Channel.RoutingKey} on thread # {Thread.CurrentThread.ManagedThreadId}"; - Log.FailedToMapMessage(s_logger, messageMappingException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToMapMessage(_logger, messageMappingException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); IncrementUnacceptableMessageCount(); processSpan?.SetStatus(ActivityStatusCode.Error, description); RejectMessage(message, new MessageRejectionReason(RejectionReason.Unacceptable, description)); @@ -355,9 +358,9 @@ public void Run() } catch (Exception e) { - Log.FailedToDispatchMessage2(s_logger, e, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToDispatchMessage2(_logger, e, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); IncrementUnacceptableMessageCount(); - processSpan?.SetStatus(ActivityStatusCode.Error,$"MessagePump: Failed to dispatch message '{message.Id}' from {Channel.Name} with {Channel.RoutingKey} on thread # {Environment.CurrentManagedThreadId}"); + processSpan?.SetStatus(ActivityStatusCode.Error, $"MessagePump: Failed to dispatch message '{message.Id}' from {Channel.Name} with {Channel.RoutingKey} on thread # {Environment.CurrentManagedThreadId}"); } finally { @@ -368,7 +371,7 @@ public void Run() } while (true); - Log.FinishedRunningMessageLoop(s_logger, Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); + Log.FinishedRunningMessageLoop(_logger, Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); } finally { @@ -379,14 +382,14 @@ public void Run() private void AcknowledgeMessage(Message message) { - Log.AcknowledgeMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.AcknowledgeMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); Channel.Acknowledge(message); } - + private void DispatchRequest(MessageHeader messageHeader, TRequest request, RequestContext requestContext) where TRequest : class, IRequest { - Log.DispatchingMessage(s_logger, request.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name); + Log.DispatchingMessage(_logger, request.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name); requestContext.Span?.AddEvent(new ActivityEvent("Dispatch Message")); var messageType = messageHeader.MessageType; @@ -396,16 +399,16 @@ private void DispatchRequest(MessageHeader messageHeader, TRequest req switch (messageType) { case MessageType.MT_COMMAND: - { - CommandProcessor.Send(request, requestContext); - break; - } + { + CommandProcessor.Send(request, requestContext); + break; + } case MessageType.MT_DOCUMENT: case MessageType.MT_EVENT: - { - CommandProcessor.Publish(request, requestContext); - break; - } + { + CommandProcessor.Publish(request, requestContext); + break; + } } } @@ -421,13 +424,13 @@ private RequestContext InitRequestContext(Activity? span, Message message) private bool RejectMessage(Message message, MessageRejectionReason reason) { - Log.RejectingMessage(s_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.RejectingMessage(_logger, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); message.Header.Bag[Message.RejectionReasonHeaderName] = $"Message rejected reason: {reason.RejectionReason} Description: {reason.Description}"; return Channel.Reject(message, reason); } - + private void InvokeDispatchRequest(IRequest request, Message message, RequestContext context) { // NOTE: DispatchRequest is a generic method constrained to TRequest : class, IRequest, but at runtime @@ -499,7 +502,7 @@ private bool RequeueMessage(Message message, TimeSpan? delay = null) { var originalMessageId = message.Header.Bag.TryGetValue(Message.OriginalMessageIdHeaderName, out object? value) ? value.ToString() : null; - Log.DroppingMessage(s_logger, RequeueCount, message.Id.Value, string.IsNullOrEmpty(originalMessageId) + Log.DroppingMessage(_logger, RequeueCount, message.Id.Value, string.IsNullOrEmpty(originalMessageId) ? string.Empty : $" (original message id {originalMessageId})", Channel.Name, Channel.RoutingKey.Value, Thread.CurrentThread.ManagedThreadId); @@ -508,23 +511,23 @@ private bool RequeueMessage(Message message, TimeSpan? delay = null) } } - Log.RequeueingMessage(s_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name, Channel.RoutingKey.Value); + Log.RequeueingMessage(_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId, Channel.Name, Channel.RoutingKey.Value); return Channel.Requeue(message, delay ?? RequeueDelay); } - + private IRequest TranslateMessage(Message message, RequestContext requestContext) { - Log.TranslateMessage(s_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId); + Log.TranslateMessage(_logger, message.Id.Value, Thread.CurrentThread.ManagedThreadId); requestContext.Span?.AddEvent(new ActivityEvent("Translate Message")); IRequest request; var requestType = _mapRequestType(message); if (requestType == null) - throw new MessageMappingException($"Failed to find request type for message {message.Id} ", + throw new MessageMappingException($"Failed to find request type for message {message.Id} ", new ArgumentNullException(nameof(requestType), "The request type cannot be null.")); - + object? pipeline = null; try { @@ -575,7 +578,7 @@ private IRequest TranslateMessage(Message message, RequestContext requestContext } catch (Exception releaseException) { - Log.FailedToReleasePipeline(s_logger, releaseException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + Log.FailedToReleasePipeline(_logger, releaseException, message.Id.Value, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); } } } @@ -585,79 +588,80 @@ private IRequest TranslateMessage(Message message, RequestContext requestContext private bool UnacceptableMessageLimitReached() { - if (UnacceptableMessageLimit <= 0) return false; + if (UnacceptableMessageLimit <= 0) + return false; if (UnacceptableMessageCount >= UnacceptableMessageLimit) { - Log.UnacceptableMessageLimitReached(s_logger, UnacceptableMessageLimit, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); - + Log.UnacceptableMessageLimitReached(_logger, UnacceptableMessageLimit, Channel.Name, Channel.RoutingKey.Value, Environment.CurrentManagedThreadId); + return true; } return false; } - + private static partial class Log { [LoggerMessage(LogLevel.Debug, "MessagePump: Receiving messages from channel {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void ReceivingMessages(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: BrokenCircuitException messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void BrokenCircuitException(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: ChannelFailureException messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void ChannelFailureException(ILogger logger, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Exception receiving messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void ExceptionReceivingMessages(ILogger logger, Exception ex, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to parse a message from the incoming message with id {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void FailedToParseMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Information, "MessagePump: Quit receiving messages from {ChannelName} on thread #{ManagementThreadId}")] internal static partial void QuitReceivingMessages(ILogger logger, string? channelName, int managementThreadId); - + [LoggerMessage(LogLevel.Critical, "MessagePump: Stopping receiving of messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void StoppingReceivingMessages(ILogger logger, Exception ex, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Failed to dispatch message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void FailedToDispatchMessage(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); [LoggerMessage(LogLevel.Debug, "MessagePump: Deferring message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void DeferringMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Critical, "MessagePump: Stopping receiving of messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void StoppingReceivingMessages2(ILogger logger, ConfigurationException configurationException, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Deferring message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void DeferringMessage2(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to map message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void FailedToMapMessage(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); [LoggerMessage(LogLevel.Warning, "MessagePump: Failed to release the transform pipeline for message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}; the message was mapped successfully and is unaffected")] internal static partial void FailedToReleasePipeline(ILogger logger, Exception ex, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Failed to dispatch message '{Id}' from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void FailedToDispatchMessage2(ILogger logger, Exception e, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Acknowledge message {Id} read from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void AcknowledgeMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Dispatching message {Id} from {ChannelName} on thread # {ManagementThreadId}")] internal static partial void DispatchingMessage(ILogger logger, string id, int managementThreadId, string? channelName); - + [LoggerMessage(LogLevel.Warning, "MessagePump: Rejecting message {Id} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void RejectingMessage(ILogger logger, string id, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Error, "MessagePump: Have tried {RequeueCount} times to handle this message {Id}{OriginalMessageId} from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}, dropping message.")] internal static partial void DroppingMessage(ILogger logger, int requeueCount, string id, string originalMessageId, string? channelName, string routingKey, int managementThreadId); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Re-queueing message {Id} from {ManagementThreadId} on thread # {ChannelName} with {RoutingKey}")] internal static partial void RequeueingMessage(ILogger logger, string id, int managementThreadId, string? channelName, string routingKey); - + [LoggerMessage(LogLevel.Debug, "MessagePump: Translate message {Id} on thread # {ManagementThreadId}")] internal static partial void TranslateMessage(ILogger logger, string id, int managementThreadId); - + [LoggerMessage(LogLevel.Critical, "MessagePump: Unacceptable message limit of {UnacceptableMessageLimit} reached, stopping reading messages from {ChannelName} with {RoutingKey} on thread # {ManagementThreadId}")] internal static partial void UnacceptableMessageLimitReached(ILogger logger, int unacceptableMessageLimit, string? channelName, string routingKey, int managementThreadId); @@ -672,4 +676,3 @@ private static partial class Log } } } - diff --git a/src/Paramore.Brighter.Sqlite/SqliteConnectionProvider.cs b/src/Paramore.Brighter.Sqlite/SqliteConnectionProvider.cs index 21b9e28d1e..667ecb10ca 100644 --- a/src/Paramore.Brighter.Sqlite/SqliteConnectionProvider.cs +++ b/src/Paramore.Brighter.Sqlite/SqliteConnectionProvider.cs @@ -42,7 +42,7 @@ public class SqliteConnectionProvider : RelationalDbConnectionProvider /// Create a connection provider for Sqlite using a connection string for Db access /// /// The configuration of the Sqlite database - public SqliteConnectionProvider(IAmARelationalDatabaseConfiguration configuration) + public SqliteConnectionProvider(IAmARelationalDatabaseConfiguration? configuration) { if (string.IsNullOrWhiteSpace(configuration?.ConnectionString)) throw new ArgumentNullException(nameof(configuration.ConnectionString)); diff --git a/src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs b/src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs index ef16a47e80..27caeef351 100644 --- a/src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs +++ b/src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs @@ -19,7 +19,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - + #endregion using System; @@ -35,7 +35,6 @@ THE SOFTWARE. */ using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; using Paramore.Brighter.Transforms.Storage; @@ -70,7 +69,7 @@ namespace Paramore.Brighter.Transformers.AWS.V4; public partial class S3LuggageStore : IAmAStorageProvider, IAmAStorageProviderAsync { private const string ClaimCheckProvider = "aws_s3"; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly S3LuggageOptions _options; private readonly Dictionary _spanAttributes = new(); private readonly string _bucketName; @@ -81,20 +80,23 @@ public partial class S3LuggageStore : IAmAStorageProvider, IAmAStorageProviderAs /// Initializes a new instance of the class with the specified S3 luggage options. /// /// The containing the S3 client, bucket details, and other configuration. - public S3LuggageStore(S3LuggageOptions options) + /// The factory used to create the logger for this store. + public S3LuggageStore(S3LuggageOptions options, ILoggerFactory loggerFactory) { _client = options.Client; _luggagePrefix = options.LuggagePrefix; _options = options; _bucketName = options.BucketName; - + _spanAttributes["claim_check.aws-s3.region"] = options.BucketRegion.Value; + + _logger = loggerFactory.CreateLogger(); } /// public IAmABrighterTracer? Tracer { get; set; } - + /// public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = default) { @@ -102,21 +104,21 @@ public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = d { return; } - - if(_options.HttpClientFactory == null) + + if (_options.HttpClientFactory == null) { throw new ConfigurationException("No HTTP Factory setup on S3Luggage Store"); } - + try { var accountId = await GetAccountIdAsync(_options.StsClient); - var bucketExists = await BucketExistsAsync(_options.HttpClientFactory, + var bucketExists = await BucketExistsAsync(_options.HttpClientFactory, accountId, _options.BucketName, - _options.BucketRegion, + _options.BucketRegion, _options.BucketAddressTemplate); - + if (bucketExists) { return; @@ -148,7 +150,7 @@ await CreateBucketAsync( } catch (Exception e) { - Log.ErrorCreatingValidatingLuggageStore(s_logger, _bucketName, _options.BucketRegion, e); + Log.ErrorCreatingValidatingLuggageStore(_logger, _bucketName, _options.BucketRegion, e); throw; } } @@ -165,7 +167,7 @@ public async Task DeleteAsync(string claimCheck, CancellationToken cancellationT if (response.HttpStatusCode != HttpStatusCode.NoContent) { - Log.CouldNotDeleteLuggage(s_logger, claimCheck, _bucketName); + Log.CouldNotDeleteLuggage(_logger, claimCheck, _bucketName); } } finally @@ -182,13 +184,13 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can { var request = new GetObjectRequest { BucketName = _bucketName, Key = claimCheck, }; - Log.Downloading(s_logger, claimCheck, _bucketName); + Log.Downloading(_logger, claimCheck, _bucketName); // Issue request and remember to dispose of the response using var response = await _client.GetObjectAsync(request, cancellationToken); if (response.HttpStatusCode != HttpStatusCode.OK) { - Log.CouldNotDownload(s_logger, claimCheck, _bucketName); + Log.CouldNotDownload(_logger, claimCheck, _bucketName); throw new InvalidOperationException($"Could not download {claimCheck} from {_bucketName}"); } @@ -197,7 +199,7 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can // Save object to local file var stream = new MemoryStream(); #if NETSTANDARD - await response.ResponseStream.CopyToAsync(stream); + await response.ResponseStream.CopyToAsync(stream); #else await response.ResponseStream.CopyToAsync(stream, cancellationToken); #endif @@ -206,12 +208,12 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can } catch (AmazonS3Exception) { - Log.UnableToRead(s_logger, claimCheck, _bucketName); + Log.UnableToRead(_logger, claimCheck, _bucketName); throw; } catch (Exception e) when (e is ObjectDisposedException || e is NotSupportedException) { - Log.UnableToRead(s_logger, claimCheck, _bucketName); + Log.UnableToRead(_logger, claimCheck, _bucketName); throw; } } @@ -254,7 +256,7 @@ public async Task StoreAsync(Stream stream, CancellationToken cancellati var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Store, ClaimCheckProvider, _bucketName, claimCheck, _spanAttributes, stream.Length)); try { - Log.Uploading(s_logger, claimCheck, _bucketName); + Log.Uploading(_logger, claimCheck, _bucketName); var transferUtility = new TransferUtility(_client); await transferUtility.UploadAsync(stream, _bucketName, claimCheck, cancellationToken); return claimCheck; @@ -280,9 +282,9 @@ public async Task StoreAsync(Stream stream, CancellationToken cancellati /// public string Store(Stream stream) => BrighterAsyncContext.Run(() => StoreAsync(stream)); - private static async Task BucketExistsAsync(IHttpClientFactory httpClientFactory, - string accountId, - string bucketName, + private static async Task BucketExistsAsync(IHttpClientFactory httpClientFactory, + string accountId, + string bucketName, S3Region bucketRegion, string bucketAddressTemplate) { @@ -291,10 +293,10 @@ private static async Task BucketExistsAsync(IHttpClientFactory httpClientF .Replace("{BucketName}", bucketName) .Replace("{BucketRegion}", bucketRegion.Value) ); - + using var headRequest = new HttpRequestMessage(HttpMethod.Head, "/"); headRequest.Headers.Add("x-amz-expected-bucket-owner", accountId); - + using var response = await httpClient.SendAsync(headRequest); //If we deny public access to the bucket, but it exists we get access denied; we get not-found if it does not exist return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Forbidden; @@ -316,9 +318,9 @@ await asyncRetryPolicy.ExecuteAsync(async () => { var bucketRequest = new PutBucketRequest { - BucketName = bucketName, + BucketName = bucketName, BucketRegionName = region.Value, - CannedACL = cannedAcl, + CannedACL = cannedAcl, UseClientRegion = false }; @@ -334,7 +336,7 @@ await asyncRetryPolicy.ExecuteAsync(async () => { // Ignoring this exception since it was created by another requests } - + }); await asyncRetryPolicy.ExecuteAsync(async () => @@ -363,7 +365,9 @@ await asyncRetryPolicy.ExecuteAsync(async () => var lifeCycleRequest = new PutLifecycleConfigurationRequest { - BucketName = bucketName, ExpectedBucketOwner = accountId, Configuration = new LifecycleConfiguration { Rules = rules } + BucketName = bucketName, + ExpectedBucketOwner = accountId, + Configuration = new LifecycleConfiguration { Rules = rules } }; var lifeCycleResponse = await client.PutLifecycleConfigurationAsync(lifeCycleRequest); if (lifeCycleResponse.HttpStatusCode != HttpStatusCode.OK) @@ -415,7 +419,8 @@ private static async Task GetAccountIdAsync(IAmazonSecurityTokenService { var callerIdentityResponse = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); - if (callerIdentityResponse.HttpStatusCode != HttpStatusCode.OK) throw new InvalidOperationException("Could not find identity of AWS account"); + if (callerIdentityResponse.HttpStatusCode != HttpStatusCode.OK) + throw new InvalidOperationException("Could not find identity of AWS account"); return callerIdentityResponse.Account; } @@ -457,7 +462,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Unable to read {ClaimCheck} from {Bucket}")] public static partial void UnableToRead(ILogger logger, string claimCheck, string bucket); - + [LoggerMessage(LogLevel.Information, "Uploading {ClaimCheck} to {Bucket}")] public static partial void Uploading(ILogger logger, string claimCheck, string bucket); } diff --git a/src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs b/src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs index dd5c259ecc..14bcd08fdf 100644 --- a/src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs +++ b/src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs @@ -19,7 +19,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - + #endregion using System; @@ -35,7 +35,6 @@ THE SOFTWARE. */ using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; using Paramore.Brighter.Transforms.Storage; @@ -70,7 +69,7 @@ namespace Paramore.Brighter.Transformers.AWS; public partial class S3LuggageStore : IAmAStorageProvider, IAmAStorageProviderAsync { private const string ClaimCheckProvider = "aws_s3"; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly S3LuggageOptions _options; private readonly Dictionary _spanAttributes = new(); private readonly string _bucketName; @@ -81,20 +80,23 @@ public partial class S3LuggageStore : IAmAStorageProvider, IAmAStorageProviderAs /// Initializes a new instance of the class with the specified S3 luggage options. /// /// The containing the S3 client, bucket details, and other configuration. - public S3LuggageStore(S3LuggageOptions options) + /// The factory used to create the logger for this store. + public S3LuggageStore(S3LuggageOptions options, ILoggerFactory loggerFactory) { _client = options.Client; _luggagePrefix = options.LuggagePrefix; _options = options; _bucketName = options.BucketName; - + _spanAttributes["claim_check.aws-s3.region"] = options.BucketRegion.Value; + + _logger = loggerFactory.CreateLogger(); } /// public IAmABrighterTracer? Tracer { get; set; } - + /// public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = default) { @@ -102,21 +104,21 @@ public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = d { return; } - - if(_options.HttpClientFactory == null) + + if (_options.HttpClientFactory == null) { throw new ConfigurationException("No HTTP Factory setup on S3Luggage Store"); } - + try { var accountId = await GetAccountIdAsync(_options.StsClient); - var bucketExists = await BucketExistsAsync(_options.HttpClientFactory, + var bucketExists = await BucketExistsAsync(_options.HttpClientFactory, accountId, _options.BucketName, - _options.BucketRegion, + _options.BucketRegion, _options.BucketAddressTemplate); - + if (bucketExists) { return; @@ -148,7 +150,7 @@ await CreateBucketAsync( } catch (Exception e) { - Log.ErrorCreatingValidatingLuggageStore(s_logger, _bucketName, _options.BucketRegion, e); + Log.ErrorCreatingValidatingLuggageStore(_logger, _bucketName, _options.BucketRegion, e); throw; } } @@ -165,7 +167,7 @@ public async Task DeleteAsync(string claimCheck, CancellationToken cancellationT if (response.HttpStatusCode != HttpStatusCode.NoContent) { - Log.CouldNotDeleteLuggage(s_logger, claimCheck, _bucketName); + Log.CouldNotDeleteLuggage(_logger, claimCheck, _bucketName); } } finally @@ -182,13 +184,13 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can { var request = new GetObjectRequest { BucketName = _bucketName, Key = claimCheck, }; - Log.Downloading(s_logger, claimCheck, _bucketName); + Log.Downloading(_logger, claimCheck, _bucketName); // Issue request and remember to dispose of the response using var response = await _client.GetObjectAsync(request, cancellationToken); if (response.HttpStatusCode != HttpStatusCode.OK) { - Log.CouldNotDownload(s_logger, claimCheck, _bucketName); + Log.CouldNotDownload(_logger, claimCheck, _bucketName); throw new InvalidOperationException($"Could not download {claimCheck} from {_bucketName}"); } @@ -197,7 +199,7 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can // Save object to local file var stream = new MemoryStream(); #if NETSTANDARD - await response.ResponseStream.CopyToAsync(stream); + await response.ResponseStream.CopyToAsync(stream); #else await response.ResponseStream.CopyToAsync(stream, cancellationToken); #endif @@ -206,12 +208,12 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can } catch (AmazonS3Exception) { - Log.UnableToRead(s_logger, claimCheck, _bucketName); + Log.UnableToRead(_logger, claimCheck, _bucketName); throw; } catch (Exception e) when (e is ObjectDisposedException || e is NotSupportedException) { - Log.UnableToRead(s_logger, claimCheck, _bucketName); + Log.UnableToRead(_logger, claimCheck, _bucketName); throw; } } @@ -255,7 +257,7 @@ public async Task StoreAsync(Stream stream, CancellationToken cancellati var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Store, ClaimCheckProvider, _bucketName, claimCheck, _spanAttributes, stream.Length)); try { - Log.Uploading(s_logger, claimCheck, _bucketName); + Log.Uploading(_logger, claimCheck, _bucketName); var transferUtility = new TransferUtility(_client); await transferUtility.UploadAsync(stream, _bucketName, claimCheck, cancellationToken); return claimCheck; @@ -281,9 +283,9 @@ public async Task StoreAsync(Stream stream, CancellationToken cancellati /// public string Store(Stream stream) => BrighterAsyncContext.Run(() => StoreAsync(stream)); - private static async Task BucketExistsAsync(IHttpClientFactory httpClientFactory, - string accountId, - string bucketName, + private static async Task BucketExistsAsync(IHttpClientFactory httpClientFactory, + string accountId, + string bucketName, S3Region bucketRegion, string bucketAddressTemplate) { @@ -292,10 +294,10 @@ private static async Task BucketExistsAsync(IHttpClientFactory httpClientF .Replace("{BucketName}", bucketName) .Replace("{BucketRegion}", bucketRegion.Value) ); - + using var headRequest = new HttpRequestMessage(HttpMethod.Head, "/"); headRequest.Headers.Add("x-amz-expected-bucket-owner", accountId); - + using var response = await httpClient.SendAsync(headRequest); //If we deny public access to the bucket, but it exists we get access denied; we get not-found if it does not exist return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Forbidden; @@ -317,9 +319,9 @@ await asyncRetryPolicy.ExecuteAsync(async () => { var bucketRequest = new PutBucketRequest { - BucketName = bucketName, + BucketName = bucketName, BucketRegionName = region.Value, - CannedACL = cannedAcl, + CannedACL = cannedAcl, UseClientRegion = false }; @@ -335,7 +337,7 @@ await asyncRetryPolicy.ExecuteAsync(async () => { // Ignoring this exception since it was created by another requests } - + }); await asyncRetryPolicy.ExecuteAsync(async () => @@ -364,7 +366,9 @@ await asyncRetryPolicy.ExecuteAsync(async () => var lifeCycleRequest = new PutLifecycleConfigurationRequest { - BucketName = bucketName, ExpectedBucketOwner = accountId, Configuration = new LifecycleConfiguration { Rules = rules } + BucketName = bucketName, + ExpectedBucketOwner = accountId, + Configuration = new LifecycleConfiguration { Rules = rules } }; var lifeCycleResponse = await client.PutLifecycleConfigurationAsync(lifeCycleRequest); if (lifeCycleResponse.HttpStatusCode != HttpStatusCode.OK) @@ -416,7 +420,8 @@ private static async Task GetAccountIdAsync(IAmazonSecurityTokenService { var callerIdentityResponse = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); - if (callerIdentityResponse.HttpStatusCode != HttpStatusCode.OK) throw new InvalidOperationException("Could not find identity of AWS account"); + if (callerIdentityResponse.HttpStatusCode != HttpStatusCode.OK) + throw new InvalidOperationException("Could not find identity of AWS account"); return callerIdentityResponse.Account; } @@ -458,7 +463,7 @@ private static partial class Log [LoggerMessage(LogLevel.Error, "Unable to read {ClaimCheck} from {Bucket}")] public static partial void UnableToRead(ILogger logger, string claimCheck, string bucket); - + [LoggerMessage(LogLevel.Information, "Uploading {ClaimCheck} to {Bucket}")] public static partial void Uploading(ILogger logger, string claimCheck, string bucket); } diff --git a/src/Paramore.Brighter.Transformers.Gcp/GcsLuggageStore.cs b/src/Paramore.Brighter.Transformers.Gcp/GcsLuggageStore.cs index 3c726bfc9a..2ad4d787d1 100644 --- a/src/Paramore.Brighter.Transformers.Gcp/GcsLuggageStore.cs +++ b/src/Paramore.Brighter.Transformers.Gcp/GcsLuggageStore.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Google; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Transforms.Storage; @@ -39,15 +38,15 @@ namespace Paramore.Brighter.Transformers.Gcp; /// Integrates with Brighter's tracing via and provides structured logging through . /// /// -public partial class GcsLuggageStore(GcsLuggageOptions options) : IAmAStorageProvider, IAmAStorageProviderAsync +public partial class GcsLuggageStore(GcsLuggageOptions options, ILoggerFactory loggerFactory) : IAmAStorageProvider, IAmAStorageProviderAsync { private const string ClaimCheckProvider = "gcp_gcs"; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); private static readonly Dictionary s_spanAttributes = new(); - + /// public IAmABrighterTracer? Tracer { get; set; } - + /// public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = default) { @@ -77,13 +76,13 @@ public async Task EnsureStoreExistsAsync(CancellationToken cancellationToken = d { throw new InvalidOperationException($"Bucket {options.BucketName} does not exist"); } - + await client.CreateBucketAsync(options.ProjectId, options.BucketName, options.CreateBucketOptions, cancellationToken); } - catch(Exception e) + catch (Exception e) { - Log.ErrorCreatingValidatingLuggageStore(s_logger, options.BucketName, e); - throw; + Log.ErrorCreatingValidatingLuggageStore(_logger, options.BucketName, e); + throw; } } @@ -98,7 +97,7 @@ public async Task DeleteAsync(string claimCheck, CancellationToken cancellationT } catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) { - Log.CouldNotDeleteLuggage(s_logger, claimCheck, options.BucketName); + Log.CouldNotDeleteLuggage(_logger, claimCheck, options.BucketName); } finally { @@ -122,7 +121,7 @@ public async Task RetrieveAsync(string claimCheck, CancellationToken can } catch (Exception e) { - Log.UnableToRead(s_logger, claimCheck, options.BucketName, e); + Log.UnableToRead(_logger, claimCheck, options.BucketName, e); throw; } finally @@ -159,14 +158,14 @@ public async Task StoreAsync(Stream stream, CancellationToken cancellati { prefix += "/"; } - + var claimCheck = $"{prefix}{Guid.NewGuid().ToString()}"; var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Store, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes, stream.Length)); try { var client = await options.CreateStorageClientAsync(); - await client.UploadObjectAsync(options.BucketName, - claimCheck, + await client.UploadObjectAsync(options.BucketName, + claimCheck, "application/vnd.brighter.claim-check", stream, options.UploadObjectOptions, @@ -208,7 +207,7 @@ public void EnsureStoreExists() { throw new InvalidOperationException($"Bucket {options.BucketName} does not exist"); } - + client.CreateBucket(options.ProjectId, options.BucketName, options.CreateBucketOptions); } } @@ -219,12 +218,12 @@ public void Delete(string claimCheck) var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Delete, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes)); try { - var client = options.CreateStorageClient(); + var client = options.CreateStorageClient(); client.DeleteObject(options.BucketName, claimCheck, options.DeleteObjectOptions); } catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) { - Log.CouldNotDeleteLuggage(s_logger, claimCheck, options.BucketName); + Log.CouldNotDeleteLuggage(_logger, claimCheck, options.BucketName); } finally { @@ -234,8 +233,8 @@ public void Delete(string claimCheck) /// public Stream Retrieve(string claimCheck) - { - var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Retrieve, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes)); + { + var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Retrieve, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes)); try { var client = options.CreateStorageClient(); @@ -248,7 +247,7 @@ public Stream Retrieve(string claimCheck) } catch (Exception e) { - Log.UnableToRead(s_logger, claimCheck, options.BucketName, e); + Log.UnableToRead(_logger, claimCheck, options.BucketName, e); throw; } finally @@ -260,7 +259,7 @@ public Stream Retrieve(string claimCheck) /// public bool HasClaim(string claimCheck) { - var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.HasClaim, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes)); + var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.HasClaim, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes)); try { var client = options.CreateStorageClient(); @@ -285,15 +284,15 @@ public string Store(Stream stream) { prefix += "/"; } - + var claimCheck = $"{prefix}{Guid.NewGuid().ToString()}"; var span = Tracer?.CreateClaimCheckSpan(new ClaimCheckSpanInfo(ClaimCheckOperation.Store, ClaimCheckProvider, options.BucketName, claimCheck, s_spanAttributes, stream.Length)); try { var client = options.CreateStorageClient(); client.UploadObject(options.BucketName, - claimCheck, - "application/vnd.brighter.claim-check", + claimCheck, + "application/vnd.brighter.claim-check", stream, options.UploadObjectOptions); return claimCheck; @@ -319,7 +318,7 @@ private static partial class Log public static partial void CouldNotDownload(ILogger logger, string claimCheck, string bucketName); [LoggerMessage(LogLevel.Error, "Unable to read {ClaimCheck} from {Bucket}")] - public static partial void UnableToRead(ILogger logger, string claimCheck, string bucket, Exception exception); + public static partial void UnableToRead(ILogger logger, string claimCheck, string bucket, Exception exception); [LoggerMessage(LogLevel.Information, "Uploading {ClaimCheck} to {Bucket}")] public static partial void Uploading(ILogger logger, string claimCheck, string bucket); diff --git a/src/Paramore.Brighter/ChannelName.cs b/src/Paramore.Brighter/ChannelName.cs index 17317b47ed..586604f756 100644 --- a/src/Paramore.Brighter/ChannelName.cs +++ b/src/Paramore.Brighter/ChannelName.cs @@ -69,7 +69,7 @@ public override string ToString() /// /// The to convert. /// The result of the conversion. - public static implicit operator string?(ChannelName rhs) + public static implicit operator string?(ChannelName? rhs) { return rhs?.ToString(); } diff --git a/src/Paramore.Brighter/CloudEventsType.cs b/src/Paramore.Brighter/CloudEventsType.cs index a8618d551f..ef01ff1372 100644 --- a/src/Paramore.Brighter/CloudEventsType.cs +++ b/src/Paramore.Brighter/CloudEventsType.cs @@ -62,7 +62,7 @@ public CloudEventsType(string value) /// /// The instance. /// The string value of the CloudEvents type. - public static implicit operator string?(CloudEventsType type) => type?.Value; + public static implicit operator string?(CloudEventsType? type) => type?.Value; /// /// Explicitly converts a to a . diff --git a/src/Paramore.Brighter/CommandProcessor.cs b/src/Paramore.Brighter/CommandProcessor.cs index 59f2744d55..7bd682929e 100644 --- a/src/Paramore.Brighter/CommandProcessor.cs +++ b/src/Paramore.Brighter/CommandProcessor.cs @@ -36,7 +36,6 @@ THE SOFTWARE. */ using Microsoft.Extensions.Logging; using Paramore.Brighter.BindingAttributes; using Paramore.Brighter.FeatureSwitch; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Polly; using Polly.Registry; @@ -51,7 +50,8 @@ namespace Paramore.Brighter /// public partial class CommandProcessor : IAmACommandProcessor { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly IAmASubscriberRegistry? _subscriberRegistry; private readonly IAmAHandlerFactorySync? _handlerFactorySync; @@ -92,7 +92,7 @@ public partial class CommandProcessor : IAmACommandProcessor /// /// public const string RequestReply = "Paramore.Brighter.CommandProcessor.RequestReply"; - + /// /// Use this as an identifier for your that determines for how long to break the circuit when communication with the Work Queue fails. /// Register that policy with your such as @@ -158,11 +158,15 @@ public CommandProcessor( IPolicyRegistry policyRegistry, ResiliencePipelineRegistry resilienceResiliencePipelineRegistry, IAmARequestSchedulerFactory requestSchedulerFactory, + ILoggerFactory loggerFactory, IAmAFeatureSwitchRegistry? featureSwitchRegistry = null, InboxConfiguration? inboxConfiguration = null, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { + _loggerFactory = loggerFactory; + _logger = _loggerFactory.CreateLogger(); + _subscriberRegistry = subscriberRegistry; if (HandlerFactoryIsNotEitherIAmAHandlerFactorySyncOrAsync(handlerFactory)) @@ -213,7 +217,8 @@ public CommandProcessor( IPolicyRegistry policyRegistry, ResiliencePipelineRegistry resilienceResiliencePipelineRegistry, IAmAnOutboxProducerMediator bus, - IAmARequestSchedulerFactory requestSchedulerFactory, + IAmARequestSchedulerFactory requestSchedulerFactory, + ILoggerFactory loggerFactory, Type? transactionType = null, IAmAFeatureSwitchRegistry? featureSwitchRegistry = null, InboxConfiguration? inboxConfiguration = null, @@ -222,7 +227,8 @@ public CommandProcessor( IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) : this(subscriberRegistry, handlerFactory, requestContextFactory, policyRegistry, - resilienceResiliencePipelineRegistry, requestSchedulerFactory, featureSwitchRegistry, inboxConfiguration) + resilienceResiliencePipelineRegistry, requestSchedulerFactory, loggerFactory, featureSwitchRegistry, + inboxConfiguration) { _responseChannelFactory = responseChannelFactory; _tracer = tracer; @@ -255,6 +261,7 @@ public CommandProcessor( ResiliencePipelineRegistry resilienceResiliencePipelineRegistry, IAmAnOutboxProducerMediator mediator, IAmARequestSchedulerFactory requestSchedulerFactory, + ILoggerFactory loggerFactory, Type? transactionType = null, IAmAFeatureSwitchRegistry? featureSwitchRegistry = null, InboxConfiguration? inboxConfiguration = null, @@ -262,6 +269,9 @@ public CommandProcessor( IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { + _loggerFactory = loggerFactory; + _logger = _loggerFactory.CreateLogger(); + _requestContextFactory = requestContextFactory; _policyRegistry = policyRegistry; _resiliencePipelineRegistry = resilienceResiliencePipelineRegistry; @@ -282,11 +292,12 @@ public CommandProcessor( /// /// An which provides a transaction for TransactionalMessaging /// The transaction type, or CommitableTransaction if transactionProvider is null - public static Type GetTransactionTypeFromTransactionProvider (IAmABoxTransactionProvider? transactionProvider) + public static Type GetTransactionTypeFromTransactionProvider(IAmABoxTransactionProvider? transactionProvider) { Type? transactionType = typeof(CommittableTransaction); - if (transactionProvider == null) return transactionType; - + if (transactionProvider == null) + return transactionType; + var transactionProviderInterface = typeof(IAmABoxTransactionProvider<>); foreach (Type i in transactionProvider.GetType().GetInterfaces()) if (i.IsGenericType && i.GetGenericTypeDefinition() == transactionProviderInterface) @@ -314,10 +325,10 @@ public void Send(T command, RequestContext? requestContext = null) where T : if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _loggerFactory, _inboxConfiguration); try { - Log.BuildingSendPipelineForCommand(s_logger, command.GetType(), command.Id.Value); + Log.BuildingSendPipelineForCommand(_logger, command.GetType(), command.Id.Value); var handlerChain = builder.Build(command, context); AssertValidSendPipeline(command, handlerChain.Count()); @@ -337,7 +348,7 @@ public void Send(T command, RequestContext? requestContext = null) where T : /// public string Send(DateTimeOffset at, TRequest command, RequestContext? requestContext = null) where TRequest : class, IRequest - { + { var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Scheduler, command, requestContext?.Span, options: _instrumentationOptions); try { @@ -375,9 +386,9 @@ public string Send(TimeSpan delay, TRequest command, RequestContext? r /// Allows the sender to cancel the request pipeline. Optional /// awaitable . public async Task SendAsync( - T command, - RequestContext? requestContext = null, - bool continueOnCapturedContext = true, + T command, + RequestContext? requestContext = null, + bool continueOnCapturedContext = true, CancellationToken cancellationToken = default ) where T : class, IRequest @@ -387,18 +398,18 @@ public async Task SendAsync( var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Send, command, requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); - + if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _loggerFactory, _inboxConfiguration); try { - Log.BuildingSendAsyncPipelineForCommand(s_logger, command.GetType(), command.Id.Value); + Log.BuildingSendAsyncPipelineForCommand(_logger, command.GetType(), command.Id.Value); var handlerChain = builder.BuildAsync(command, context, continueOnCapturedContext); AssertValidSendPipeline(command, handlerChain.Count()); - + await handlerChain.First().HandleAsync(command, cancellationToken) .ConfigureAwait(continueOnCapturedContext); } @@ -459,7 +470,7 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { if (_handlerFactorySync == null) throw new InvalidOperationException("No handler factory defined."); - + var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Create, @event, requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); @@ -468,14 +479,14 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); - Log.BuildingSendPipelineForEvent(s_logger, @event.GetType(), @event.Id.Value); + + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _loggerFactory, _inboxConfiguration); + Log.BuildingSendPipelineForEvent(_logger, @event.GetType(), @event.Id.Value); var handlerChain = builder.Build(@event, context); var handlerCount = handlerChain.Count(); - Log.FoundHandlerCountForEvent(s_logger, handlerCount, @event.GetType(), @event.Id.Value); + Log.FoundHandlerCountForEvent(_logger, handlerCount, @event.GetType(), @event.Id.Value); var exceptions = new ConcurrentBag(); Parallel.ForEach(handlerChain, (handleRequests) => @@ -484,10 +495,10 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { var handlerName = handleRequests.Name.ToString(); handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - if(handleRequests.Context is not null) + if (handleRequests.Context is not null) handleRequests.Context.Span = handlerSpans[handlerName]; handleRequests.Handle(@event); - if(handleRequests.Context is not null) + if (handleRequests.Context is not null) handleRequests.Context.Span = span; } catch (Exception e) @@ -495,7 +506,7 @@ public void Publish(T @event, RequestContext? requestContext = null) where T exceptions.Add(e); } }); - + _tracer?.LinkSpans(handlerSpans); if (exceptions.Any()) @@ -529,7 +540,7 @@ public string Publish(DateTimeOffset at, TRequest @event, RequestConte } /// - public string Publish(TimeSpan delay, TRequest @event, RequestContext? requestContext = null) where TRequest : class, IRequest + public string Publish(TimeSpan delay, TRequest @event, RequestContext? requestContext = null) where TRequest : class, IRequest { var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Scheduler, @event, requestContext?.Span, options: _instrumentationOptions); try @@ -571,17 +582,17 @@ public async Task PublishAsync( if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); + + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _loggerFactory, _inboxConfiguration); var handlerSpans = new ConcurrentDictionary(); try { - Log.BuildingSendAsyncPipelineForEvent(s_logger, @event.GetType(), @event.Id.Value); + Log.BuildingSendAsyncPipelineForEvent(_logger, @event.GetType(), @event.Id.Value); var handlerChain = builder.BuildAsync(@event, context, continueOnCapturedContext); var handlerCount = handlerChain.Count(); - Log.FoundAsyncHandlerCount(s_logger, handlerCount, @event.GetType(), @event.Id.Value); + Log.FoundAsyncHandlerCount(_logger, handlerCount, @event.GetType(), @event.Id.Value); var exceptions = new ConcurrentBag(); @@ -591,13 +602,13 @@ public async Task PublishAsync( foreach (var handleRequests in handlerChain) { handlerSpans[handleRequests.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - if(handleRequests.Context is not null) + if (handleRequests.Context is not null) handleRequests.Context.Span = handlerSpans[handleRequests.Name.ToString()]; tasks.Add(handleRequests.HandleAsync(@event, cancellationToken)); - if(handleRequests.Context is not null) + if (handleRequests.Context is not null) handleRequests.Context.Span = span; } - + await Task.WhenAll(tasks).ConfigureAwait(continueOnCapturedContext); } catch (Exception e) @@ -693,12 +704,12 @@ public string Post(DateTimeOffset at, TRequest request, RequestContext finally { _tracer?.EndSpan(span); - } + } } /// public string Post(TimeSpan delay, TRequest request, RequestContext? requestContext = null, Dictionary? args = null) where TRequest : class, IRequest - { + { var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Scheduler, request, requestContext?.Span, options: _instrumentationOptions); try { @@ -708,7 +719,7 @@ public string Post(TimeSpan delay, TRequest request, RequestContext? r finally { _tracer?.EndSpan(span); - } + } } /// @@ -755,7 +766,7 @@ public async Task PostAsync(DateTimeOffset at, TRequest reques finally { _tracer?.EndSpan(span); - } + } } /// @@ -771,7 +782,7 @@ public async Task PostAsync(TimeSpan delay, TRequest request, finally { _tracer?.EndSpan(span); - } + } } /// @@ -812,16 +823,16 @@ public Id DepositPost( /// The type of transaction used by the Outbox /// The Id of the Message that has been deposited. [DepositCallSite] //NOTE: if you adjust the signature, adjust the invocation site - public Id DepositPost( + public Id DepositPost( TRequest request, IAmABoxTransactionProvider? transactionProvider, RequestContext? requestContext = null, Dictionary? args = null, - string? batchId = null) + string? batchId = null) where TRequest : class, IRequest { - Log.SaveRequest(s_logger, request.GetType(), request.Id.Value); - + Log.SaveRequest(_logger, request.GetType(), request.Id.Value); + var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Deposit, request, requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); @@ -893,11 +904,11 @@ public Id[] DepositPost( Dictionary? args = null ) where TRequest : class, IRequest { - Log.SaveBulkRequestsRequest(s_logger, typeof(TRequest)); - + Log.SaveBulkRequestsRequest(_logger, typeof(TRequest)); + var span = _tracer?.CreateBatchSpan(requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); - + try { if (typeof(TTransaction) != _transactionType) @@ -939,7 +950,7 @@ Type transactionType ) where TRequest : class, IRequest { var requestType = typeof(TRequest).FullName; - if(string.IsNullOrEmpty(requestType)) + if (string.IsNullOrEmpty(requestType)) { throw new InvalidOperationException("Could not determine request type for bulk deposit"); } @@ -982,7 +993,7 @@ Type transactionType { var actualRequestType = actualRequest.GetType(); var actualRequestTypeName = actualRequestType.FullName; - if(string.IsNullOrEmpty(actualRequestTypeName)) + if (string.IsNullOrEmpty(actualRequestTypeName)) { throw new InvalidOperationException("Could not determine request type for deposit"); } @@ -1062,10 +1073,10 @@ public async Task DepositPostAsync( CancellationToken cancellationToken = default, string? batchId = null) where TRequest : class, IRequest { - Log.SaveRequest(s_logger, request.GetType(), request.Id.Value); - - var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Deposit, request, requestContext?.Span, options: _instrumentationOptions); - var context = InitRequestContext(span, requestContext); + Log.SaveRequest(_logger, request.GetType(), request.Id.Value); + + var span = _tracer?.CreateSpan(CommandProcessorSpanOperation.Deposit, request, requestContext?.Span, options: _instrumentationOptions); + var context = InitRequestContext(span, requestContext); try { @@ -1155,10 +1166,10 @@ public async Task DepositPostAsync( foreach (var request in requests) { var createSpan = context.Span; - var messageId = await CallDepositPostAsync(request, transactionProvider, context, args, + var messageId = await CallDepositPostAsync(request, transactionProvider, context, args, continueOnCapturedContext, cancellationToken, batchId, typeof(TTransaction)); - successfullySentMessage.Add(messageId); + successfullySentMessage.Add(messageId); context.Span = createSpan; } @@ -1188,7 +1199,7 @@ Type transactionType ) where TRequest : class, IRequest { var requestType = typeof(TRequest).FullName; - if(string.IsNullOrEmpty(requestType)) + if (string.IsNullOrEmpty(requestType)) { throw new InvalidOperationException("Could not determine request type for bulk deposit"); } @@ -1231,7 +1242,7 @@ Type transactionType { var actualRequestType = actualRequest.GetType(); var actualRequestTypeName = actualRequestType.FullName; - if(string.IsNullOrEmpty(actualRequestTypeName)) + if (string.IsNullOrEmpty(actualRequestTypeName)) { throw new InvalidOperationException("Could not determine request type for deposit"); } @@ -1351,7 +1362,7 @@ public void ClearOutbox(Id[] ids, RequestContext? requestContext = null, Diction { var span = _tracer?.CreateClearSpan(CommandProcessorSpanOperation.Create, requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); - + try { _mediator!.ClearOutbox(ids, context, args); @@ -1385,7 +1396,7 @@ public async Task ClearOutboxAsync( { var span = _tracer?.CreateClearSpan(CommandProcessorSpanOperation.Create, requestContext?.Span, options: _instrumentationOptions); var context = InitRequestContext(span, requestContext); - + try { await _mediator!.ClearOutboxAsync(posts, context, continueOnCapturedContext, args, cancellationToken); @@ -1400,7 +1411,7 @@ public async Task ClearOutboxAsync( _tracer?.EndSpan(span); } } - + /// /// Uses the Request-Reply messaging approach to send a message to another server and block awaiting a reply. /// The message is placed into a message queue but not into the outbox. @@ -1417,7 +1428,7 @@ public async Task ClearOutboxAsync( where T : class, ICall where TResponse : class, IResponse { timeOut ??= TimeSpan.FromMilliseconds(500); - + if (timeOut <= TimeSpan.Zero) { throw new InvalidOperationException("Timeout to a call method must have a duration greater than zero"); @@ -1427,7 +1438,7 @@ public async Task ClearOutboxAsync( if (subscription is null) throw new InvalidOperationException($"No Subscription registered fpr replies of type {typeof(T)}"); - + if (_responseChannelFactory is null) throw new InvalidOperationException("No ResponseChannelFactory registered"); @@ -1439,7 +1450,7 @@ public async Task ClearOutboxAsync( subscription.RoutingKey = new RoutingKey(routingKey); using var responseChannel = _responseChannelFactory.CreateSyncChannel(subscription); - Log.CreateReplyQueueForTopic(s_logger, channelName); + Log.CreateReplyQueueForTopic(_logger, channelName); request.ReplyAddress.Topic = subscription.RoutingKey; request.ReplyAddress.CorrelationId = channelName.ToString(); @@ -1456,18 +1467,18 @@ public async Task ClearOutboxAsync( var outMessage = _mediator!.CreateMessageFromRequest(request, context); //We don't store the message, if we continue to fail further retry is left to the sender - Log.SendingRequestWithRoutingkey(s_logger, channelName); + Log.SendingRequestWithRoutingkey(_logger, channelName); _mediator.CallViaExternalBus(outMessage, requestContext); Message? responseMessage = null; - //now we block on the receiver to try and get the message, until timeout. - Log.AwaitingResponseOn(s_logger, channelName); - ExecuteWithResiliencePipeline(() => responseMessage = responseChannel.Receive(timeOut)); + //now we block on the receiver to try and get the message, until timeout. + Log.AwaitingResponseOn(_logger, channelName); + ExecuteWithResiliencePipeline(() => responseMessage = responseChannel.Receive(timeOut)); if (responseMessage is not null && responseMessage.Header.MessageType != MessageType.MT_NONE) { - Log.ReplyReceivedFrom(s_logger, channelName); + Log.ReplyReceivedFrom(_logger, channelName); //map to request is map to a response, but it is a request from consumer point of view. Confusing, but... _mediator.CreateRequestFromMessage(responseMessage, context, out TResponse response); Send(response); @@ -1475,10 +1486,10 @@ public async Task ClearOutboxAsync( return response; } - Log.DeletingQueueForRoutingkey(s_logger, channelName); + Log.DeletingQueueForRoutingkey(_logger, channelName); return null; - } + } catch (Exception e) { _tracer?.AddExceptionToSpan(span, [e]); @@ -1501,7 +1512,7 @@ public static void ClearServiceBus() private void AssertValidSendPipeline(T command, int handlerCount) where T : class, IRequest { - Log.FoundHandlerCountForCommand(s_logger, handlerCount, typeof(T), command.Id.Value); + Log.FoundHandlerCountForCommand(_logger, handlerCount, typeof(T), command.Id.Value); if (handlerCount > 1) throw new ArgumentException( @@ -1510,7 +1521,7 @@ private void AssertValidSendPipeline(T command, int handlerCount) where T : c throw new ArgumentException( $"No command handler was found for the typeof command {typeof(T)} - a command should have exactly one handler."); } - + private bool HandlerFactoryIsNotEitherIAmAHandlerFactorySyncOrAsync(IAmAHandlerFactory handlerFactory) { // If we do not have a subscriber registry and we do not have a handler factory @@ -1540,8 +1551,8 @@ private RequestContext InitRequestContext(Activity? span, RequestContext? reques context.FeatureSwitches = _featureSwitchRegistry; return context; } - - + + private void ExecuteWithResiliencePipeline(Action action) { var resiliencePipeline = _resiliencePipelineRegistry.GetPipeline(RequestReply); @@ -1551,10 +1562,10 @@ private void ExecuteWithResiliencePipeline(Action action) } catch (Exception e) { - Log.ExceptionWhilstTryingToPublishMessage(s_logger, e); + Log.ExceptionWhilstTryingToPublishMessage(_logger, e); } } - + private static partial class Log { [LoggerMessage(LogLevel.Information, "Building send pipeline for command: {CommandType} {Id}")] @@ -1577,28 +1588,28 @@ private static partial class Log [LoggerMessage(LogLevel.Information, "Found {HandlerCount} async pipelines for event: {EventType} {Id}")] public static partial void FoundAsyncHandlerCount(ILogger logger, int handlerCount, Type eventType, string id); - + [LoggerMessage(LogLevel.Information, "Save request: {RequestType} {Id}")] public static partial void SaveRequest(ILogger logger, Type requestType, string id); - + [LoggerMessage(LogLevel.Information, "Save bulk requests request: {RequestType}")] public static partial void SaveBulkRequestsRequest(ILogger logger, Type requestType); - + [LoggerMessage(LogLevel.Information, "Create reply queue for topic {ChannelName}")] public static partial void CreateReplyQueueForTopic(ILogger logger, Guid channelName); - + [LoggerMessage(LogLevel.Debug, "Sending request with routingkey {ChannelName}")] public static partial void SendingRequestWithRoutingkey(ILogger logger, Guid channelName); - + [LoggerMessage(LogLevel.Debug, "Awaiting response on {ChannelName}")] public static partial void AwaitingResponseOn(ILogger logger, Guid channelName); - + [LoggerMessage(LogLevel.Debug, "Reply received from {ChannelName}")] public static partial void ReplyReceivedFrom(ILogger logger, Guid channelName); - + [LoggerMessage(LogLevel.Information, "Deleting queue for routingkey: {ChannelName}")] public static partial void DeletingQueueForRoutingkey(ILogger logger, Guid channelName); - + [LoggerMessage(LogLevel.Error, "Exception whilst trying to publish message")] public static partial void ExceptionWhilstTryingToPublishMessage(ILogger logger, Exception exception); } diff --git a/src/Paramore.Brighter/CommandProcessorBuilder.cs b/src/Paramore.Brighter/CommandProcessorBuilder.cs index d770b21331..fa97f4e355 100644 --- a/src/Paramore.Brighter/CommandProcessorBuilder.cs +++ b/src/Paramore.Brighter/CommandProcessorBuilder.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper @@ -23,7 +23,9 @@ THE SOFTWARE. */ #endregion +using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; using Paramore.Brighter.FeatureSwitch; using Paramore.Brighter.Observability; @@ -102,6 +104,7 @@ public class CommandProcessorBuilder : INeedAHandlers, private InstrumentationOptions? _instrumetationOptions; private IAmABrighterTracer? _tracer; private IAmARequestSchedulerFactory _requestSchedulerFactory = null!; + private ILoggerFactory? _loggerFactory; private CommandProcessorBuilder() { @@ -147,7 +150,7 @@ public INeedMessaging Resilience(ResiliencePipelineRegistry resiliencePi { throw new ConfigurationException("The resilience pipeline registry is missing the CommandProcessor.OutboxProducer resilience pipeline which is required"); } - + policyRegistry ??= new DefaultPolicy(); #pragma warning disable CS0618 // Type or member is obsolete if (!policyRegistry.ContainsKey(CommandProcessor.RETRYPOLICY)) @@ -166,7 +169,7 @@ public INeedMessaging Resilience(ResiliencePipelineRegistry resiliencePi return this; } - + /// public INeedMessaging DefaultResilience() { @@ -203,7 +206,7 @@ public INeedInstrumentation ExternalBus( break; case ExternalBusType.FireAndForget: _bus = bus; - _transactionType = transactionType; + _transactionType = transactionType; break; case ExternalBusType.RPC: _bus = bus; @@ -276,12 +279,22 @@ public IAmACommandProcessorBuilder RequestSchedulerFactory(IAmARequestSchedulerF return this; } + /// + public IAmACommandProcessorBuilder ConfigureLogging(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + return this; + } + /// /// Builds the from the configuration. /// /// CommandProcessor. public CommandProcessor Build() { + var loggerFactory = _loggerFactory ?? throw new ConfigurationException( + "A logger factory is required. Call ConfigureLogging before Build."); + if (_registry == null) throw new ConfigurationException( "A SubscriberRegistry must be provided to construct a command processor"); @@ -303,14 +316,15 @@ public CommandProcessor Build() if (_bus == null) { - return new CommandProcessor(subscriberRegistry: _registry, + return new CommandProcessor(subscriberRegistry: _registry, handlerFactory: _handlerFactory, - requestContextFactory: _requestContextFactory, + requestContextFactory: _requestContextFactory, policyRegistry: _policyRegistry, resilienceResiliencePipelineRegistry: _resiliencePipelineRegistry, featureSwitchRegistry: _featureSwitchRegistry, instrumentationOptions: _instrumetationOptions.Value, - requestSchedulerFactory: _requestSchedulerFactory); + requestSchedulerFactory: _requestSchedulerFactory, + loggerFactory: loggerFactory); } if (!_useRequestReplyQueues) @@ -322,11 +336,12 @@ public CommandProcessor Build() resilienceResiliencePipelineRegistry: _resiliencePipelineRegistry, bus: _bus, transactionType: _transactionType, - featureSwitchRegistry: _featureSwitchRegistry, + featureSwitchRegistry: _featureSwitchRegistry, inboxConfiguration: _inboxConfiguration, tracer: _tracer, instrumentationOptions: _instrumetationOptions.Value, - requestSchedulerFactory: _requestSchedulerFactory + requestSchedulerFactory: _requestSchedulerFactory, + loggerFactory: loggerFactory ); if (_useRequestReplyQueues) @@ -338,13 +353,14 @@ public CommandProcessor Build() resilienceResiliencePipelineRegistry: _resiliencePipelineRegistry, bus: _bus, transactionType: _transactionType, - featureSwitchRegistry: _featureSwitchRegistry, + featureSwitchRegistry: _featureSwitchRegistry, inboxConfiguration: _inboxConfiguration, replySubscriptions: _replySubscriptions, responseChannelFactory: _responseChannelFactory, tracer: _tracer, instrumentationOptions: _instrumetationOptions.Value, - requestSchedulerFactory: _requestSchedulerFactory + requestSchedulerFactory: _requestSchedulerFactory, + loggerFactory: loggerFactory ); throw new ConfigurationException( @@ -393,7 +409,7 @@ public interface INeedResilience /// An interface to continue configuring the messaging pipeline. INeedMessaging DefaultResilience(); } - + /// /// Interface INeedMessaging /// Note that a single command builder does not support both task queues and rpc, using the builder @@ -481,6 +497,14 @@ public interface INeedARequestSchedulerFactory /// public interface IAmACommandProcessorBuilder { + /// + /// Supplies the used to create instance-scoped loggers for the + /// and the object graph it constructs. This must be called before . + /// + /// The logger factory. + /// IAmACommandProcessorBuilder. + IAmACommandProcessorBuilder ConfigureLogging(ILoggerFactory loggerFactory); + /// /// Builds this instance. /// diff --git a/src/Paramore.Brighter/ControlBusSenderFactory.cs b/src/Paramore.Brighter/ControlBusSenderFactory.cs index 44d9a1c568..5aa5a4e364 100644 --- a/src/Paramore.Brighter/ControlBusSenderFactory.cs +++ b/src/Paramore.Brighter/ControlBusSenderFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ #endregion using System.Transactions; +using Microsoft.Extensions.Logging; using Paramore.Brighter.CircuitBreaker; using Paramore.Brighter.Extensions; using Paramore.Brighter.Monitoring.Events; @@ -36,7 +37,7 @@ namespace Paramore.Brighter /// /// Class ControlBusSenderFactory. Helper for creating instances of a control bus (which requires messaging, but not subscribers). /// - public class ControlBusSenderFactory : IAmAControlBusSenderFactory + public class ControlBusSenderFactory(ILoggerFactory loggerFactory) : IAmAControlBusSenderFactory { /// /// Creates the specified configuration. @@ -46,7 +47,7 @@ public class ControlBusSenderFactory : IAmAControlBusSenderFactory /// /// /// IAmAControlBusSender. - public IAmAControlBusSender Create(IAmAnOutbox outbox, + public IAmAControlBusSender Create(IAmAnOutbox outbox, IAmAProducerRegistry producerRegistry, BrighterTracer tracer, IAmARequestSchedulerFactory? requestSchedulerFactory = null, @@ -66,17 +67,19 @@ public IAmAControlBusSender Create(IAmAnOutbox outbox, messageTransformerFactoryAsync: new EmptyMessageTransformerFactoryAsync(), tracer: tracer, outbox: outbox, outboxCircuitBreaker: new InMemoryOutboxCircuitBreaker(), - publicationFinder: publicationFinder ?? new FindPublicationByPublicationTopicOrRequestType() - ); - + publicationFinder: publicationFinder ?? new FindPublicationByPublicationTopicOrRequestType(), + loggerFactory: loggerFactory + ); + return new ControlBusSender( CommandProcessorBuilder.StartNew() .Handlers(new HandlerConfiguration()) .DefaultResilience() - .ExternalBus(ExternalBusType.FireAndForget, mediator) + .ExternalBus(ExternalBusType.FireAndForget, mediator) .ConfigureInstrumentation(null, InstrumentationOptions.None) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(requestSchedulerFactory ?? new InMemorySchedulerFactory()) + .RequestSchedulerFactory(requestSchedulerFactory ?? new InMemorySchedulerFactory(loggerFactory)) + .ConfigureLogging(loggerFactory) .Build() ); } diff --git a/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandler.cs b/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandler.cs index f21e371875..11dc77e69f 100644 --- a/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandler.cs +++ b/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandler.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -25,7 +25,6 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; using Paramore.Brighter.Actions; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Defer.Handlers; @@ -41,9 +40,18 @@ namespace Paramore.Brighter.Defer.Handlers; public partial class DeferMessageOnErrorHandler : RequestHandler, IAmABackstopHandler where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private int _delayMilliseconds; + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public DeferMessageOnErrorHandler(ILogger> logger) + { + _logger = logger; + } + /// /// Initializes from attribute parameters. /// @@ -70,7 +78,7 @@ public override TRequest Handle(TRequest request) } catch (Exception ex) { - Log.UnhandledExceptionDeferringMessage(s_logger, ex, typeof(TRequest).Name, ex.Message); + Log.UnhandledExceptionDeferringMessage(_logger, ex, typeof(TRequest).Name, ex.Message); throw new DeferMessageAction(ex.Message, ex, _delayMilliseconds); } } diff --git a/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandlerAsync.cs b/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandlerAsync.cs index 07e4739f34..323717e546 100644 --- a/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandlerAsync.cs +++ b/src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandlerAsync.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.Actions; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Defer.Handlers; @@ -44,9 +43,18 @@ namespace Paramore.Brighter.Defer.Handlers; public partial class DeferMessageOnErrorHandlerAsync : RequestHandlerAsync, IAmABackstopHandler where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private int _delayMilliseconds; + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public DeferMessageOnErrorHandlerAsync(ILogger> logger) + { + _logger = logger; + } + /// /// Initializes from attribute parameters. /// @@ -74,7 +82,7 @@ public override async Task HandleAsync(TRequest command, CancellationT } catch (Exception ex) { - Log.UnhandledExceptionDeferringMessage(s_logger, ex, typeof(TRequest).Name, ex.Message); + Log.UnhandledExceptionDeferringMessage(_logger, ex, typeof(TRequest).Name, ex.Message); throw new DeferMessageAction(ex.Message, ex, _delayMilliseconds); } } diff --git a/src/Paramore.Brighter/HandlerLifetimeScope.cs b/src/Paramore.Brighter/HandlerLifetimeScope.cs index e009e5bc4d..41946feeba 100644 --- a/src/Paramore.Brighter/HandlerLifetimeScope.cs +++ b/src/Paramore.Brighter/HandlerLifetimeScope.cs @@ -26,31 +26,31 @@ THE SOFTWARE. */ using System.Collections.Generic; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { internal sealed partial class HandlerLifetimeScope : IAmALifetime { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly IAmAHandlerFactorySync? _handlerFactorySync; private readonly List _trackedObjects = new List(); private readonly List _trackedAsyncObjects = new List(); private readonly IAmAHandlerFactoryAsync? _asyncHandlerFactory; - public HandlerLifetimeScope(IAmAHandlerFactorySync handlerFactorySync) - : this(handlerFactorySync, null) - {} + public HandlerLifetimeScope(IAmAHandlerFactorySync handlerFactorySync, ILoggerFactory loggerFactory) + : this(handlerFactorySync, null, loggerFactory) + { } - public HandlerLifetimeScope(IAmAHandlerFactoryAsync asyncHandlerFactory) - : this(null, asyncHandlerFactory) - {} + public HandlerLifetimeScope(IAmAHandlerFactoryAsync asyncHandlerFactory, ILoggerFactory loggerFactory) + : this(null, asyncHandlerFactory, loggerFactory) + { } - public HandlerLifetimeScope(IAmAHandlerFactorySync? handlerFactorySync, IAmAHandlerFactoryAsync? asyncHandlerFactory) + public HandlerLifetimeScope(IAmAHandlerFactorySync? handlerFactorySync, IAmAHandlerFactoryAsync? asyncHandlerFactory, ILoggerFactory loggerFactory) { _handlerFactorySync = handlerFactorySync; _asyncHandlerFactory = asyncHandlerFactory; + _logger = loggerFactory.CreateLogger(); } public int TrackedItemCount => _trackedObjects.Count + _trackedAsyncObjects.Count; @@ -60,7 +60,7 @@ public void Add(IHandleRequests instance) if (_handlerFactorySync == null) throw new ArgumentException("An instance of a handler can not be added without a HandlerFactory."); _trackedObjects.Add(instance); - Log.TrackingInstance(s_logger, instance.GetHashCode(), instance.GetType()); + Log.TrackingInstance(_logger, instance.GetHashCode(), instance.GetType()); } public void Add(IHandleRequestsAsync instance) @@ -68,7 +68,7 @@ public void Add(IHandleRequestsAsync instance) if (_asyncHandlerFactory == null) throw new ArgumentException("An instance of an async handler can not be added without an AsyncHandlerFactory."); _trackedAsyncObjects.Add(instance); - Log.TrackingAsyncHandlerInstance(s_logger, instance.GetHashCode(), instance.GetType()); + Log.TrackingAsyncHandlerInstance(_logger, instance.GetHashCode(), instance.GetType()); } public void Dispose() @@ -77,14 +77,14 @@ public void Dispose() { //free disposable items _handlerFactorySync?.Release(trackedItem, this); - Log.ReleasingHandlerInstance(s_logger, trackedItem.GetHashCode(), trackedItem.GetType()); + Log.ReleasingHandlerInstance(_logger, trackedItem.GetHashCode(), trackedItem.GetType()); }); _trackedAsyncObjects.Each(trackedItem => { //free disposable items _asyncHandlerFactory?.Release(trackedItem, this); - Log.ReleasingAsyncHandlerInstance(s_logger, trackedItem.GetHashCode(), trackedItem.GetType()); + Log.ReleasingAsyncHandlerInstance(_logger, trackedItem.GetHashCode(), trackedItem.GetType()); }); //clear our tracking diff --git a/src/Paramore.Brighter/Id.cs b/src/Paramore.Brighter/Id.cs index 6d2c4948b1..c1e2342f22 100644 --- a/src/Paramore.Brighter/Id.cs +++ b/src/Paramore.Brighter/Id.cs @@ -92,7 +92,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] Id? id) /// /// The to convert. /// The value of the identifier. - public static implicit operator string?(Id id) => id?.Value; + public static implicit operator string?(Id? id) => id?.Value; /// /// Implicitly converts a string to an Id. diff --git a/src/Paramore.Brighter/InMemoryChannelFactory.cs b/src/Paramore.Brighter/InMemoryChannelFactory.cs index 1a13cd470f..1d1230ce45 100644 --- a/src/Paramore.Brighter/InMemoryChannelFactory.cs +++ b/src/Paramore.Brighter/InMemoryChannelFactory.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter { @@ -36,6 +37,7 @@ public class InMemoryChannelFactory : IAmAChannelFactory, IAmAChannelFactoryWith private readonly InternalBus _internalBus; private readonly TimeProvider _timeProvider; private readonly TimeSpan? _ackTimeout; + private readonly ILoggerFactory _loggerFactory; /// /// Gets or sets the message scheduler for delayed requeue support. /// @@ -46,12 +48,14 @@ public class InMemoryChannelFactory : IAmAChannelFactory, IAmAChannelFactoryWith /// /// The internal bus for message routing. /// The time provider for managing time-related operations. + /// The factory used to create loggers. /// Optional acknowledgment timeout. /// Optional scheduler for delayed requeue operations. - public InMemoryChannelFactory(InternalBus internalBus, TimeProvider timeProvider, TimeSpan? ackTimeout = null, IAmAMessageScheduler? scheduler = null) + public InMemoryChannelFactory(InternalBus internalBus, TimeProvider timeProvider, ILoggerFactory loggerFactory, TimeSpan? ackTimeout = null, IAmAMessageScheduler? scheduler = null) { _internalBus = internalBus; _timeProvider = timeProvider; + _loggerFactory = loggerFactory; _ackTimeout = ackTimeout; Scheduler = scheduler; } @@ -64,19 +68,20 @@ public InMemoryChannelFactory(InternalBus internalBus, TimeProvider timeProvider public IAmAChannelSync CreateSyncChannel(Subscription subscription) { var deadLetterSupport = subscription as IUseBrighterDeadLetterSupport; - var deadLetterKey = deadLetterSupport?.DeadLetterRoutingKey; - + var deadLetterKey = deadLetterSupport?.DeadLetterRoutingKey; + var invalidMessageSupport = subscription as IUseBrighterInvalidMessageSupport; var invalidMessageKey = invalidMessageSupport?.InvalidMessageRoutingKey; - + return new Channel( subscription.ChannelName, subscription.RoutingKey, new InMemoryMessageConsumer( - subscription.RoutingKey, - _internalBus, + subscription.RoutingKey, + _internalBus, _timeProvider, - deadLetterKey, + _loggerFactory, + deadLetterKey, invalidMessageKey, ackTimeout: _ackTimeout, scheduler: Scheduler), @@ -104,6 +109,7 @@ public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) subscription.RoutingKey, _internalBus, _timeProvider, + _loggerFactory, deadLetterKey, invalidMessageKey, ackTimeout: _ackTimeout, @@ -133,6 +139,7 @@ public Task CreateAsyncChannelAsync(Subscription subscription, subscription.RoutingKey, _internalBus, _timeProvider, + _loggerFactory, deadLetterKey, invalidMessageKey, ackTimeout: _ackTimeout, diff --git a/src/Paramore.Brighter/InMemoryMessageConsumer.cs b/src/Paramore.Brighter/InMemoryMessageConsumer.cs index a93528d7b6..8175884d5b 100644 --- a/src/Paramore.Brighter/InMemoryMessageConsumer.cs +++ b/src/Paramore.Brighter/InMemoryMessageConsumer.cs @@ -26,6 +26,7 @@ THE SOFTWARE. */ using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter; @@ -47,6 +48,7 @@ public sealed class InMemoryMessageConsumer : IAmAMessageConsumerSync, IAmAMessa private readonly TimeSpan _ackTimeout; private readonly ITimer _lockTimer; private readonly IAmAMessageScheduler? _scheduler; + private readonly ILoggerFactory _loggerFactory; private InMemoryMessageProducer? _requeueProducer; private volatile bool _requeueProducerInitialized; private object? _requeueProducerLock; @@ -65,6 +67,7 @@ public sealed class InMemoryMessageConsumer : IAmAMessageConsumerSync, IAmAMessa /// The that we want to consume from /// The that we want to read the messages from /// Allows us to use a timer that can be controlled from tests + /// The factory used to create loggers. /// If a dead letter channel is required, then provide a topic to use /// If an invalid message channel is required, then provide a topic to use /// The period before we requeue an unacknowledged message; defaults to -1ms or infinite @@ -72,6 +75,7 @@ public sealed class InMemoryMessageConsumer : IAmAMessageConsumerSync, IAmAMessa public InMemoryMessageConsumer(RoutingKey topic, InternalBus bus, TimeProvider timeProvider, + ILoggerFactory loggerFactory, RoutingKey? deadLetterTopic = null, RoutingKey? invalidMessageTopic = null, TimeSpan? ackTimeout = null, @@ -82,6 +86,7 @@ public InMemoryMessageConsumer(RoutingKey topic, _invalidMessageTopic = invalidMessageTopic; _bus = bus; _timeProvider = timeProvider; + _loggerFactory = loggerFactory; _scheduler = scheduler; ackTimeout ??= TimeSpan.FromMilliseconds(-1); _ackTimeout = ackTimeout.Value; @@ -94,7 +99,7 @@ public InMemoryMessageConsumer(RoutingKey topic, ); } - + /// /// Disposes of the consumer, will remove timers, producers, etc. /// @@ -126,7 +131,7 @@ public async Task AcknowledgeAsync(Message message, CancellationToken cancellati { await Task.Run(() => Acknowledge(message), cancellationToken); } - + /// /// Nacks the specified message, removing it from the locked messages and re-enqueuing it to the bus /// so it is immediately available for redelivery. @@ -155,11 +160,12 @@ public async Task NackAsync(Message message, CancellationToken cancellationToken public void Purge() { Message message; - do { + do + { message = _bus.Dequeue(_topic); } while (message.Header.MessageType != MessageType.MT_NONE); } - + /// /// Purges the specified queue name. /// We use Task.Run here to emulate async @@ -180,8 +186,8 @@ public async Task PurgeAsync(CancellationToken cancellationToken = default) public Message[] Receive(TimeSpan? timeOut = null) { timeOut ??= TimeSpan.FromSeconds(1); - - var messages = new[] {_bus.Dequeue(_topic, timeOut)}; + + var messages = new[] { _bus.Dequeue(_topic, timeOut) }; foreach (var message in messages) { //don't lock empty messages @@ -206,8 +212,8 @@ public Task ReceiveAsync(TimeSpan? timeOut = null, CancellationToken { return Task.Run(() => Receive(timeOut), cancellationToken); } - - /// + + /// /// Rejects the specified message. /// /// When a message is rejected, another consumer should not process it. If there is a dead letter, or invalid @@ -221,13 +227,14 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) if (reason is { RejectionReason: RejectionReason.DeliveryError }) { - if ( _deadLetterTopic is null) return true; + if (_deadLetterTopic is null) + return true; message.Header.Topic = _deadLetterTopic; } else if (reason is { RejectionReason: RejectionReason.Unacceptable }) { - if (_invalidMessageTopic is not null) + if (_invalidMessageTopic is not null) message.Header.Topic = _invalidMessageTopic; else if (_deadLetterTopic is not null) message.Header.Topic = _deadLetterTopic; @@ -236,10 +243,11 @@ public bool Reject(Message message, MessageRejectionReason? reason = null) } else if (reason is null) { - if ( _deadLetterTopic is null) return true; + if (_deadLetterTopic is null) + return true; message.Header.Topic = _deadLetterTopic; - } + } _bus.Enqueue(message); @@ -335,7 +343,7 @@ public async Task RequeueAsync(Message message, TimeSpan? timeOut = null, } } - throw new ConfigurationException($"Cannot requeue {message.Id} with delay; no scheduler is configured. Configure a scheduler via MessageSchedulerFactory in IAmProducersConfiguration."); + throw new ConfigurationException($"Cannot requeue {message.Id} with delay; no scheduler is configured. Configure a scheduler via MessageSchedulerFactory in IAmProducersConfiguration."); } /// @@ -349,9 +357,9 @@ public void Dispose() public async ValueTask DisposeAsync() { await DisposeAsyncCore().ConfigureAwait(false); - GC.SuppressFinalize(this); + GC.SuppressFinalize(this); } - + private void CheckLockedMessages() { @@ -374,20 +382,21 @@ private void DisposeCore() private async ValueTask DisposeAsyncCore() { await _lockTimer.DisposeAsync().ConfigureAwait(false); - if (_requeueProducer != null) await _requeueProducer.DisposeAsync().ConfigureAwait(false); + if (_requeueProducer != null) + await _requeueProducer.DisposeAsync().ConfigureAwait(false); } private void EnsureProducer(RoutingKey topic) { #pragma warning disable CS0420 // LazyInitializer handles the memory barrier for the volatile field LazyInitializer.EnsureInitialized(ref _requeueProducer, ref _requeueProducerInitialized, - ref _requeueProducerLock, () => new InMemoryMessageProducer(_bus, new Publication { Topic = topic }) + ref _requeueProducerLock, () => new InMemoryMessageProducer(_bus, _loggerFactory, new Publication { Topic = topic }) { Scheduler = _scheduler }); #pragma warning restore CS0420 } - + private bool RequeueNoDelay(Message message) { _lockedMessages.TryRemove(message.Id.Value, out _); //--allow requeue even if not from locked msg in bus diff --git a/src/Paramore.Brighter/InMemoryMessageProducer.cs b/src/Paramore.Brighter/InMemoryMessageProducer.cs index 660137be31..2024707057 100644 --- a/src/Paramore.Brighter/InMemoryMessageProducer.cs +++ b/src/Paramore.Brighter/InMemoryMessageProducer.cs @@ -30,7 +30,6 @@ THE SOFTWARE. */ using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Tasks; @@ -42,7 +41,7 @@ namespace Paramore.Brighter /// public sealed partial class InMemoryMessageProducer : IAmAMessageProducerSync, IAmAMessageProducerAsync, IAmABulkMessageProducerAsync, ISupportPublishConfirmation, ISupportPublishConfirmationAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly IAmABus _bus; private readonly InstrumentationOptions _instrumentationOptions; private readonly System.Threading.Channels.Channel _channel = @@ -60,12 +59,14 @@ public sealed partial class InMemoryMessageProducer : IAmAMessageProducerSync, I /// then inspect the messages that have been sent. /// /// An instance of typically we use an + /// The factory used to create loggers. /// The that we want to sent messages to via the publication; if null defaults to a Publication with a Topic of "Internal" /// The for how deep should the instrumentation go? - public InMemoryMessageProducer(IAmABus bus, Publication? publication = null, + public InMemoryMessageProducer(IAmABus bus, ILoggerFactory loggerFactory, Publication? publication = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { _bus = bus; + _logger = loggerFactory.CreateLogger(); _instrumentationOptions = instrumentationOptions; Publication = publication ?? new Publication { Topic = new RoutingKey("Internal") }; } @@ -73,7 +74,7 @@ public InMemoryMessageProducer(IAmABus bus, Publication? publication = null, /// /// The publication that describes what the Producer is for /// - public Publication Publication { get; set; } + public Publication Publication { get; set; } /// /// Used for OTel tracing. We use property injection to set this, so that we can use the same tracer across all @@ -291,7 +292,7 @@ private void RaiseActionSubscribers(PublishConfirmationResult result) => } catch (Exception ex) { - Log.ConfirmationCallbackFault(s_logger, result.MessageId.Value, ex); + Log.ConfirmationCallbackFault(_logger, result.MessageId.Value, ex); } })); @@ -306,7 +307,7 @@ private async Task RaiseConfirmationCallbacksAsync(PublishConfirmationResult res } catch (Exception ex) { - Log.ConfirmationCallbackFault(s_logger, result.MessageId.Value, ex); + Log.ConfirmationCallbackFault(_logger, result.MessageId.Value, ex); } } @@ -334,11 +335,11 @@ public void SendWithDelay(Message message, TimeSpan? delay = null) scheduler.Schedule(message, delay.Value); return; } - - throw new ConfigurationException($"Cannot requeue {message.Id} with delay; no scheduler is configured. Configure a scheduler via MessageSchedulerFactory in IAmProducersConfiguration."); - + + throw new ConfigurationException($"Cannot requeue {message.Id} with delay; no scheduler is configured. Configure a scheduler via MessageSchedulerFactory in IAmProducersConfiguration."); + } - + /// /// Send a message to a broker; in this case an with a delay. /// When delay is zero or null, the message is sent immediately. diff --git a/src/Paramore.Brighter/InMemoryMessageProducerFactory.cs b/src/Paramore.Brighter/InMemoryMessageProducerFactory.cs index fd6bebf9ae..e260e91762 100644 --- a/src/Paramore.Brighter/InMemoryMessageProducerFactory.cs +++ b/src/Paramore.Brighter/InMemoryMessageProducerFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter @@ -34,8 +35,9 @@ namespace Paramore.Brighter /// /// An instance of typically we use an /// The list of topics that we want to publish to + /// The factory used to create loggers. /// The for how deep should the instrumentation go? - public class InMemoryMessageProducerFactory(InternalBus bus, IEnumerable publications, InstrumentationOptions instrumentationOptions) + public class InMemoryMessageProducerFactory(InternalBus bus, IEnumerable publications, ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions) : IAmAMessageProducerFactory { @@ -51,7 +53,7 @@ public Dictionary Create() { if (publication.Topic is null) throw new ConfigurationException("A publication must have a Topic to be dispatched"); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: instrumentationOptions); + var producer = new InMemoryMessageProducer(bus, loggerFactory, instrumentationOptions: instrumentationOptions); producer.Publication = publication; var producerKey = new ProducerKey(publication.Topic, publication.Type); if (producers.ContainsKey(producerKey)) diff --git a/src/Paramore.Brighter/InMemoryOutbox.cs b/src/Paramore.Brighter/InMemoryOutbox.cs index 47da7df58c..3d368e97ac 100644 --- a/src/Paramore.Brighter/InMemoryOutbox.cs +++ b/src/Paramore.Brighter/InMemoryOutbox.cs @@ -290,7 +290,7 @@ public Task DeleteAsync( /// A list of dispatched messages public IEnumerable DispatchedMessages( TimeSpan dispatchedSince, - RequestContext requestContext, + RequestContext? requestContext, int pageSize = 100, int pageNumber = 1, int outBoxTimeout = -1, @@ -352,7 +352,7 @@ public Task> DispatchedMessagesAsync(TimeSpan dispatchedSin /// How long to wait for the message before timing out /// For outboxes that require additional parameters such as topic, provide an optional arg /// The message - public Message Get(Id messageId, RequestContext requestContext, int outBoxTimeout = -1, + public Message Get(Id messageId, RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null) { ClearExpiredMessages(); @@ -374,7 +374,7 @@ public Message Get(Id messageId, RequestContext requestContext, int outBoxTimeou } /// - public IEnumerable Get(IEnumerable messageIds, RequestContext requestContext, int outBoxTimeout = -1, + public IEnumerable Get(IEnumerable messageIds, RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null) { ClearExpiredMessages(); @@ -511,7 +511,7 @@ public Task MarkDispatchedAsync( /// What is the context for this request; used to access the Span /// The time that the message was dispatched /// Allows passing arbitrary arguments for searching for a message - not used - public void MarkDispatched(Id id, RequestContext requestContext, DateTimeOffset? dispatchedAt = null, + public void MarkDispatched(Id id, RequestContext? requestContext, DateTimeOffset? dispatchedAt = null, Dictionary? args = null) { ClearExpiredMessages(); diff --git a/src/Paramore.Brighter/InMemoryProducerRegistryFactory.cs b/src/Paramore.Brighter/InMemoryProducerRegistryFactory.cs index 8229477453..f90f2be44f 100644 --- a/src/Paramore.Brighter/InMemoryProducerRegistryFactory.cs +++ b/src/Paramore.Brighter/InMemoryProducerRegistryFactory.cs @@ -24,6 +24,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter @@ -34,8 +35,9 @@ namespace Paramore.Brighter /// /// An instance of typically used for testing /// The list of topics that we want to publish to + /// The factory used to create loggers. /// The for how deep should the instrumentation go? - public class InMemoryProducerRegistryFactory(InternalBus bus, IEnumerable publications, InstrumentationOptions instrumentationOptions) + public class InMemoryProducerRegistryFactory(InternalBus bus, IEnumerable publications, ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions) : IAmAProducerRegistryFactory { /// @@ -44,7 +46,7 @@ public class InMemoryProducerRegistryFactory(InternalBus bus, IEnumerableAn instance of public IAmAProducerRegistry Create() { - var producerFactory = new InMemoryMessageProducerFactory(bus, publications, instrumentationOptions); + var producerFactory = new InMemoryMessageProducerFactory(bus, publications, loggerFactory, instrumentationOptions); return new ProducerRegistry(producerFactory.Create()); } diff --git a/src/Paramore.Brighter/InMemoryScheduler.cs b/src/Paramore.Brighter/InMemoryScheduler.cs index d7cd6639a8..555ef34b38 100644 --- a/src/Paramore.Brighter/InMemoryScheduler.cs +++ b/src/Paramore.Brighter/InMemoryScheduler.cs @@ -31,7 +31,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Scheduler.Events; using Paramore.Brighter.Tasks; using InvalidOperationException = System.InvalidOperationException; @@ -51,12 +50,13 @@ public class InMemoryScheduler( TimeProvider timeProvider, Func getOrCreateRequestSchedulerId, Func getOrCreateMessageSchedulerId, - OnSchedulerConflict onConflict) + OnSchedulerConflict onConflict, + ILoggerFactory loggerFactory) : IAmAMessageSchedulerSync, IAmAMessageSchedulerAsync, IAmARequestSchedulerSync, IAmARequestSchedulerAsync, IDisposable, IAsyncDisposable { private readonly ConcurrentDictionary _timers = new(); private long _generation; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); /// public string Schedule(Message message, DateTimeOffset at) @@ -296,7 +296,7 @@ private void Execute(object? state) return; } - s_logger.LogError("Invalid input during executing scheduler {Data}", state); + _logger.LogError("Invalid input during executing scheduler {Data}", state); } /// diff --git a/src/Paramore.Brighter/InMemorySchedulerFactory.cs b/src/Paramore.Brighter/InMemorySchedulerFactory.cs index 9a89380a76..1b57b231ab 100644 --- a/src/Paramore.Brighter/InMemorySchedulerFactory.cs +++ b/src/Paramore.Brighter/InMemorySchedulerFactory.cs @@ -23,19 +23,20 @@ THE SOFTWARE. */ #endregion using System; +using Microsoft.Extensions.Logging; namespace Paramore.Brighter; /// /// The factory /// -public class InMemorySchedulerFactory : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory +public class InMemorySchedulerFactory(ILoggerFactory loggerFactory) : IAmAMessageSchedulerFactory, IAmARequestSchedulerFactory { /// /// The . /// public TimeProvider TimeProvider { get; set; } = TimeProvider.System; - + /// /// Get or create a scheduler id for a message /// @@ -56,17 +57,17 @@ public class InMemorySchedulerFactory : IAmAMessageSchedulerFactory, IAmARequest /// The action be executed on conflict during scheduler message /// public OnSchedulerConflict OnConflict { get; set; } = OnSchedulerConflict.Throw; - + /// - public IAmAMessageScheduler Create(IAmACommandProcessor processor) - => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict); + public IAmAMessageScheduler Create(IAmACommandProcessor processor) + => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict, loggerFactory); /// public IAmARequestSchedulerSync CreateSync(IAmACommandProcessor processor) - => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict); + => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict, loggerFactory); /// public IAmARequestSchedulerAsync CreateAsync(IAmACommandProcessor processor) - => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict); + => new InMemoryScheduler(processor, TimeProvider, GetOrCreateRequestSchedulerId, GetOrCreateMessageSchedulerId, OnConflict, loggerFactory); } - + diff --git a/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandler.cs b/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandler.cs index 352badd4c6..155e7a0731 100644 --- a/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandler.cs +++ b/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandler.cs @@ -42,9 +42,9 @@ namespace Paramore.Brighter.Inbox.Handlers /// approach is typically called Command Sourcing. /// /// - public partial class UseInboxHandler : RequestHandler where T: class, IRequest + public partial class UseInboxHandler : RequestHandler where T : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; // Set once, process-wide, the first time a custom IRequestContext disables Replay, to keep the warning // out of the hot path. A benign race may let it log a couple of extra times under concurrent first-hits. @@ -64,18 +64,20 @@ public partial class UseInboxHandler : RequestHandler where T: class, IReq /// The store for commands that pass into the system /// An optional causation-tracking outbox, used to replay messages when a duplicate is /// seen and is configured. Resolved from DI when registered. - public UseInboxHandler(IAmAnInboxSync inbox, IAmACausationTrackingOutbox? outbox = null) + /// The logger. + public UseInboxHandler(IAmAnInboxSync inbox, ILogger> logger, IAmACausationTrackingOutbox? outbox = null) { _inbox = inbox; _outbox = outbox; + _logger = logger; } - + public override void InitializeFromAttributeParams(params object?[] initializerList) { - _onceOnly = (bool?) initializerList[0] ?? false; + _onceOnly = (bool?)initializerList[0] ?? false; _contextKey = (string?)initializerList[1]; _onceOnlyAction = (OnceOnlyAction?)initializerList[2] ?? OnceOnlyAction.Throw; - + base.InitializeFromAttributeParams(initializerList); } @@ -100,7 +102,7 @@ public override T Handle(T request) if (_onceOnly) { - Log.CheckingIfCommandHasAlreadyBeenSeen(s_logger, request.Id.Value); + Log.CheckingIfCommandHasAlreadyBeenSeen(_logger, request.Id.Value); if (_inbox.Exists(request.Id.Value, _contextKey, requestContext)) { @@ -109,17 +111,17 @@ public override T Handle(T request) switch (_onceOnlyAction) { case OnceOnlyAction.Throw: - Log.CommandHasAlreadyBeenSeenAsDebug(s_logger, request.Id.Value); + Log.CommandHasAlreadyBeenSeenAsDebug(_logger, request.Id.Value); WriteInboxEvent(span, request, "UseInboxHandler Duplicate Throw"); throw new OnceOnlyException($"A command with id {request.Id} has already been handled"); case OnceOnlyAction.Warn: - Log.CommandHasAlreadyBeenSeenAsWarning(s_logger, request.Id.Value); + Log.CommandHasAlreadyBeenSeenAsWarning(_logger, request.Id.Value); WriteInboxEvent(span, request, "UseInboxHandler Duplicate Warn"); return request; case OnceOnlyAction.Replay: - Log.CommandHasAlreadyBeenSeenReplayingOutbox(s_logger, request.Id.Value); + Log.CommandHasAlreadyBeenSeenReplayingOutbox(_logger, request.Id.Value); var (causationId, replayed) = ReplayCausation(request, requestContext); WriteReplayEvent(span, request, causationId, replayed); return request; @@ -129,7 +131,7 @@ public override T Handle(T request) T handledCommand = base.Handle(request); - Log.WritingCommandToTheInbox(s_logger, request.Id.Value); + Log.WritingCommandToTheInbox(_logger, request.Id.Value); _inbox.Add(request, _contextKey, requestContext); @@ -157,7 +159,7 @@ private RequestContext ResolveRequestContext() // Replay cannot flow the causation id to the outbox and will therefore be a no-op. if (_onceOnlyAction is OnceOnlyAction.Replay && Interlocked.CompareExchange(ref s_warnedAboutCustomContext, 1, 0) == 0) { - Log.CustomContextDisablesReplay(s_logger); + Log.CustomContextDisablesReplay(_logger); } return new RequestContext { Span = Activity.Current }; diff --git a/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandlerAsync.cs b/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandlerAsync.cs index bcd9ab0018..2135b9787a 100644 --- a/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandlerAsync.cs +++ b/src/Paramore.Brighter/Inbox/Handlers/UseInboxHandlerAsync.cs @@ -44,7 +44,7 @@ namespace Paramore.Brighter.Inbox.Handlers /// public partial class UseInboxHandlerAsync : RequestHandlerAsync where T : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; // Set once, process-wide, the first time a custom IRequestContext disables Replay, to keep the warning // out of the hot path. A benign race may let it log a couple of extra times under concurrent first-hits. @@ -64,16 +64,18 @@ public partial class UseInboxHandlerAsync : RequestHandlerAsync where T : /// The store for commands that pass into the system /// An optional causation-tracking outbox, used to replay messages when a duplicate is /// seen and is configured. Resolved from DI when registered. - public UseInboxHandlerAsync(IAmAnInboxAsync inbox, IAmACausationTrackingOutbox? outbox = null) + /// The logger. + public UseInboxHandlerAsync(IAmAnInboxAsync inbox, ILogger> logger, IAmACausationTrackingOutbox? outbox = null) { _inbox = inbox; _outbox = outbox; + _logger = logger; } - - + + public override void InitializeFromAttributeParams(params object?[] initializerList) { - _onceOnly = (bool?) initializerList[0] ?? false; + _onceOnly = (bool?)initializerList[0] ?? false; _contextKey = (string?)initializerList[1]; _onceOnlyAction = (OnceOnlyAction?)initializerList[2] ?? OnceOnlyAction.Throw; @@ -104,7 +106,7 @@ public override async Task HandleAsync(T command, CancellationToken cancellat if (_onceOnly) { - Log.CheckingIfCommandHasBeenSeen(s_logger, command.Id.Value); + Log.CheckingIfCommandHasBeenSeen(_logger, command.Id.Value); //TODO: We should not use an infinite timeout here - how to configure var exists = await _inbox.ExistsAsync(command.Id.Value, _contextKey, requestContext, -1, cancellationToken) @@ -117,17 +119,17 @@ await _inbox.ExistsAsync(command.Id.Value, _contextKey, requestContext, -1, c switch (_onceOnlyAction) { case OnceOnlyAction.Throw: - Log.CommandHasBeenSeen(s_logger, command.Id.Value); + Log.CommandHasBeenSeen(_logger, command.Id.Value); WriteInboxEvent(span, command, "UseInboxHandler Duplicate Throw"); throw new OnceOnlyException($"A command with id {command.Id} has already been handled"); case OnceOnlyAction.Warn: - Log.CommandHasBeenSeenWarning(s_logger, command.Id.Value); + Log.CommandHasBeenSeenWarning(_logger, command.Id.Value); WriteInboxEvent(span, command, "UseInboxHandler Duplicate Warn"); return command; case OnceOnlyAction.Replay: - Log.CommandHasBeenSeenReplayingOutbox(s_logger, command.Id.Value); + Log.CommandHasBeenSeenReplayingOutbox(_logger, command.Id.Value); var (causationId, replayed) = await ReplayCausationAsync(command, requestContext, cancellationToken) .ConfigureAwait(ContinueOnCapturedContext); WriteReplayEvent(span, command, causationId, replayed); @@ -136,7 +138,7 @@ await _inbox.ExistsAsync(command.Id.Value, _contextKey, requestContext, -1, c } } - Log.WritingCommandToInbox(s_logger, command.Id.Value); + Log.WritingCommandToInbox(_logger, command.Id.Value); T handledCommand = await base.HandleAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext); @@ -169,7 +171,7 @@ private RequestContext ResolveRequestContext() if (_onceOnlyAction is OnceOnlyAction.Replay && Interlocked.CompareExchange(ref s_warnedAboutCustomContext, 1, 0) == 0) { - Log.CustomContextDisablesReplay(s_logger); + Log.CustomContextDisablesReplay(_logger); } return new RequestContext { Span = Activity.Current }; diff --git a/src/Paramore.Brighter/JsonConverters/JsonStringConverter.cs b/src/Paramore.Brighter/JsonConverters/JsonStringConverter.cs index 839164a364..fce508bf42 100644 --- a/src/Paramore.Brighter/JsonConverters/JsonStringConverter.cs +++ b/src/Paramore.Brighter/JsonConverters/JsonStringConverter.cs @@ -19,7 +19,7 @@ public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS } } - public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { // For performance, lift up the writer implementation. if (value == null) diff --git a/src/Paramore.Brighter/Logging/ApplicationLogging.cs b/src/Paramore.Brighter/Logging/ApplicationLogging.cs deleted file mode 100644 index 7c80f1e807..0000000000 --- a/src/Paramore.Brighter/Logging/ApplicationLogging.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Microsoft.Extensions.Logging; - -namespace Paramore.Brighter.Logging -{ - public static class ApplicationLogging - { - public static ILoggerFactory LoggerFactory { get; set; } = new LoggerFactory(); - public static ILogger CreateLogger() => LoggerFactory.CreateLogger(); - } -} diff --git a/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandler.cs b/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandler.cs index 214348e8f1..497ae34395 100644 --- a/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandler.cs +++ b/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandler.cs @@ -40,10 +40,19 @@ namespace Paramore.Brighter.Logging.Handlers /// The type of the t request. public partial class RequestLoggingHandler : RequestHandler where TRequest : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private HandlerTiming _timing; + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public RequestLoggingHandler(ILogger> logger) + { + _logger = logger; + } + /// /// Initializes from attribute parameters. /// @@ -60,7 +69,7 @@ public override void InitializeFromAttributeParams(params object?[] initializerL /// TRequest. public override TRequest Handle(TRequest request) { - Log.LogCommand(s_logger, _timing.ToString(), typeof(TRequest), JsonSerializer.Serialize(request, JsonSerialisationOptions.Options), DateTime.UtcNow); + Log.LogCommand(_logger, _timing.ToString(), typeof(TRequest), JsonSerializer.Serialize(request, JsonSerialisationOptions.Options), DateTime.UtcNow); return base.Handle(request); } @@ -85,7 +94,7 @@ public override TRequest Handle(TRequest request) /// TRequest. public override TRequest Fallback(TRequest command) { - Log.LogFailure(s_logger, typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); + Log.LogFailure(_logger, typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); return base.Fallback(command); } diff --git a/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandlerAsync.cs b/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandlerAsync.cs index a7b87a1fe1..554e8a5d1e 100644 --- a/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandlerAsync.cs +++ b/src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandlerAsync.cs @@ -39,10 +39,19 @@ namespace Paramore.Brighter.Logging.Handlers /// The type of the t request. public partial class RequestLoggingHandlerAsync : RequestHandlerAsync where TRequest : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private HandlerTiming _timing; + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public RequestLoggingHandlerAsync(ILogger> logger) + { + _logger = logger; + } + /// /// Initializes from attribute parameters. /// @@ -60,7 +69,7 @@ public override void InitializeFromAttributeParams(params object?[] initializerL /// Awaitable . public override async Task HandleAsync(TRequest command, CancellationToken cancellationToken = default) { - Log.LogCommand(s_logger, _timing.ToString(), typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); + Log.LogCommand(_logger, _timing.ToString(), typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); return await base.HandleAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext); } @@ -86,7 +95,7 @@ public override async Task HandleAsync(TRequest command, CancellationT /// TRequest. public override async Task FallbackAsync(TRequest command, CancellationToken cancellationToken = default) { - Log.LogFailure(s_logger, typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); + Log.LogFailure(_logger, typeof(TRequest), JsonSerializer.Serialize(command, JsonSerialisationOptions.Options), DateTime.UtcNow); return await base.FallbackAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext); } diff --git a/src/Paramore.Brighter/NullOutboxArchiveProvider.cs b/src/Paramore.Brighter/NullOutboxArchiveProvider.cs index 4a687f73ee..e98d6c1780 100644 --- a/src/Paramore.Brighter/NullOutboxArchiveProvider.cs +++ b/src/Paramore.Brighter/NullOutboxArchiveProvider.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2024 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { @@ -36,7 +35,16 @@ namespace Paramore.Brighter /// public class NullOutboxArchiveProvider : IAmAnArchiveProvider { - private readonly ILogger _logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + + /// + /// Creates an archive provider that discards archived messages. + /// + /// The logger. + public NullOutboxArchiveProvider(ILogger logger) + { + _logger = logger; + } /// /// Send a Message to the archive provider diff --git a/src/Paramore.Brighter/OutboxArchiver.cs b/src/Paramore.Brighter/OutboxArchiver.cs index fd61c5e77a..71a815e447 100644 --- a/src/Paramore.Brighter/OutboxArchiver.cs +++ b/src/Paramore.Brighter/OutboxArchiver.cs @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter @@ -39,7 +38,7 @@ namespace Paramore.Brighter /// The transaction type of the Db public partial class OutboxArchiver where TMessage : Message { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; private readonly IAmARequestContextFactory _requestContextFactory; private readonly IAmAnOutboxSync? _outBox; private readonly IAmAnOutboxAsync? _asyncOutbox; @@ -56,6 +55,7 @@ public partial class OutboxArchiver where TMessage : Mes public OutboxArchiver( IAmAnOutbox outbox, IAmAnArchiveProvider archiveProvider, + ILoggerFactory loggerFactory, IAmARequestContextFactory? requestContextFactory = null, int archiveBatchSize = 100, IAmABrighterTracer? tracer = null, @@ -66,9 +66,12 @@ public OutboxArchiver( _tracer = tracer; _instrumentationOptions = instrumentationOptions; _requestContextFactory = requestContextFactory ?? new InMemoryRequestContextFactory(); - - if (outbox is IAmAnOutboxSync syncOutbox) _outBox = syncOutbox; - if (outbox is IAmAnOutboxAsync asyncOutbox) _asyncOutbox = asyncOutbox; + _logger = loggerFactory.CreateLogger>(); + + if (outbox is IAmAnOutboxSync syncOutbox) + _outBox = syncOutbox; + if (outbox is IAmAnOutboxAsync asyncOutbox) + _asyncOutbox = asyncOutbox; } /// @@ -94,25 +97,28 @@ public OutboxArchiver( /// /// How stale is the message that we want archive /// The context for the request pipeline; gives us the OTel span for example - public void Archive(TimeSpan dispatchedSince, RequestContext? requestContext = null) + public void Archive(TimeSpan dispatchedSince, RequestContext? requestContext = null) { requestContext ??= _requestContextFactory.Create(); //This is an archive span parent; we expect individual archiving operations for messages to have their own spans var parentSpan = requestContext.Span; var span = _tracer?.CreateArchiveSpan(requestContext.Span, dispatchedSince, options: _instrumentationOptions); requestContext.Span = span; - + try { - if (_outBox is null) throw new ArgumentException(NoSyncOutboxError); - if (_archiveProvider is null) throw new ArgumentException(NoArchiveProviderError); + if (_outBox is null) + throw new ArgumentException(NoSyncOutboxError); + if (_archiveProvider is null) + throw new ArgumentException(NoArchiveProviderError); var messages = _outBox .DispatchedMessages(dispatchedSince, requestContext, _archiveBatchSize) .ToArray(); - Log.FoundMessagesToArchive(s_logger, messages.Length, _archiveBatchSize); + Log.FoundMessagesToArchive(_logger, messages.Length, _archiveBatchSize); - if (messages.Length <= 0) return; + if (messages.Length <= 0) + return; foreach (var message in messages) { @@ -121,11 +127,11 @@ public void Archive(TimeSpan dispatchedSince, RequestContext? requestContext = n _outBox.Delete(messages.Select(e => e.Id).ToArray(), requestContext); - Log.SuccessfullyArchivedMessages(s_logger, messages.Length, _archiveBatchSize); + Log.SuccessfullyArchivedMessages(_logger, messages.Length, _archiveBatchSize); } catch (Exception e) { - Log.ErrorArchivingFromOutbox(s_logger, e); + Log.ErrorArchivingFromOutbox(_logger, e); _tracer?.AddExceptionToSpan(span, [e]); throw; } @@ -151,11 +157,13 @@ public async Task ArchiveAsync(TimeSpan dispatchedSince, RequestContext? request var parentSpan = requestContext.Span; var span = _tracer?.CreateArchiveSpan(requestContext.Span, dispatchedSince, options: _instrumentationOptions); requestContext.Span = span; - + try { - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); - if (_archiveProvider is null) throw new ArgumentException(NoArchiveProviderError); + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); + if (_archiveProvider is null) + throw new ArgumentException(NoArchiveProviderError); var messages = (await _asyncOutbox.DispatchedMessagesAsync( dispatchedSince, requestContext, pageSize: _archiveBatchSize, cancellationToken: cancellationToken @@ -178,7 +186,7 @@ await _asyncOutbox.DeleteAsync(messages.Select(e => e.Id).ToArray(), requestCont } catch (Exception e) { - Log.ErrorArchivingFromOutbox(s_logger, e); + Log.ErrorArchivingFromOutbox(_logger, e); _tracer?.AddExceptionToSpan(span, [e]); throw; } diff --git a/src/Paramore.Brighter/OutboxProducerMediator.cs b/src/Paramore.Brighter/OutboxProducerMediator.cs index ef7b694cd6..ae4641f05b 100644 --- a/src/Paramore.Brighter/OutboxProducerMediator.cs +++ b/src/Paramore.Brighter/OutboxProducerMediator.cs @@ -42,13 +42,13 @@ namespace Paramore.Brighter /// /// Mediates the interaction between a producer and an outbox. As we want to write to the outbox, and then send from there /// to the producer, we need to take control of produce operations to mediate between the two in a transaction. - /// NOTE: This class is singleton. The CommandProcessor by contrast, is transient or more typically scoped. + /// NOTE: This class is singleton. The CommandProcessor by contrast, is transient or more typically scoped. /// public partial class OutboxProducerMediator : IAmAnOutboxProducerMediator, IAmAnOutboxProducerMediator where TMessage : Message { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private readonly ResiliencePipelineRegistry _resiliencePipelineRegistry; private readonly IAmAMessageMapperRegistry _messageMapperRegistry; @@ -77,7 +77,7 @@ public partial class OutboxProducerMediator : IAmAnOutbo private const string NoSyncOutboxError = "A sync Outbox must be defined."; private const string NoAsyncOutboxError = "An async Outbox must be defined."; - + private int _outStandingCount; //an int rather than a bool so Dispose can claim it with a single atomic Interlocked.Exchange: //an owner and the container disposing concurrently must run CloseAll() (broker I/O) and the factory @@ -88,10 +88,10 @@ public partial class OutboxProducerMediator : IAmAnOutbo private readonly Dictionary _outBoxBag; private readonly IAmABrighterTracer? _tracer; private readonly TimeProvider _timeProvider; - + /// public IAmAnOutbox? Outbox => (IAmAnOutbox?)_outBox ?? _asyncOutbox; - + /// /// Creates an instance of the Outbox Producer Mediator /// @@ -102,6 +102,7 @@ public partial class OutboxProducerMediator : IAmAnOutbo /// The factory used to create a transformer pipeline for an async message mapper /// /// A publication finder. + /// The factory used to create instance-scoped loggers. /// Track unhealthy topics and allow for cooldown, should be registered as singleton and shared with Outbox /// An outbox for transactional messaging, if none is provided, use an InMemoryOutbox /// @@ -129,6 +130,7 @@ public OutboxProducerMediator( IAmAMessageTransformerFactoryAsync messageTransformerFactoryAsync, IAmABrighterTracer? tracer, IAmAPublicationFinder publicationFinder, + ILoggerFactory loggerFactory, IAmAnOutbox? outbox = null, IAmAnOutboxCircuitBreaker? outboxCircuitBreaker = null, IAmARequestContextFactory? requestContextFactory = null, @@ -141,23 +143,17 @@ public OutboxProducerMediator( bool ownsRegistry = false, bool ownsTransformerFactories = false) { + _logger = loggerFactory.CreateLogger(); + _producerRegistry = producerRegistry ?? throw new ConfigurationException("Missing Producer Registry for External Bus Services"); _resiliencePipelineRegistry = resiliencePipelineRegistry ?? throw new ConfigurationException("Missing Resilience Pipeline Registry for External Bus Services"); requestContextFactory ??= new InMemoryRequestContextFactory(); + var mapperRegistryAsync = ValidateMessagingDependencies( + mapperRegistry, messageTransformerFactory, messageTransformerFactoryAsync); - if (mapperRegistry is null) - throw new ConfigurationException( - "A Command Processor with an external bus must have a message mapper registry that implements IAmAMessageMapperRegistry"); - if (mapperRegistry is not IAmAMessageMapperRegistryAsync mapperRegistryAsync) - throw new ConfigurationException( - "A Command Processor with an external bus must have a message mapper registry that implements IAmAMessageMapperRegistryAsync"); - if (messageTransformerFactory is null || messageTransformerFactoryAsync is null) - throw new ConfigurationException( - "A Command Processor with an external bus must have a message transformer factory"); - _timeProvider = timeProvider ?? TimeProvider.System; _lastOutStandingMessageCheckAt = _timeProvider.GetUtcNow(); @@ -167,16 +163,13 @@ public OutboxProducerMediator( _ownsRegistry = ownsRegistry; _ownsTransformerFactories = ownsTransformerFactories; - _transformPipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, instrumentationOptions); + _transformPipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory, instrumentationOptions); _transformPipelineBuilderAsync = - new TransformPipelineBuilderAsync(mapperRegistryAsync, messageTransformerFactoryAsync, instrumentationOptions); + new TransformPipelineBuilderAsync(mapperRegistryAsync, messageTransformerFactoryAsync, loggerFactory, instrumentationOptions); //default to in-memory; expectation for an in memory box is Message and CommittableTransaction outbox ??= new InMemoryOutbox(TimeProvider.System); - outbox.Tracer = tracer; - - if (outbox is IAmAnOutboxSync syncOutbox) _outBox = syncOutbox; - if (outbox is IAmAnOutboxAsync asyncOutbox) _asyncOutbox = asyncOutbox; + (_outBox, _asyncOutbox) = ConfigureOutbox(outbox, tracer); _outboxCircuitBreaker = outboxCircuitBreaker; _outboxTimeout = outboxTimeout; @@ -190,6 +183,32 @@ public OutboxProducerMediator( ConfigureCallbacks(requestContextFactory.Create()); } + private static (IAmAnOutboxSync? Sync, IAmAnOutboxAsync? Async) + ConfigureOutbox(IAmAnOutbox outbox, IAmABrighterTracer? tracer) + { + outbox.Tracer = tracer; + return (outbox as IAmAnOutboxSync, + outbox as IAmAnOutboxAsync); + } + + private static IAmAMessageMapperRegistryAsync ValidateMessagingDependencies( + IAmAMessageMapperRegistry mapperRegistry, + IAmAMessageTransformerFactory messageTransformerFactory, + IAmAMessageTransformerFactoryAsync messageTransformerFactoryAsync) + { + if (mapperRegistry is null) + throw new ConfigurationException( + "A Command Processor with an external bus must have a message mapper registry that implements IAmAMessageMapperRegistry"); + if (mapperRegistry is not IAmAMessageMapperRegistryAsync mapperRegistryAsync) + throw new ConfigurationException( + "A Command Processor with an external bus must have a message mapper registry that implements IAmAMessageMapperRegistryAsync"); + if (messageTransformerFactory is null || messageTransformerFactoryAsync is null) + throw new ConfigurationException( + "A Command Processor with an external bus must have a message transformer factory"); + + return mapperRegistryAsync; + } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// @@ -213,8 +232,9 @@ private void Dispose(bool disposing) //guard every step independently: a failure in one must not skip the rest. Otherwise a throw //from CloseAll() would leak the per-resolution IServiceScope each factory retains for a //mapper or transform obtained but not released — the exact retention this owner exists to drain. - try { _producerRegistry.CloseAll(); } - catch (Exception e) { Log.FailedToCloseProducers(s_logger, e); } + try + { _producerRegistry.CloseAll(); } + catch (Exception e) { Log.FailedToCloseProducers(_logger, e); } //dispose only what this mediator owns. On the DI path it is the sole owner of the runtime //mapper/transform factories (built for it in ServiceCollectionExtensions and never registered in @@ -237,10 +257,11 @@ private void Dispose(bool disposing) //Disposes a member if it is IDisposable, swallowing and logging any failure so one factory's fault //cannot skip the remaining disposals in the teardown chain. - private static void DisposeQuietly(object? member) + private void DisposeQuietly(object? member) { - try { (member as IDisposable)?.Dispose(); } - catch (Exception e) { Log.FailedToDisposeOwnedResource(s_logger, member?.GetType().Name ?? "null", e); } + try + { (member as IDisposable)?.Dispose(); } + catch (Exception e) { Log.FailedToDisposeOwnedResource(_logger, member?.GetType().Name ?? "null", e); } } /// @@ -262,8 +283,9 @@ public async Task AddToOutboxAsync( CancellationToken cancellationToken = default, string? batchId = null) { - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); - + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); + if (batchId != null) { GetBatchOrThrow(batchId).Add(message); @@ -306,7 +328,8 @@ public void AddToOutbox( string? batchId = null ) { - if (_outBox is null) throw new ArgumentException(NoSyncOutboxError); + if (_outBox is null) + throw new ArgumentException(NoSyncOutboxError); if (batchId != null) { GetBatchOrThrow(batchId).Add(message); @@ -333,7 +356,7 @@ public void AddToOutbox( /// Used with RPC to call a remote service via the external bus /// /// The message to send - /// The context of the request pipeline + /// The context of the request pipeline /// The type of the call /// The type of the response public void CallViaExternalBus(Message outMessage, RequestContext? requestContext) @@ -341,10 +364,10 @@ public void CallViaExternalBus(Message outMessage, RequestContext? { //We assume that this only occurs over a blocking producer var producer = _producerRegistry.LookupSyncBy(outMessage.Header.Topic); - ExecuteWithResiliencePipeline( - () => producer.Send(outMessage), - requestContext - ); + ExecuteWithResiliencePipeline( + () => producer.Send(outMessage), + requestContext + ); } /// @@ -378,7 +401,7 @@ public void ClearOutbox( if (messages.Length != posts.Length) { var missingMessageIds = posts.Where(id => !messages.Any(m => m.Id == id)); - Log.OutboxMessagesNotFound(s_logger, string.Join(",", missingMessageIds)); + Log.OutboxMessagesNotFound(_logger, string.Join(",", missingMessageIds)); } BrighterTracer.WriteOutboxEvent(BoxDbOperation.Get, messages, parentSpan, false, false, _instrumentationOptions); @@ -447,7 +470,7 @@ public async Task ClearOutboxAsync( if (messages.Length != postArray.Length) { var missingMessageIds = postArray.Where(id => !messages.Any(m => m.Id == id)); - Log.OutboxMessagesNotFound(s_logger, string.Join(",", missingMessageIds)); + Log.OutboxMessagesNotFound(_logger, string.Join(",", missingMessageIds)); } BrighterTracer.WriteOutboxEvent(BoxDbOperation.Get, messages, parentSpan, false, true, _instrumentationOptions); @@ -483,7 +506,7 @@ public async Task ClearOutboxAsync( /// /// This is the clear outbox for explicit clearing of messages. It runs a task in the background to clear the outbox. /// This method returns whilst that thread runs, so it is non-blocking but also does not indicate the clear has - /// happened by returning control - that happens in parallel. + /// happened by returning control - that happens in parallel. /// /// Only works for Async Outboxes /// Maximum number to clear. @@ -521,13 +544,13 @@ public Message CreateMessageFromRequest(TRequest request, RequestConte { return scheduler.Message; } - + var message = MapMessage(request, requestContext); return message; } /// - /// Given a request, run the transformation pipeline to create a message + /// Given a request, run the transformation pipeline to create a message /// /// The request /// The context of the request pipeline @@ -546,7 +569,7 @@ CancellationToken cancellationToken { return schedulerMessage.Message; } - + var message = await MapMessageAsync(request, requestContext, cancellationToken); return message; } @@ -626,8 +649,9 @@ public void EndBatchAddToOutbox(string batchId, IAmABoxTransactionProvider { _outBox.Add(batch, requestContext, _outboxTimeout, transactionProvider); @@ -654,7 +678,8 @@ public async Task EndBatchAddToOutboxAsync(string batchId, { var batch = BeginBatchAddToOutbox(batchId, transactionProvider, requestContext, isAsync: true); - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); var written = await ExecuteWithResiliencePipelineAsync( async _ => @@ -696,22 +721,23 @@ private List BeginBatchAddToOutbox(string batchId, bool isAsync) { CheckOutboxOutstandingLimit(); - + var batch = GetBatchOrThrow(batchId); - + BrighterTracer.WriteOutboxEvent(BoxDbOperation.Add, batch, requestContext.Span, transactionProvider != null, isAsync, _instrumentationOptions); - + return batch; } - + private List GetBatchOrThrow(string batchId) { - if (_outboxBatches.TryGetValue(batchId, out var batch)) return batch; + if (_outboxBatches.TryGetValue(batchId, out var batch)) + return batch; throw new ArgumentException($"Batch id {batchId} is not active", nameof(batchId)); } - + private async Task BackgroundDispatchUsingAsync( int amountToClear, TimeSpan timeSinceSent, @@ -732,7 +758,8 @@ CancellationToken cancellationToken { requestContext.Span = span; - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); var messages = (await _asyncOutbox.OutstandingMessagesAsync(timeSinceSent, requestContext, pageSize: amountToClear, trippedTopics: _outboxCircuitBreaker?.TrippedTopics, args: args, cancellationToken: cancellationToken)).ToArray(); @@ -742,7 +769,7 @@ CancellationToken cancellationToken requestContext.Span = parentSpan; - Log.FoundMessagesToClear(s_logger, messages.Length, amountToClear); + Log.FoundMessagesToClear(_logger, messages.Length, amountToClear); if (useBulk) { @@ -753,11 +780,11 @@ CancellationToken cancellationToken await DispatchAsync(messages, requestContext, false, cancellationToken); } - Log.MessagesHaveBeenCleared(s_logger); + Log.MessagesHaveBeenCleared(_logger); } catch (Exception e) { - Log.ErrorWhileDispatchingFromOutbox(s_logger, e); + Log.ErrorWhileDispatchingFromOutbox(_logger, e); requestContext.Span?.SetStatus(ActivityStatusCode.Error, "Error while dispatching from outbox"); throw; } @@ -772,7 +799,7 @@ CancellationToken cancellationToken else { requestContext.Span?.SetStatus(ActivityStatusCode.Error); - Log.SkippingDispatchOfMessages(s_logger); + Log.SkippingDispatchOfMessages(_logger); } } @@ -782,7 +809,7 @@ private void CheckOutboxOutstandingLimit() if (!hasOutBox) return; - Log.OutboxOutstandingMessageCount(s_logger, _outStandingCount); + Log.OutboxOutstandingMessageCount(_logger, _outStandingCount); // Because a thread recalculates this, we may always be in a delay, so we check on entry for the next outstanding item bool exceedsOutstandingMessageLimit = _maxOutStandingMessages != -1 && _outStandingCount > _maxOutStandingMessages; @@ -798,15 +825,15 @@ private void CheckOutstandingMessages(RequestContext? requestContext) var timeSinceLastCheck = now - _lastOutStandingMessageCheckAt; - Log.TimeSinceLastCheck(s_logger, timeSinceLastCheck.TotalSeconds); + Log.TimeSinceLastCheck(_logger, timeSinceLastCheck.TotalSeconds); if (timeSinceLastCheck < _maxOutStandingCheckInterval) { - Log.CheckNotReadyToRunYet(s_logger); + Log.CheckNotReadyToRunYet(_logger); return; - } + } - Log.RunningOutstandingMessageCheck(s_logger, now, timeSinceLastCheck.TotalSeconds); + Log.RunningOutstandingMessageCheck(_logger, now, timeSinceLastCheck.TotalSeconds); //This is expensive, so use a background thread Task.Run( () => OutstandingMessagesCheck(requestContext) @@ -814,7 +841,7 @@ private void CheckOutstandingMessages(RequestContext? requestContext) } /// - /// Configure the callbacks for the producers + /// Configure the callbacks for the producers /// private void ConfigureCallbacks(RequestContext requestContext) { @@ -838,7 +865,7 @@ private void ConfigureCallbacks(RequestContext requestContext) /// Outbox /// /// The producer to add a callback for - /// The request context for the pipeline + /// The request context for the pipeline /// private void ConfigureAsyncPublisherCallbackMaybe(IAmAMessageProducerAsync producer, RequestContext requestContext) { @@ -865,7 +892,7 @@ private async Task HandleAsyncPublishConfirmation(PublishConfirmationResult resu { if (result.Success) { - Log.SentMessage(s_logger, result.MessageId.Value); + Log.SentMessage(_logger, result.MessageId.Value); if (_asyncOutbox != null) { // Explicitly re-parent the MarkDispatched DB span to the confirmation @@ -886,7 +913,7 @@ await _asyncOutbox.MarkDispatchedAsync(result.MessageId, dispatchedContext, _tim } else { - Log.ConfirmationFailed(s_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty); + Log.ConfirmationFailed(_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty); // Trip the breaker on the wire topic (result.Topic == message.Header.Topic), // not the Publication topic — exact parity with the non-confirmation send // failure path (see DispatchAsync). TripTopic safely no-ops on null/empty. @@ -897,7 +924,7 @@ await _asyncOutbox.MarkDispatchedAsync(result.MessageId, dispatchedContext, _tim { // The callback must not allow a failed dispatch update to crash the producer. The // message remains undispatched, so the Sweeper will retry it. - Log.ConfirmationDispatchError(s_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty, ex); + Log.ConfirmationDispatchError(_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty, ex); } finally { @@ -925,7 +952,7 @@ await _asyncOutbox.MarkDispatchedAsync(result.MessageId, dispatchedContext, _tim } catch (Exception ex) { - Log.ConfirmationObservabilityFault(s_logger, ex); + Log.ConfirmationObservabilityFault(_logger, ex); return null; } } @@ -939,7 +966,7 @@ private void EndConfirmationSpan(Activity? confirmationSpan) } catch (Exception ex) { - Log.ConfirmationObservabilityFault(s_logger, ex); + Log.ConfirmationObservabilityFault(_logger, ex); } } @@ -948,12 +975,12 @@ private void EndConfirmationSpan(Activity? confirmationSpan) /// Outbox /// /// The producer to add a callback for - /// What is the context for this request; used to access the Span + /// What is the context for this request; used to access the Span private bool ConfigurePublisherCallbackMaybe(IAmAMessageProducerSync producer, RequestContext requestContext) { if (producer is ISupportPublishConfirmation producerSync) { - producerSync.OnMessagePublished += delegate(PublishConfirmationResult result) + producerSync.OnMessagePublished += delegate (PublishConfirmationResult result) { var confirmationSpan = StartConfirmationSpan(result); @@ -961,7 +988,7 @@ private bool ConfigurePublisherCallbackMaybe(IAmAMessageProducerSync producer, R { if (result.Success) { - Log.SentMessage(s_logger, result.MessageId.Value); + Log.SentMessage(_logger, result.MessageId.Value); if (_outBox != null) { @@ -980,7 +1007,7 @@ private bool ConfigurePublisherCallbackMaybe(IAmAMessageProducerSync producer, R } else { - Log.ConfirmationFailed(s_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty); + Log.ConfirmationFailed(_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty); // Trip the breaker on the wire topic (result.Topic == message.Header.Topic), // not the Publication topic — exact parity with the non-confirmation send // failure path (see DispatchAsync). TripTopic safely no-ops on null/empty. @@ -995,7 +1022,7 @@ private bool ConfigurePublisherCallbackMaybe(IAmAMessageProducerSync producer, R // MarkDispatched path — a throwing breaker, logger or context copy must not be able to // crash the producer. The message is left un-dispatched, so the Sweeper will retry it // (C-1); we log at Warning, not Error, because nothing is lost. - Log.ConfirmationDispatchError(s_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty, ex); + Log.ConfirmationDispatchError(_logger, result.MessageId.Value, result.Topic?.Value ?? string.Empty, ex); } finally { @@ -1038,19 +1065,21 @@ private void Dispatch(IEnumerable posts, RequestContext requestContext, var producerSpans = new ConcurrentDictionary(); try { - if (_outBox is null) throw new ArgumentException(NoSyncOutboxError); + if (_outBox is null) + throw new ArgumentException(NoSyncOutboxError); foreach (var message in posts) { // Log the wire topic (Header.Topic) — where the message is going. Producer // lookup uses GetProducerLookupTopic, which may differ from Header.Topic when // a mapper overrode it (e.g. Reply messages routed to a dynamic reply address). - Log.DecoupledInvocationOfMessage(s_logger, message.Header.Topic.Value, message.Id.Value); + Log.DecoupledInvocationOfMessage(_logger, message.Header.Topic.Value, message.Id.Value); var producer = _producerRegistry.LookupBy(GetProducerLookupTopic(message), message.Header.Type, requestContext); var span = _tracer?.CreateProducerSpan(producer.Publication, message, requestContext.Span, _instrumentationOptions); producer.Span = span; - if (span != null) producerSpans.TryAdd(message.Id.Value, span); + if (span != null) + producerSpans.TryAdd(message.Id.Value, span); if (producer is IAmAMessageProducerSync producerSync) { @@ -1090,7 +1119,7 @@ private void Dispatch(IEnumerable posts, RequestContext requestContext, } private async Task BulkDispatchAsync( - IEnumerable posts, + IEnumerable posts, RequestContext requestContext, bool continueOnCapturedContext, CancellationToken cancellationToken) @@ -1101,7 +1130,8 @@ private async Task BulkDispatchAsync( //Chunk into Topics try { - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); // Group by (wire topic, producer-lookup topic) so a batch is guaranteed to // resolve to a single producer — messages with the same wire topic but // different ProducerTopic bag values land in separate batches. @@ -1125,7 +1155,7 @@ private async Task BulkDispatchAsync( { var messages = topicBatch.ToArray(); - Log.BulkDispatchingMessages(s_logger, messages.Length, topicBatch.Key.WireTopic.Value); + Log.BulkDispatchingMessages(_logger, messages.Length, topicBatch.Key.WireTopic.Value); foreach (var batch in await bulkMessageProducer.CreateBatchesAsync(messages, cancellationToken)) { @@ -1183,19 +1213,21 @@ private async Task DispatchAsync( try { - if (_asyncOutbox is null) throw new ArgumentException(NoAsyncOutboxError); + if (_asyncOutbox is null) + throw new ArgumentException(NoAsyncOutboxError); foreach (var message in posts) { // Log the wire topic (Header.Topic) — where the message is going. Producer // lookup uses GetProducerLookupTopic, which may differ from Header.Topic when // a mapper overrode it (e.g. Reply messages routed to a dynamic reply address). - Log.DecoupledInvocationOfMessage(s_logger, message.Header.Topic.Value, message.Id.Value); + Log.DecoupledInvocationOfMessage(_logger, message.Header.Topic.Value, message.Id.Value); var producer = _producerRegistry.LookupBy(GetProducerLookupTopic(message), message.Header.Type, requestContext); var span = _tracer?.CreateProducerSpan(producer.Publication, message, parentSpan, _instrumentationOptions); producer.Span = span; - if (span != null) producerSpans.TryAdd(message.Id.Value, span); + if (span != null) + producerSpans.TryAdd(message.Id.Value, span); if (producer is IAmAMessageProducerAsync producerAsync) { @@ -1220,7 +1252,8 @@ await ExecuteWithResiliencePipelineAsync( ); } - if(!sent) TripTopic(message.Header.Topic); + if (!sent) + TripTopic(message.Header.Topic); } else throw new InvalidOperationException("No async message producer defined."); @@ -1266,7 +1299,7 @@ private Message MapMessage(TRequest request, RequestContext requestCon return message; } - private static void ReleasePipeline(IDisposable pipeline, Id requestId) + private void ReleasePipeline(IDisposable pipeline, Id requestId) { try { @@ -1274,11 +1307,11 @@ private static void ReleasePipeline(IDisposable pipeline, Id requestId) } catch (Exception releaseException) { - Log.FailedToReleasePipeline(s_logger, releaseException, requestId.Value); + Log.FailedToReleasePipeline(_logger, releaseException, requestId.Value); } } - private static async ValueTask ReleasePipelineAsync(IAsyncDisposable pipeline, Id requestId) + private async ValueTask ReleasePipelineAsync(IAsyncDisposable pipeline, Id requestId) { try { @@ -1286,7 +1319,7 @@ private static async ValueTask ReleasePipelineAsync(IAsyncDisposable pipeline, I } catch (Exception releaseException) { - Log.FailedToReleasePipeline(s_logger, releaseException, requestId.Value); + Log.FailedToReleasePipeline(_logger, releaseException, requestId.Value); } } @@ -1334,7 +1367,7 @@ private void OutstandingMessagesCheck(RequestContext? requestContext) s_checkOutstandingSemaphoreToken.Wait(); _lastOutStandingMessageCheckAt = _timeProvider.GetUtcNow(); - Log.BeginCountOfOutstandingMessages(s_logger); + Log.BeginCountOfOutstandingMessages(_logger); try { if (_outBox != null) @@ -1367,12 +1400,12 @@ private void OutstandingMessagesCheck(RequestContext? requestContext) catch (Exception ex) { //if we can't talk to the outbox, swallow the exception on this thread - Log.ErrorGettingOutstandingMessageCount(s_logger, ex); + Log.ErrorGettingOutstandingMessageCount(_logger, ex); _outStandingCount = 0; } finally { - Log.CurrentOutstandingCount(s_logger, _outStandingCount); + Log.CurrentOutstandingCount(_logger, _outStandingCount); s_checkOutstandingSemaphoreToken.Release(); } } @@ -1391,12 +1424,12 @@ private bool ExecuteWithResiliencePipeline(Action action, RequestContext? reques { resiliencePipeline.Execute(action); } - + return true; } catch (Exception ex) { - Log.ExceptionWhilstTryingToPublishMessage(s_logger, ex); + Log.ExceptionWhilstTryingToPublishMessage(_logger, ex); CheckOutstandingMessages(requestContext); return false; } @@ -1423,12 +1456,12 @@ await resiliencePipeline await resiliencePipeline.ExecuteAsync(async ct => await send(ct), cancellationToken) .ConfigureAwait(continueOnCapturedContext); } - + return true; } catch (Exception ex) { - Log.ExceptionWhilstTryingToPublishMessage(s_logger, ex); + Log.ExceptionWhilstTryingToPublishMessage(_logger, ex); CheckOutstandingMessages(requestContext); return false; } @@ -1436,10 +1469,10 @@ await resiliencePipeline.ExecuteAsync(async ct => await send(ct), cancellationTo private void TripTopic(RoutingKey? routingKey) { - if(!RoutingKey.IsNullOrEmpty(routingKey)) + if (!RoutingKey.IsNullOrEmpty(routingKey)) _outboxCircuitBreaker?.TripTopic(routingKey); } - + private static partial class Log { [LoggerMessage(LogLevel.Information, "Found {NumberOfMessages} to clear out of amount {AmountToClear}")] @@ -1447,16 +1480,16 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Failed to release the transform pipeline for request {Id}; the message was mapped successfully and is unaffected")] public static partial void FailedToReleasePipeline(ILogger logger, Exception ex, string id); - + [LoggerMessage(LogLevel.Debug, "Time since last check is {SecondsSinceLastCheck} seconds")] public static partial void TimeSinceLastCheck(ILogger logger, double secondsSinceLastCheck); - + [LoggerMessage(LogLevel.Debug, "Check not ready to run yet")] public static partial void CheckNotReadyToRunYet(ILogger logger); - + [LoggerMessage(LogLevel.Debug, "Running outstanding message check at {MessageCheckTime} after {SecondsSinceLastCheck} seconds wait")] public static partial void RunningOutstandingMessageCheck(ILogger logger, DateTimeOffset messageCheckTime, double secondsSinceLastCheck); - + [LoggerMessage(LogLevel.Information, "Sent message: Id:{Id}")] public static partial void SentMessage(ILogger logger, string id); @@ -1468,37 +1501,37 @@ private static partial class Log [LoggerMessage(LogLevel.Warning, "Error handling publish confirmation for message Id:{Id} on topic {Topic}; message left un-dispatched for Sweeper retry")] public static partial void ConfirmationDispatchError(ILogger logger, string id, string topic, Exception ex); - + [LoggerMessage(LogLevel.Information, "Decoupled invocation of message: Topic:{Topic} Id:{Id}")] public static partial void DecoupledInvocationOfMessage(ILogger logger, string topic, string id); - + [LoggerMessage(LogLevel.Information, "Bulk Dispatching {NumberOfMessages} for Topic {TopicName}")] public static partial void BulkDispatchingMessages(ILogger logger, int numberOfMessages, string topicName); - + [LoggerMessage(LogLevel.Debug, "Begin count of outstanding messages")] public static partial void BeginCountOfOutstandingMessages(ILogger logger); - + [LoggerMessage(LogLevel.Error, "Error getting outstanding message count, reset count")] public static partial void ErrorGettingOutstandingMessageCount(ILogger logger, Exception ex); - + [LoggerMessage(LogLevel.Debug, "Current outstanding count is {OutstandingCount}")] public static partial void CurrentOutstandingCount(ILogger logger, int outstandingCount); - + [LoggerMessage(LogLevel.Error, "Exception whilst trying to publish message")] public static partial void ExceptionWhilstTryingToPublishMessage(ILogger logger, Exception exception); - + [LoggerMessage(LogLevel.Information, "Messages have been cleared")] public static partial void MessagesHaveBeenCleared(ILogger logger); - + [LoggerMessage(LogLevel.Error, "Error while dispatching from outbox")] public static partial void ErrorWhileDispatchingFromOutbox(ILogger logger, Exception exception); - + [LoggerMessage(LogLevel.Information, "Skipping dispatch of messages as another thread is running")] public static partial void SkippingDispatchOfMessages(ILogger logger); [LoggerMessage(LogLevel.Error, "Message(s) with Id(s) {MissingIds} not found in Outbox; dispatching found messages")] public static partial void OutboxMessagesNotFound(ILogger logger, string missingIds); - + [LoggerMessage(LogLevel.Debug, "Outbox outstanding message count is: {OutstandingMessageCount}")] public static partial void OutboxOutstandingMessageCount(ILogger logger, int outstandingMessageCount); diff --git a/src/Paramore.Brighter/PartitionKey.cs b/src/Paramore.Brighter/PartitionKey.cs index e22facb9a0..b8348c72b3 100644 --- a/src/Paramore.Brighter/PartitionKey.cs +++ b/src/Paramore.Brighter/PartitionKey.cs @@ -30,7 +30,7 @@ public PartitionKey(string value) /// Implicitly converts a PartitionKey to its string representation. /// /// The PartitionKey to convert - public static implicit operator string?(PartitionKey key) => key?.Value; + public static implicit operator string?(PartitionKey? key) => key?.Value; /// /// Implicitly converts a string to a PartitionKey. diff --git a/src/Paramore.Brighter/PipelineBuilder.cs b/src/Paramore.Brighter/PipelineBuilder.cs index c204905305..c9d17707c8 100644 --- a/src/Paramore.Brighter/PipelineBuilder.cs +++ b/src/Paramore.Brighter/PipelineBuilder.cs @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Linq; using System.Collections.Generic; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Validation; using Microsoft.Extensions.Logging; using Paramore.Brighter.Inbox.Attributes; @@ -37,7 +36,8 @@ namespace Paramore.Brighter public partial class PipelineBuilder : IAmAPipelineBuilder, IAmAnAsyncPipelineBuilder where TRequest : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly IAmASubscriberRegistry? _subscriberRegistry; private readonly IAmASubscriberRegistryInspector? _subscriberRegistryInspector; @@ -59,11 +59,12 @@ public partial class PipelineBuilder : IAmAPipelineBuilder, public PipelineBuilder( IAmASubscriberRegistry subscriberRegistry, IAmAHandlerFactorySync syncHandlerFactory, - InboxConfiguration? inboxConfiguration = null) + ILoggerFactory loggerFactory, + InboxConfiguration? inboxConfiguration = null) + : this(loggerFactory, inboxConfiguration) { _subscriberRegistry = subscriberRegistry; _syncHandlerFactory = syncHandlerFactory; - _inboxConfiguration = inboxConfiguration; } /// @@ -76,11 +77,12 @@ public PipelineBuilder( public PipelineBuilder( IAmASubscriberRegistry subscriberRegistry, IAmAHandlerFactoryAsync asyncHandlerFactory, + ILoggerFactory loggerFactory, InboxConfiguration? inboxConfiguration = null) + : this(loggerFactory, inboxConfiguration) { _subscriberRegistry = subscriberRegistry; _asyncHandlerFactory = asyncHandlerFactory; - _inboxConfiguration = inboxConfiguration; } /// @@ -91,10 +93,18 @@ public PipelineBuilder( /// Optional inbox configuration for global inbox attribute detection. public PipelineBuilder( IAmASubscriberRegistryInspector subscriberRegistryInspector, + ILoggerFactory loggerFactory, InboxConfiguration? inboxConfiguration = null) + : this(loggerFactory, inboxConfiguration) { _subscriberRegistryInspector = subscriberRegistryInspector; + } + + private PipelineBuilder(ILoggerFactory loggerFactory, InboxConfiguration? inboxConfiguration) + { _inboxConfiguration = inboxConfiguration; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger>(); } /// @@ -173,17 +183,17 @@ public IEnumerable Describe() /// Thrown if there is an error building the pipeline. public Pipelines Build(TRequest request, IRequestContext requestContext) { - if(_syncHandlerFactory is null) + if (_syncHandlerFactory is null) throw new NullReferenceException("HandlerFactorySync is null"); - + try { var observers = _subscriberRegistry!.Get(request, requestContext); - + var pipelines = new Pipelines(); var observerTypes = observers as Type[] ?? observers.ToArray(); - + observerTypes.Each(observer => { var context = observerTypes.Length == 1 ? requestContext : requestContext.CreateCopy(); @@ -191,9 +201,10 @@ public Pipelines Build(TRequest request, IRequestContext requestContex var handler = (RequestHandler?)_syncHandlerFactory.Create(observer, instanceScope); if (handler is null) throw new ConfigurationException($"Handler Factory could not construct handler of type {observer}"); + ConfigureLogging(handler); var pipeline = BuildPipeline(handler, context, instanceScope); pipeline.AddToLifetime(instanceScope); - + pipelines.Add(pipeline); }); @@ -218,9 +229,9 @@ public Pipelines Build(TRequest request, IRequestContext requestContex /// Thrown if there is an error building the pipeline. public AsyncPipelines BuildAsync(TRequest request, IRequestContext requestContext, bool continueOnCapturedContext) { - if(_asyncHandlerFactory is null) + if (_asyncHandlerFactory is null) throw new NullReferenceException("AsyncHandlerFactory is null"); - + try { var observers = _subscriberRegistry!.Get(request, requestContext); @@ -228,24 +239,25 @@ public AsyncPipelines BuildAsync(TRequest request, IRequestContext req var pipelines = new AsyncPipelines(); var observerTypes = observers as Type[] ?? observers.ToArray(); - + observerTypes.Each(observer => { var context = observerTypes.Length == 1 ? requestContext : requestContext.CreateCopy(); var instanceScope = GetAsyncInstanceScope(); var handler = (RequestHandlerAsync?)_asyncHandlerFactory.Create(observer, instanceScope); if (handler is null) - throw new ConfigurationException($"Handler Factory could not construct handler of type {observer}"); + throw new ConfigurationException($"Handler Factory could not construct handler of type {observer}"); + ConfigureLogging(handler); var pipeline = BuildAsyncPipeline(handler, context, instanceScope, continueOnCapturedContext); pipeline.AddToLifetime(instanceScope); - + pipelines.Add(pipeline); }); return pipelines; } - catch (Exception e) when(!(e is ConfigurationException)) + catch (Exception e) when (!(e is ConfigurationException)) { throw new ConfigurationException("Error when building pipeline, see inner Exception for details", e); } @@ -309,7 +321,7 @@ private IHandleRequests BuildPipeline(RequestHandler implici } AppendToPipeline(postAttributes, implicitHandler, requestContext, instanceScope); - Log.NewHandlerPipelineCreated(s_logger, TracePipeline(firstInPipeline).ToString()); + Log.NewHandlerPipelineCreated(_logger, TracePipeline(firstInPipeline).ToString()); return firstInPipeline; } @@ -350,7 +362,7 @@ private IHandleRequestsAsync BuildAsyncPipeline(RequestHandlerAsync preAttributes, RequestHandlerAsync implicitHandler) @@ -424,7 +436,7 @@ private void AddGlobalInboxAttributesAsync(ref IOrderedEnumerable attributes, IHandleRequests implicitHandler, IRequestContext requestContext, IAmALifetime instanceScope) @@ -437,6 +449,7 @@ private void AppendToPipeline(IEnumerable attributes, I { var decorator = new HandlerFactory(attribute, _syncHandlerFactory!, requestContext).CreateRequestHandler(instanceScope); + ConfigureLogging(decorator); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } @@ -460,6 +473,7 @@ private void AppendToAsyncPipeline(IEnumerable attribut var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, instanceScope); + ConfigureLogging(decorator); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } @@ -507,6 +521,7 @@ private IHandleRequests PushOntoPipeline(IEnumerable(attribute, _syncHandlerFactory!, requestContext) .CreateRequestHandler(instanceScope); + ConfigureLogging(decorator); decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; } @@ -534,6 +549,7 @@ private IHandleRequestsAsync PushOntoAsyncPipeline(IEnumerable(attribute, requestContext, instanceScope); + ConfigureLogging(decorator); decorator.ContinueOnCapturedContext = continueOnCapturedContext; decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; @@ -550,6 +566,12 @@ private IHandleRequestsAsync PushOntoAsyncPipeline(IEnumerable firstInPipeline) { var pipelineTracer = new PipelineTracer(); @@ -566,23 +588,23 @@ private PipelineTracer TracePipeline(IHandleRequestsAsync firstInPipel private IAmALifetime GetSyncInstanceScope() { - if(_syncHandlerFactory is null) + if (_syncHandlerFactory is null) throw new NullReferenceException("HandlerFactorySync is null"); - var scope = new HandlerLifetimeScope(_syncHandlerFactory); + var scope = new HandlerLifetimeScope(_syncHandlerFactory, _loggerFactory); _instanceScopes.Add(scope); - + return scope; } private IAmALifetime GetAsyncInstanceScope() { - if(_asyncHandlerFactory is null) + if (_asyncHandlerFactory is null) throw new NullReferenceException("AsyncHandlerFactory is null"); - - var scope = new HandlerLifetimeScope(_asyncHandlerFactory); + + var scope = new HandlerLifetimeScope(_asyncHandlerFactory, _loggerFactory); _instanceScopes.Add(scope); - + return scope; } diff --git a/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandler.cs b/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandler.cs index e98bb816c7..ea0cdb253e 100644 --- a/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandler.cs +++ b/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandler.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -25,7 +25,6 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; using Paramore.Brighter.Actions; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Reject.Handlers; @@ -41,7 +40,16 @@ namespace Paramore.Brighter.Reject.Handlers; public partial class RejectMessageOnErrorHandler : RequestHandler, IAmABackstopHandler where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public RejectMessageOnErrorHandler(ILogger> logger) + { + _logger = logger; + } /// /// Handles the request by passing it to the next handler in the pipeline. @@ -60,7 +68,7 @@ public override TRequest Handle(TRequest request) } catch (Exception ex) { - Log.UnhandledExceptionRejectingMessage(s_logger, ex, typeof(TRequest).Name, ex.Message); + Log.UnhandledExceptionRejectingMessage(_logger, ex, typeof(TRequest).Name, ex.Message); throw new RejectMessageAction(ex.Message, ex); } } diff --git a/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandlerAsync.cs b/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandlerAsync.cs index 22addbbfcc..fcb1e3be06 100644 --- a/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandlerAsync.cs +++ b/src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandlerAsync.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -27,7 +27,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.Actions; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.Reject.Handlers; @@ -44,7 +43,16 @@ namespace Paramore.Brighter.Reject.Handlers; public partial class RejectMessageOnErrorHandlerAsync : RequestHandlerAsync, IAmABackstopHandler where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public RejectMessageOnErrorHandlerAsync(ILogger> logger) + { + _logger = logger; + } /// /// Handles the request asynchronously by passing it to the next handler in the pipeline. @@ -64,7 +72,7 @@ public override async Task HandleAsync(TRequest command, CancellationT } catch (Exception ex) { - Log.UnhandledExceptionRejectingMessage(s_logger, ex, typeof(TRequest).Name, ex.Message); + Log.UnhandledExceptionRejectingMessage(_logger, ex, typeof(TRequest).Name, ex.Message); throw new RejectMessageAction(ex.Message, ex); } } diff --git a/src/Paramore.Brighter/RelationDatabaseOutbox.cs b/src/Paramore.Brighter/RelationDatabaseOutbox.cs index 65998ee4d4..373aae1ecf 100644 --- a/src/Paramore.Brighter/RelationDatabaseOutbox.cs +++ b/src/Paramore.Brighter/RelationDatabaseOutbox.cs @@ -71,7 +71,7 @@ public abstract partial class RelationDatabaseOutbox( /// Task. public void Add( Message message, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, IAmABoxTransactionProvider? transactionProvider = null) { @@ -166,7 +166,7 @@ public void Add( /// Task<Message>. public async Task AddAsync( Message message, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, IAmABoxTransactionProvider? transactionProvider = null, CancellationToken cancellationToken = default) @@ -500,7 +500,7 @@ public IEnumerable DispatchedMessages( /// The message public IEnumerable Get( IEnumerable messageIds, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null) { @@ -542,7 +542,7 @@ public IEnumerable Get( /// The message public Message Get( Id messageId, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null ) @@ -583,7 +583,7 @@ public Message Get( /// . public async Task GetAsync( Id messageId, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default) @@ -617,7 +617,7 @@ public async Task GetAsync( /// public async Task> GetAsync( IEnumerable messageIds, - RequestContext requestContext, + RequestContext? requestContext, int outBoxTimeout = -1, Dictionary? args = null, CancellationToken cancellationToken = default @@ -874,7 +874,7 @@ await WriteToStoreAsync(null, /// Allows additional arguments to be provided for specific Outbox Db providers public void MarkDispatched( Id id, - RequestContext requestContext, + RequestContext? requestContext, DateTimeOffset? dispatchedAt = null, Dictionary? args = null) { diff --git a/src/Paramore.Brighter/RequestHandler.cs b/src/Paramore.Brighter/RequestHandler.cs index c4a1ed0804..5f6291f06a 100644 --- a/src/Paramore.Brighter/RequestHandler.cs +++ b/src/Paramore.Brighter/RequestHandler.cs @@ -26,7 +26,6 @@ THE SOFTWARE. */ using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Policies.Attributes; using Paramore.Brighter.Policies.Handlers; @@ -49,9 +48,15 @@ namespace Paramore.Brighter /// /// The type of the t request. /// The for how deep should the instrumentation go? - public abstract partial class RequestHandler(InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) : IHandleRequests where TRequest : class, IRequest + public abstract partial class RequestHandler(InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) : IHandleRequests, IRequireLoggerFactory where TRequest : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private ILogger? _logger; + + private ILogger Logger => _logger ?? throw new InvalidOperationException( + "Handler logging must be configured by PipelineBuilder before the handler executes."); + + void IRequireLoggerFactory.ConfigureLogging(ILoggerFactory loggerFactory) + => _logger = loggerFactory.CreateLogger>(); private IHandleRequests? _successor; @@ -105,12 +110,12 @@ public virtual TRequest Handle(TRequest request) { if (Context?.Span != null) { - BrighterTracer.WriteHandlerEvent(Context.Span, this.GetType().Name, isAsync:false, instrumentationOptions, isSink:_successor == null); - } - + BrighterTracer.WriteHandlerEvent(Context.Span, this.GetType().Name, isAsync: false, instrumentationOptions, isSink: _successor == null); + } + if (_successor != null) { - Log.PassingRequestFromTo(s_logger, Name, _successor.Name); + Log.PassingRequestFromTo(Logger, Name, _successor.Name); return _successor.Handle(request); } @@ -140,12 +145,12 @@ public virtual TRequest Fallback(TRequest command) { if (Context?.Span != null) { - BrighterTracer.WriteHandlerEvent(Context.Span, $"{this.GetType().Name} Fallback", isAsync:false, instrumentationOptions, isSink:_successor == null); - } - + BrighterTracer.WriteHandlerEvent(Context.Span, $"{this.GetType().Name} Fallback", isAsync: false, instrumentationOptions, isSink: _successor == null); + } + if (_successor != null) { - Log.FallingBackFromTo(s_logger, Name, _successor.Name); + Log.FallingBackFromTo(Logger, Name, _successor.Name); return _successor.Fallback(command); } @@ -172,5 +177,10 @@ private static partial class Log public static partial void FallingBackFromTo(ILogger logger, HandlerName handlerName, HandlerName nextHandler); } } + + internal interface IRequireLoggerFactory + { + void ConfigureLogging(ILoggerFactory loggerFactory); + } } diff --git a/src/Paramore.Brighter/RequestHandlerAsync.cs b/src/Paramore.Brighter/RequestHandlerAsync.cs index 4e23a909ee..a61479ae79 100644 --- a/src/Paramore.Brighter/RequestHandlerAsync.cs +++ b/src/Paramore.Brighter/RequestHandlerAsync.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Policies.Attributes; using Paramore.Brighter.Policies.Handlers; @@ -37,7 +36,7 @@ THE SOFTWARE. */ namespace Paramore.Brighter { /// - /// Class RequestHandlerAsync + /// Class RequestHandlerAsync /// A target of the either as the target of the Command Dispatcher to provide the domain logic required to handle the /// or or as an orthogonal handler used as part of the Command Processor pipeline. /// We recommend deriving your concrete handler from instead of implementing the interface as it provides boilerplate @@ -51,9 +50,15 @@ namespace Paramore.Brighter /// /// The type of the t request. /// The for how deep should the instrumentation go? - public abstract partial class RequestHandlerAsync(InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) : IHandleRequestsAsync where TRequest : class, IRequest + public abstract partial class RequestHandlerAsync(InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) : IHandleRequestsAsync, IRequireLoggerFactory where TRequest : class, IRequest { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private ILogger? _logger; + + private ILogger Logger => _logger ?? throw new InvalidOperationException( + "Handler logging must be configured by PipelineBuilder before the handler executes."); + + void IRequireLoggerFactory.ConfigureLogging(ILoggerFactory loggerFactory) + => _logger = loggerFactory.CreateLogger>(); private IHandleRequestsAsync? _successor; @@ -120,12 +125,12 @@ public virtual async Task HandleAsync(TRequest command, CancellationTo { if (Context?.Span != null) { - BrighterTracer.WriteHandlerEvent(Context.Span, this.GetType().Name, isAsync:true, instrumentationOptions, isSink:_successor == null); - } - + BrighterTracer.WriteHandlerEvent(Context.Span, this.GetType().Name, isAsync: true, instrumentationOptions, isSink: _successor == null); + } + if (_successor != null) { - Log.PassingRequest(s_logger, Name, _successor.Name); + Log.PassingRequest(Logger, Name, _successor.Name); return await _successor.HandleAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext); } @@ -156,12 +161,12 @@ public virtual async Task FallbackAsync(TRequest command, Cancellation { if (Context?.Span != null) { - BrighterTracer.WriteHandlerEvent(Context.Span, $"{this.GetType().Name} Fallback", isAsync:true, instrumentationOptions, isSink:_successor == null); - } - + BrighterTracer.WriteHandlerEvent(Context.Span, $"{this.GetType().Name} Fallback", isAsync: true, instrumentationOptions, isSink: _successor == null); + } + if (_successor != null) { - Log.FallingBack(s_logger, Name, _successor.Name); + Log.FallingBack(Logger, Name, _successor.Name); return await _successor.FallbackAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext); } diff --git a/src/Paramore.Brighter/RoutingKey.cs b/src/Paramore.Brighter/RoutingKey.cs index f094b8f016..27f6c175be 100644 --- a/src/Paramore.Brighter/RoutingKey.cs +++ b/src/Paramore.Brighter/RoutingKey.cs @@ -90,7 +90,7 @@ public override string ToString() /// /// The to convert. /// The result of the conversion. - public static implicit operator string?(RoutingKey rhs) + public static implicit operator string?(RoutingKey? rhs) { return rhs?.ToString(); } diff --git a/src/Paramore.Brighter/SubscriptionName.cs b/src/Paramore.Brighter/SubscriptionName.cs index 0fb02c204f..96782ac636 100644 --- a/src/Paramore.Brighter/SubscriptionName.cs +++ b/src/Paramore.Brighter/SubscriptionName.cs @@ -70,7 +70,7 @@ public override string ToString() /// /// The to convert. /// The result of the conversion. - public static implicit operator string?(SubscriptionName rhs) + public static implicit operator string?(SubscriptionName? rhs) { return rhs?.ToString(); } diff --git a/src/Paramore.Brighter/TraceContext.cs b/src/Paramore.Brighter/TraceContext.cs index f1c8b20dcc..7cb8edac74 100644 --- a/src/Paramore.Brighter/TraceContext.cs +++ b/src/Paramore.Brighter/TraceContext.cs @@ -42,7 +42,7 @@ public TraceParent(string value) /// /// /// - public static implicit operator string?(TraceParent parent) => parent?.Value; + public static implicit operator string?(TraceParent? parent) => parent?.Value; /// /// Converts a string to a TraceParent instance. @@ -105,7 +105,7 @@ public TraceState(string value) /// /// /// - public static implicit operator string?(TraceState state) => state?.Value; + public static implicit operator string?(TraceState? state) => state?.Value; /// /// Converts a string to a TraceState instance. diff --git a/src/Paramore.Brighter/TransformLifetimeScope.cs b/src/Paramore.Brighter/TransformLifetimeScope.cs index febbdde61b..a0db3408ad 100644 --- a/src/Paramore.Brighter/TransformLifetimeScope.cs +++ b/src/Paramore.Brighter/TransformLifetimeScope.cs @@ -1,21 +1,28 @@ using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { - public partial class TransformLifetimeScope(IAmAMessageTransformerFactory factory) : IAmATransformLifetime + public partial class TransformLifetimeScope : IAmATransformLifetime { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly IAmAMessageTransformerFactory _factory; private readonly IList> _trackedObjects = new List>(); + public TransformLifetimeScope(IAmAMessageTransformerFactory factory, ILoggerFactory loggerFactory) + { + _factory = factory; + _logger = loggerFactory.CreateLogger(); + } + public void Dispose() { //SuppressFinalize in a finally: the drain can now throw (a Release failure surfaces as an //AggregateException to an explicit Dispose), and if it does the object would otherwise stay //registered for finalization, whose retry only re-runs the already-drained list — wasted work - try { ReleaseTrackedObjects(); } + try + { ReleaseTrackedObjects(); } finally { GC.SuppressFinalize(this); } } @@ -28,16 +35,17 @@ public void Dispose() //Finalization order is non-deterministic, so this scope can be finalized before its owning //pipeline disposes it. Release best-effort here and swallow; an explicit Dispose still //surfaces the exception to the owner. - try { ReleaseTrackedObjects(); } + try + { ReleaseTrackedObjects(); } catch { /* swallowed: a finalizer must not throw */ } } - + public void Add(Lease lease) { _trackedObjects.Add(lease); - Log.TrackingInstance(s_logger, lease.Instance.GetHashCode(), lease.Instance.GetType()); - } - + Log.TrackingInstance(_logger, lease.Instance.GetHashCode(), lease.Instance.GetType()); + } + private void ReleaseTrackedObjects() { //drain as we go: remove each transform before releasing it, so a Release that throws (MS DI's @@ -56,8 +64,8 @@ private void ReleaseTrackedObjects() _trackedObjects.RemoveAt(lastIndex); try { - factory.Release(trackedItem); - Log.ReleasingHandlerInstance(s_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); + _factory.Release(trackedItem); + Log.ReleasingHandlerInstance(_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); } catch (Exception ex) { @@ -80,3 +88,4 @@ private static partial class Log } } + diff --git a/src/Paramore.Brighter/TransformLifetimeScopeAsync.cs b/src/Paramore.Brighter/TransformLifetimeScopeAsync.cs index 23cc3cf697..56a0b2d6a2 100644 --- a/src/Paramore.Brighter/TransformLifetimeScopeAsync.cs +++ b/src/Paramore.Brighter/TransformLifetimeScopeAsync.cs @@ -2,22 +2,28 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { - public partial class TransformLifetimeScopeAsync(IAmAMessageTransformerFactoryAsync factory) - : IAmATransformLifetimeAsync + public partial class TransformLifetimeScopeAsync : IAmATransformLifetimeAsync { - private static readonly ILogger s_logger= ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly IAmAMessageTransformerFactoryAsync _factory; private readonly IList> _trackedObjects = new List>(); + public TransformLifetimeScopeAsync(IAmAMessageTransformerFactoryAsync factory, ILoggerFactory loggerFactory) + { + _factory = factory; + _logger = loggerFactory.CreateLogger(); + } + public void Dispose() { //SuppressFinalize in a finally: the drain can now throw (a Release failure surfaces as an //AggregateException to an explicit Dispose), and if it does the object would otherwise stay //registered for finalization, whose retry only re-runs the already-drained list — wasted work - try { ReleaseTrackedObjects(); } + try + { ReleaseTrackedObjects(); } finally { GC.SuppressFinalize(this); } } @@ -31,7 +37,8 @@ public async ValueTask DisposeAsync() //SuppressFinalize in a finally: the drain can now throw (a Release failure surfaces as an //AggregateException to an explicit DisposeAsync), and if it does the object would otherwise stay //registered for finalization, whose retry only re-runs the already-drained list — wasted work - try { await ReleaseTrackedObjectsAsync().ConfigureAwait(false); } + try + { await ReleaseTrackedObjectsAsync().ConfigureAwait(false); } finally { GC.SuppressFinalize(this); } } @@ -44,15 +51,16 @@ public async ValueTask DisposeAsync() //Finalization order is non-deterministic, so this scope can be finalized before its owning //pipeline disposes it. Release best-effort here and swallow; an explicit Dispose/DisposeAsync //still surfaces the exception to the owner. - try { ReleaseTrackedObjects(); } + try + { ReleaseTrackedObjects(); } catch { /* swallowed: a finalizer must not throw */ } } public void Add(Lease lease) { _trackedObjects.Add(lease); - Log.TrackingInstance(s_logger, lease.Instance.GetHashCode(), lease.Instance.GetType()); - } + Log.TrackingInstance(_logger, lease.Instance.GetHashCode(), lease.Instance.GetType()); + } private void ReleaseTrackedObjects() { @@ -70,8 +78,8 @@ private void ReleaseTrackedObjects() _trackedObjects.RemoveAt(lastIndex); try { - factory.Release(trackedItem); - Log.ReleasingHandlerInstance(s_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); + _factory.Release(trackedItem); + Log.ReleasingHandlerInstance(_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); } catch (Exception ex) { @@ -99,8 +107,8 @@ private async ValueTask ReleaseTrackedObjectsAsync() _trackedObjects.RemoveAt(lastIndex); try { - await factory.ReleaseAsync(trackedItem).ConfigureAwait(false); - Log.ReleasingHandlerInstance(s_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); + await _factory.ReleaseAsync(trackedItem).ConfigureAwait(false); + Log.ReleasingHandlerInstance(_logger, trackedItem.Instance.GetHashCode(), trackedItem.Instance.GetType()); } catch (Exception ex) { @@ -123,3 +131,4 @@ private static partial class Log } } + diff --git a/src/Paramore.Brighter/TransformPipelineBuilder.cs b/src/Paramore.Brighter/TransformPipelineBuilder.cs index bb56f92ad7..8fe2d9bd55 100644 --- a/src/Paramore.Brighter/TransformPipelineBuilder.cs +++ b/src/Paramore.Brighter/TransformPipelineBuilder.cs @@ -30,7 +30,6 @@ THE SOFTWARE. */ using System.Reflection; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; using Paramore.Brighter.Validation; @@ -47,7 +46,8 @@ namespace Paramore.Brighter /// public partial class TransformPipelineBuilder { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly IAmAMessageMapperRegistry _mapperRegistry; private readonly IAmAMessageTransformerFactory _messageTransformerFactory; @@ -72,8 +72,9 @@ public partial class TransformPipelineBuilder /// The for how deep should the instrumentation go? /// Throws a configuration exception on a null mapperRegistry public TransformPipelineBuilder( - IAmAMessageMapperRegistry mapperRegistry, + IAmAMessageMapperRegistry mapperRegistry, IAmAMessageTransformerFactory messageTransformerFactory, + ILoggerFactory loggerFactory, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All ) { @@ -82,6 +83,8 @@ public TransformPipelineBuilder( _messageTransformerFactory = messageTransformerFactory; _instrumentationOptions = instrumentationOptions; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } /// @@ -101,14 +104,14 @@ public WrapPipeline BuildWrapPipeline() where TRequest : cla transformLeases = BuildTransformPipeline(FindWrapTransforms(messageMapperLease.Instance)); - pipeline = new WrapPipeline(messageMapperLease, _messageTransformerFactory, transformLeases, _instrumentationOptions, _mapperRegistry); + pipeline = new WrapPipeline(messageMapperLease, _messageTransformerFactory, transformLeases, _instrumentationOptions, _loggerFactory, _mapperRegistry); - Log.NewWrapPipelineCreated(s_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); + Log.NewWrapPipelineCreated(_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); var unwraps = FindUnwrapTransforms(messageMapperLease.Instance); if (unwraps.Any()) { - Log.UnwrapAttributesOnMapToMessageMethodIgnored(s_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); + Log.UnwrapAttributesOnMapToMessageMethodIgnored(_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); } return pipeline; @@ -119,8 +122,9 @@ public WrapPipeline BuildWrapPipeline() where TRequest : cla //release them here rather than leak them. Cleanup may throw (Release/Dispose surface //exceptions), so guard it: a disposal failure must not mask the configuration error //the caller needs to see. - try { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } - catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(s_logger, cleanupException); } + try + { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } + catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(_logger, cleanupException); } throw new ConfigurationException("Error building wrap pipeline for outgoing message, see inner exception for details", e); } } @@ -142,14 +146,14 @@ public UnwrapPipeline BuildUnwrapPipeline() where TRequest : transformLeases = BuildTransformPipeline(FindUnwrapTransforms(messageMapperLease.Instance)); - pipeline = new UnwrapPipeline(transformLeases, _messageTransformerFactory, messageMapperLease, _mapperRegistry); + pipeline = new UnwrapPipeline(transformLeases, _messageTransformerFactory, messageMapperLease, _loggerFactory, _mapperRegistry); - Log.NewUnwrapPipelineCreated(s_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); + Log.NewUnwrapPipelineCreated(_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); var wraps = FindWrapTransforms(messageMapperLease.Instance); if (wraps.Any()) { - Log.WrapAttributesOnMapToRequestMethodIgnored(s_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); + Log.WrapAttributesOnMapToRequestMethodIgnored(_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); } return pipeline; @@ -160,8 +164,9 @@ public UnwrapPipeline BuildUnwrapPipeline() where TRequest : //release them here rather than leak them. Cleanup may throw (Release/Dispose surface //exceptions), so guard it: a disposal failure must not mask the configuration error //the caller needs to see. - try { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } - catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(s_logger, cleanupException); } + try + { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } + catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(_logger, cleanupException); } throw new ConfigurationException("Error building unwrap pipeline for outgoing message, see inner exception for details", e); } } @@ -181,7 +186,7 @@ private IEnumerable> BuildTransformPipeline 0) - Log.NoMessageTransformerFactoryConfigured(s_logger, i); + Log.NoMessageTransformerFactoryConfigured(_logger, i); return transforms; } @@ -190,7 +195,7 @@ private IEnumerable> BuildTransformPipeline { - var transformerLease = new TransformerFactory(attribute, _messageTransformerFactory).CreateMessageTransformer(); + var transformerLease = new TransformerFactory(attribute, _messageTransformerFactory, _logger).CreateMessageTransformer(); transforms.Add(transformerLease); }); } @@ -210,7 +215,8 @@ private IEnumerable> BuildTransformPipeline> transformLeases) { - if (_messageTransformerFactory is null) return; + if (_messageTransformerFactory is null) + return; //release every transform even when one Release throws: on the failed-build path no pipeline //owns these transforms and no finalizer retries, so skipping the rest would leak their DI @@ -218,8 +224,9 @@ private void ReleaseTransforms(IEnumerable> transfor //build error the caller rethrows. foreach (var transformLease in transformLeases) { - try { _messageTransformerFactory.Release(transformLease); } - catch (Exception releaseException) { Log.FailedToReleaseTransform(s_logger, releaseException); } + try + { _messageTransformerFactory.Release(transformLease); } + catch (Exception releaseException) { Log.FailedToReleaseTransform(_logger, releaseException); } } } @@ -240,8 +247,10 @@ private void CleanUpAfterFailedBuild( return; } - if (transformLeases is not null) ReleaseTransforms(transformLeases); - if (messageMapperLease is not null) _mapperRegistry.Release(messageMapperLease); + if (transformLeases is not null) + ReleaseTransforms(transformLeases); + if (messageMapperLease is not null) + _mapperRegistry.Release(messageMapperLease); } /// @@ -330,7 +339,8 @@ public static void ClearPipelineCache() private Lease> FindMessageMapper() where TRequest : class, IRequest { var messageMapperLease = _mapperRegistry.Get(); - if (messageMapperLease == null) throw new InvalidOperationException(string.Format("Could not find mapper for {0}. Hint: did you set MessagePumpType.Reactor on the subscription to match the mapper type?", typeof(TRequest).Name)); + if (messageMapperLease == null) + throw new InvalidOperationException(string.Format("Could not find mapper for {0}. Hint: did you set MessagePumpType.Reactor on the subscription to match the mapper type?", typeof(TRequest).Name)); return messageMapperLease; } @@ -387,7 +397,7 @@ private TransformPipelineTracer TraceUnwrapPipeline(UnwrapPipeline public partial class TransformPipelineBuilderAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; private readonly IAmAMessageMapperRegistryAsync _mapperRegistryAsync; private readonly IAmAMessageTransformerFactoryAsync _messageTransformerFactoryAsync; @@ -74,7 +74,8 @@ public partial class TransformPipelineBuilderAsync public TransformPipelineBuilderAsync( IAmAMessageMapperRegistryAsync mapperRegistryAsync, IAmAMessageTransformerFactoryAsync messageTransformerFactoryAsync, - InstrumentationOptions instrumentationOptions + ILoggerFactory loggerFactory, + InstrumentationOptions instrumentationOptions = InstrumentationOptions.All ) { _mapperRegistryAsync = mapperRegistryAsync ?? @@ -82,6 +83,8 @@ InstrumentationOptions instrumentationOptions "TransformPipelineBuilder expected a Message Mapper Registry but none supplied"); _messageTransformerFactoryAsync = messageTransformerFactoryAsync; _instrumentationOptions = instrumentationOptions; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } /// @@ -101,14 +104,14 @@ public WrapPipelineAsync BuildWrapPipeline() where TRequest transformLeases = BuildTransformPipeline(FindWrapTransforms(messageMapperLease.Instance)); - pipeline = new WrapPipelineAsync(messageMapperLease, _messageTransformerFactoryAsync, transformLeases, _instrumentationOptions, _mapperRegistryAsync); + pipeline = new WrapPipelineAsync(messageMapperLease, _messageTransformerFactoryAsync, transformLeases, _instrumentationOptions, _loggerFactory, _mapperRegistryAsync); - Log.NewWrapPipelineCreated(s_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); + Log.NewWrapPipelineCreated(_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); var unwraps = FindUnwrapTransforms(messageMapperLease.Instance); if (unwraps.Any()) { - Log.UnwrapAttributesOnMapToMessageMethodIgnored(s_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); + Log.UnwrapAttributesOnMapToMessageMethodIgnored(_logger, typeof(TRequest).Name, TraceWrapPipeline(pipeline)); } return pipeline; @@ -119,8 +122,9 @@ public WrapPipelineAsync BuildWrapPipeline() where TRequest //release them here rather than leak them. Cleanup may throw (Release/Dispose surface //exceptions), so guard it: a disposal failure must not mask the configuration error //the caller needs to see. - try { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } - catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(s_logger, cleanupException); } + try + { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } + catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(_logger, cleanupException); } throw new ConfigurationException("Error building wrap pipeline for outgoing message, see inner exception for details", e); } } @@ -142,14 +146,14 @@ public UnwrapPipelineAsync BuildUnwrapPipeline() where TRequ transformLeases = BuildTransformPipeline(FindUnwrapTransforms(messageMapperLease.Instance)); - pipeline = new UnwrapPipelineAsync(transformLeases, _messageTransformerFactoryAsync, messageMapperLease, _mapperRegistryAsync); + pipeline = new UnwrapPipelineAsync(transformLeases, _messageTransformerFactoryAsync, messageMapperLease, _loggerFactory, _mapperRegistryAsync); - Log.NewUnwrapPipelineCreated(s_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); + Log.NewUnwrapPipelineCreated(_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); var wraps = FindWrapTransforms(messageMapperLease.Instance); if (wraps.Any()) { - Log.WrapAttributesOnMapToRequestMethodIgnored(s_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); + Log.WrapAttributesOnMapToRequestMethodIgnored(_logger, typeof(TRequest).Name, TraceUnwrapPipeline(pipeline)); } return pipeline; @@ -160,12 +164,13 @@ public UnwrapPipelineAsync BuildUnwrapPipeline() where TRequ //release them here rather than leak them. Cleanup may throw (Release/Dispose surface //exceptions), so guard it: a disposal failure must not mask the configuration error //the caller needs to see. - try { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } - catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(s_logger, cleanupException); } + try + { CleanUpAfterFailedBuild(pipeline, transformLeases, messageMapperLease); } + catch (Exception cleanupException) { Log.FailedToCleanUpAfterFailedBuild(_logger, cleanupException); } throw new ConfigurationException("Error building unwrap pipeline for outgoing message, see inner exception for details", e); } } - + public bool HasPipeline() where TRequest : class, IRequest //resolve the mapper type rather than create an instance: this runs once per message and only //answers "is there a pipeline?", so there is nothing to release and no probe to leak @@ -181,7 +186,7 @@ private IEnumerable> BuildTransformPipeline 0) - Log.NoMessageTransformerFactoryConfigured(s_logger, i); + Log.NoMessageTransformerFactoryConfigured(_logger, i); return transforms; } @@ -190,7 +195,7 @@ private IEnumerable> BuildTransformPipeline { - var transformerLease = new TransformerFactoryAsync(attribute, _messageTransformerFactoryAsync).CreateMessageTransformer(); + var transformerLease = new TransformerFactoryAsync(attribute, _messageTransformerFactoryAsync, _logger).CreateMessageTransformer(); transforms.Add(transformerLease); }); } @@ -210,7 +215,8 @@ private IEnumerable> BuildTransformPipeline> transformLeases) { - if (_messageTransformerFactoryAsync is null) return; + if (_messageTransformerFactoryAsync is null) + return; //release every transform even when one Release throws: on the failed-build path no pipeline //owns these transforms and no finalizer retries, so skipping the rest would leak their DI @@ -218,8 +224,9 @@ private void ReleaseTransforms(IEnumerable> tra //build error the caller rethrows. foreach (var transformLease in transformLeases) { - try { _messageTransformerFactoryAsync.Release(transformLease); } - catch (Exception releaseException) { Log.FailedToReleaseTransform(s_logger, releaseException); } + try + { _messageTransformerFactoryAsync.Release(transformLease); } + catch (Exception releaseException) { Log.FailedToReleaseTransform(_logger, releaseException); } } } @@ -240,8 +247,10 @@ private void CleanUpAfterFailedBuild( return; } - if (transformLeases is not null) ReleaseTransforms(transformLeases); - if (messageMapperLease is not null) _mapperRegistryAsync.Release(messageMapperLease); + if (transformLeases is not null) + ReleaseTransforms(transformLeases); + if (messageMapperLease is not null) + _mapperRegistryAsync.Release(messageMapperLease); } public static void ClearPipelineCache() @@ -253,7 +262,8 @@ public static void ClearPipelineCache() private Lease> FindMessageMapper() where TRequest : class, IRequest { var messageMapperLease = _mapperRegistryAsync.GetAsync(); - if (messageMapperLease == null) throw new InvalidOperationException($"Could not find mapper for {typeof(TRequest).Name}. Hint: did you set MessagePumpType.Proactor on the subscription to match the mapper type?"); + if (messageMapperLease == null) + throw new InvalidOperationException($"Could not find mapper for {typeof(TRequest).Name}. Hint: did you set MessagePumpType.Proactor on the subscription to match the mapper type?"); return messageMapperLease; } diff --git a/src/Paramore.Brighter/TransformerFactory.cs b/src/Paramore.Brighter/TransformerFactory.cs index 1c65a55983..5aa53e6c7d 100644 --- a/src/Paramore.Brighter/TransformerFactory.cs +++ b/src/Paramore.Brighter/TransformerFactory.cs @@ -25,15 +25,15 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { - internal sealed partial class TransformerFactory(TransformAttribute attribute, IAmAMessageTransformerFactory factory) + internal sealed partial class TransformerFactory( + TransformAttribute attribute, + IAmAMessageTransformerFactory factory, + ILogger logger) where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - private readonly Type _messageType = typeof(TRequest); public Lease CreateMessageTransformer() @@ -45,8 +45,10 @@ public Lease CreateMessageTransformer() try { var transformer = lease.Instance; - if (attribute is WrapWithAttribute) transformer.InitializeWrapFromAttributeParams(attribute.InitializerParams()); - if (attribute is UnwrapWithAttribute) transformer.InitializeUnwrapFromAttributeParams(attribute.InitializerParams()); + if (attribute is WrapWithAttribute) + transformer.InitializeWrapFromAttributeParams(attribute.InitializerParams()); + if (attribute is UnwrapWithAttribute) + transformer.InitializeUnwrapFromAttributeParams(attribute.InitializerParams()); } catch (Exception) { @@ -56,8 +58,9 @@ public Lease CreateMessageTransformer() //netstandard2.0 for an IAsyncDisposable-only transform); log-and-swallow it so it cannot //mask the real initialization error being rethrown, but a repeated failure here (an //unreleased transform scope) is not left invisible. - try { factory.Release(lease); } - catch (Exception releaseException) { Log.FailedToReleaseTransformerAfterInitFailure(s_logger, releaseException); } + try + { factory.Release(lease); } + catch (Exception releaseException) { Log.FailedToReleaseTransformerAfterInitFailure(logger, releaseException); } throw; } return lease; diff --git a/src/Paramore.Brighter/TransformerFactoryAsync.cs b/src/Paramore.Brighter/TransformerFactoryAsync.cs index 4bb357fbde..ab1ea0b386 100644 --- a/src/Paramore.Brighter/TransformerFactoryAsync.cs +++ b/src/Paramore.Brighter/TransformerFactoryAsync.cs @@ -23,15 +23,15 @@ THE SOFTWARE. */ using System; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; namespace Paramore.Brighter { - internal sealed partial class TransformerFactoryAsync(TransformAttribute attribute, IAmAMessageTransformerFactoryAsync factory) + internal sealed partial class TransformerFactoryAsync( + TransformAttribute attribute, + IAmAMessageTransformerFactoryAsync factory, + ILogger logger) where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - private readonly Type _messageType = typeof(TRequest); public Lease CreateMessageTransformer() @@ -56,8 +56,9 @@ public Lease CreateMessageTransformer() //netstandard2.0 for an IAsyncDisposable-only transform); log-and-swallow it so it cannot //mask the real initialization error being rethrown, but a repeated failure here (an //unreleased transform scope) is not left invisible. - try { factory.Release(lease); } - catch (Exception releaseException) { Log.FailedToReleaseTransformerAfterInitFailure(s_logger, releaseException); } + try + { factory.Release(lease); } + catch (Exception releaseException) { Log.FailedToReleaseTransformerAfterInitFailure(logger, releaseException); } throw; } return lease; diff --git a/src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs b/src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs index d9dab06086..0871d83c50 100644 --- a/src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs +++ b/src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; using Paramore.Brighter.JsonConverters; -using Paramore.Brighter.Logging; using Paramore.Brighter.Transforms.Attributes; namespace Paramore.Brighter.Transforms.Transformers; @@ -36,9 +35,18 @@ namespace Paramore.Brighter.Transforms.Transformers; /// public partial class CloudEventsTransformer : IAmAMessageTransform, IAmAMessageTransformAsync { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private readonly ILogger _logger; private static readonly Uri s_defaultSource = new(MessageHeader.DefaultSource); + /// + /// Initializes a new instance of the class. + /// + /// The factory used to create the logger. + public CloudEventsTransformer(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } + private Uri? _source; private string? _type; private string? _specVersion; @@ -115,7 +123,7 @@ public void InitializeUnwrapFromAttributeParams(params object?[] initializerList if (initializerList[0] is CloudEventFormat format) { _format = format; - } + } } /// @@ -132,7 +140,7 @@ public Task UnwrapAsync(Message message, CancellationToken cancellation /// public Message Wrap(Message message, Publication publication) { - var msg = ApplyCloudEventsPrecedence(message, publication); + var msg = ApplyCloudEventsPrecedence(message, publication); return _format == CloudEventFormat.Binary ? msg : WriteJsonMessage(msg, publication); } @@ -148,11 +156,11 @@ public Message Unwrap(Message message) return ReadCloudEventJsonMessage(message); } - private static Message ReadCloudEventJsonMessage(Message message) + private Message ReadCloudEventJsonMessage(Message message) { try { - #if NETSTANDARD2_0 +#if NETSTANDARD2_0 var cloudEvents = JsonSerializer.Deserialize(message.Body.Memory.ToArray(), JsonSerialisationOptions.Options); #else var cloudEvents = JsonSerializer.Deserialize(message.Body.Memory.Span, JsonSerialisationOptions.Options); @@ -190,7 +198,7 @@ private static Message ReadCloudEventJsonMessage(Message message) TraceState = message.Header.TraceState, Bag = bag }; - + MessageBody body; if (!string.IsNullOrEmpty(cloudEvents.DataBase64)) { @@ -201,20 +209,20 @@ private static Message ReadCloudEventJsonMessage(Message message) else if (cloudEvents.Data.HasValue) { // JSON or string data - body = cloudEvents.Data.Value.ValueKind == JsonValueKind.String - ? new MessageBody(cloudEvents.Data.Value.GetString() ?? string.Empty) + body = cloudEvents.Data.Value.ValueKind == JsonValueKind.String + ? new MessageBody(cloudEvents.Data.Value.GetString() ?? string.Empty) : new MessageBody(cloudEvents.Data.Value.GetRawText()); } else { body = new MessageBody(string.Empty); } - + return new Message(header, body); } - catch(JsonException ex) + catch (JsonException ex) { - Log.ErrorDuringDeserializerOnUnwrap(s_logger, ex); + Log.ErrorDuringDeserializerOnUnwrap(_logger, ex); return message; } } @@ -243,18 +251,20 @@ private Message ApplyCloudEventsPrecedence(Message message, Publication publicat private static T? ResolveWithSentinel(T? attrValue, T? headerValue, T sentinel, T? publicationValue) where T : class { - if (attrValue is not null) return attrValue; - if (!Equals(headerValue, sentinel)) return headerValue; + if (attrValue is not null) + return attrValue; + if (!Equals(headerValue, sentinel)) + return headerValue; return publicationValue; } - + private Message WriteJsonMessage(Message message, Publication publication) { try { JsonElement? data = null; string? dataBase64 = null; - var contentType = message.Header.ContentType.ToString()?? string.Empty; + var contentType = message.Header.ContentType.ToString() ?? string.Empty; if (message.Body.Value.Length > 0) { if (contentType.Contains("application/json") || contentType.Contains("text/json")) @@ -277,7 +287,7 @@ private Message WriteJsonMessage(Message message, Publication publication) data = JsonDocument.Parse($"\"{encoded.ToString()}\"").RootElement; } } - + var defaultCloudEventsAdditionalProperties = publication.CloudEventsAdditionalProperties ?? new Dictionary(); var cloudEvent = new JsonEvent @@ -302,7 +312,7 @@ private Message WriteJsonMessage(Message message, Publication publication) } catch (JsonException e) { - Log.ErrorDuringDeserializerAJsonOnWrap(s_logger, e); + Log.ErrorDuringDeserializerAJsonOnWrap(_logger, e); return message; } } diff --git a/src/Paramore.Brighter/UnwrapPipeline.cs b/src/Paramore.Brighter/UnwrapPipeline.cs index 2f8a7fd6d7..78f1db6ab0 100644 --- a/src/Paramore.Brighter/UnwrapPipeline.cs +++ b/src/Paramore.Brighter/UnwrapPipeline.cs @@ -23,6 +23,7 @@ THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; namespace Paramore.Brighter @@ -33,7 +34,7 @@ namespace Paramore.Brighter /// Takes a message and maps it to a request /// Runs transforms on that message /// - public class UnwrapPipeline : TransformPipeline where TRequest: class, IRequest + public class UnwrapPipeline : TransformPipeline where TRequest : class, IRequest { /// /// Constructs an instance of an Unwrap pipeline @@ -41,17 +42,19 @@ public class UnwrapPipeline : TransformPipeline where TReque /// The leases over the transforms that run before the mapper /// The factory used to create transforms /// The lease over the message mapper that forms the pipeline sink + /// The factory used to create loggers. /// The registry the message mapper came from, required to release it when the pipeline is disposed public UnwrapPipeline( IEnumerable> transformLeases, IAmAMessageTransformerFactory? messageTransformerFactory, Lease> messageMapperLease, + ILoggerFactory loggerFactory, IAmAMessageMapperRegistry? mapperRegistry = null ) : base(messageMapperLease, transformLeases, mapperRegistry) { if (messageTransformerFactory != null) { - InstanceScope = new TransformLifetimeScope(messageTransformerFactory); + InstanceScope = new TransformLifetimeScope(messageTransformerFactory, loggerFactory); TransformLeases.Each(lease => InstanceScope.Add(lease)); } } @@ -76,16 +79,16 @@ public void DescribePath(TransformPipelineTracer pipelineTracer) /// a request public TRequest Unwrap(Message message, RequestContext? requestContext) { - if(requestContext is not null) + if (requestContext is not null) requestContext.Span ??= Activity.Current; - + var msg = message; Transforms.Each(transform => { transform.Context = requestContext; msg = transform.Unwrap(msg); }); - + MessageMapper.Context = requestContext; return MessageMapper.MapToRequest(msg); } diff --git a/src/Paramore.Brighter/UnwrapPipelineAsync.cs b/src/Paramore.Brighter/UnwrapPipelineAsync.cs index 47cbf3d489..fe0e498d54 100644 --- a/src/Paramore.Brighter/UnwrapPipelineAsync.cs +++ b/src/Paramore.Brighter/UnwrapPipelineAsync.cs @@ -25,6 +25,7 @@ THE SOFTWARE. */ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; namespace Paramore.Brighter @@ -35,7 +36,7 @@ namespace Paramore.Brighter /// Takes a message and maps it to a request /// Runs transforms on that message /// - public class UnwrapPipelineAsync : TransformPipelineAsync where TRequest: class, IRequest + public class UnwrapPipelineAsync : TransformPipelineAsync where TRequest : class, IRequest { /// /// Constructs an instance of an Unwrap pipeline @@ -43,17 +44,19 @@ public class UnwrapPipelineAsync : TransformPipelineAsync wh /// The leases over the transforms that run before the mapper /// The factory used to create transforms /// The lease over the message mapper that forms the pipeline sink + /// The factory used to create loggers. /// The registry the message mapper came from, required to release it when the pipeline is disposed public UnwrapPipelineAsync( IEnumerable> transformLeases, IAmAMessageTransformerFactoryAsync? messageTransformerFactory, Lease> messageMapperLease, + ILoggerFactory loggerFactory, IAmAMessageMapperRegistryAsync? mapperRegistry = null ) : base(messageMapperLease, transformLeases, mapperRegistry) { if (messageTransformerFactory != null) { - InstanceScope = new TransformLifetimeScopeAsync(messageTransformerFactory); + InstanceScope = new TransformLifetimeScopeAsync(messageTransformerFactory, loggerFactory); TransformLeases.Each(lease => InstanceScope.Add(lease)); } } @@ -77,19 +80,20 @@ public void DescribePath(TransformPipelineTracer pipelineTracer) /// The context of the request in this pipeline /// The cancellation token /// a request - public async Task UnwrapAsync(Message message,RequestContext? requestContext, CancellationToken cancellationToken = default) + public async Task UnwrapAsync(Message message, RequestContext? requestContext, CancellationToken cancellationToken = default) { - if(requestContext is not null) + if (requestContext is not null) requestContext.Span ??= Activity.Current; - + var msg = message; - await Transforms.EachAsync(async transform => { - transform.Context = requestContext; - msg = await transform.UnwrapAsync(msg, cancellationToken); + await Transforms.EachAsync(async transform => + { + transform.Context = requestContext; + msg = await transform.UnwrapAsync(msg, cancellationToken); }); MessageMapper.Context = requestContext; return await MessageMapper.MapToRequestAsync(msg, cancellationToken); - } + } } } diff --git a/src/Paramore.Brighter/WrapPipeline.cs b/src/Paramore.Brighter/WrapPipeline.cs index a7181514be..1afb9d4e7e 100644 --- a/src/Paramore.Brighter/WrapPipeline.cs +++ b/src/Paramore.Brighter/WrapPipeline.cs @@ -25,7 +25,6 @@ THE SOFTWARE. */ using System.Diagnostics; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter @@ -36,10 +35,10 @@ namespace Paramore.Brighter /// Takes a request and maps it to a message /// Runs transforms on that message /// - public partial class WrapPipeline : TransformPipeline where TRequest: class, IRequest + public partial class WrapPipeline : TransformPipeline where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - + private readonly ILogger _logger; + private readonly InstrumentationOptions _instrumentationOptions; /// @@ -50,18 +49,21 @@ public partial class WrapPipeline : TransformPipeline where /// The leases over the transforms applied after the message mapper /// The for how deep should the instrumentation go? /// The registry the message mapper came from, required to release it when the pipeline is disposed + /// The factory used to create loggers. public WrapPipeline( Lease> messageMapperLease, IAmAMessageTransformerFactory? messageTransformerFactory, IEnumerable> transformLeases, InstrumentationOptions instrumentationOptions, + ILoggerFactory loggerFactory, IAmAMessageMapperRegistry? mapperRegistry = null ) : base(messageMapperLease, transformLeases, mapperRegistry) { + _logger = loggerFactory.CreateLogger>(); _instrumentationOptions = instrumentationOptions; if (messageTransformerFactory != null) { - InstanceScope = new TransformLifetimeScope(messageTransformerFactory); + InstanceScope = new TransformLifetimeScope(messageTransformerFactory, loggerFactory); TransformLeases.Each(lease => InstanceScope.Add(lease)); } } @@ -94,7 +96,7 @@ public Message Wrap(TRequest request, RequestContext requestContext, Publication if (message.Header.Topic != publication.Topic) { - Log.DifferentPublicationAndMessageTopic(s_logger, publication.Topic?.Value ?? string.Empty, message.Header.Topic.Value); + Log.DifferentPublicationAndMessageTopic(_logger, publication.Topic?.Value ?? string.Empty, message.Header.Topic.Value); if (publication.Topic is not null) { message.Header.Bag[Message.ProducerTopicHeaderName] = publication.Topic.Value; @@ -102,7 +104,7 @@ public Message Wrap(TRequest request, RequestContext requestContext, Publication } BrighterTracer.WriteMapperEvent(message, publication, requestContext.Span, MessageMapper.GetType().Name, false, _instrumentationOptions, true); - + Transforms.Each(transform => { transform.Context = requestContext; @@ -113,11 +115,11 @@ public Message Wrap(TRequest request, RequestContext requestContext, Publication if (!string.IsNullOrEmpty(publication.ReplyTo)) { message.Header.ReplyTo = publication.ReplyTo!; - } - + } + return message; } - + private static partial class Log { [LoggerMessage(LogLevel.Warning, "Topic mismatch detected: The found topic ({FindPublicationTopic}) differs from the message topic ({MessageTopic}). This discrepancy could lead to invalid data in the pipeline")] @@ -125,3 +127,4 @@ private static partial class Log } } } + diff --git a/src/Paramore.Brighter/WrapPipelineAsync.cs b/src/Paramore.Brighter/WrapPipelineAsync.cs index ae6e03069c..59478a069a 100644 --- a/src/Paramore.Brighter/WrapPipelineAsync.cs +++ b/src/Paramore.Brighter/WrapPipelineAsync.cs @@ -29,7 +29,6 @@ THE SOFTWARE. */ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Paramore.Brighter.Extensions; -using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; namespace Paramore.Brighter @@ -40,10 +39,10 @@ namespace Paramore.Brighter /// Takes a request and maps it to a message /// Runs transforms on that message /// - public partial class WrapPipelineAsync : TransformPipelineAsync where TRequest: class, IRequest + public partial class WrapPipelineAsync : TransformPipelineAsync where TRequest : class, IRequest { - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - + private readonly ILogger _logger; + private readonly InstrumentationOptions _instrumentationOptions; /// @@ -54,18 +53,21 @@ public partial class WrapPipelineAsync : TransformPipelineAsyncThe leases over the transforms applied after the message mapper /// The for how deep should the instrumentation go? /// The registry the message mapper came from, required to release it when the pipeline is disposed + /// The factory used to create loggers. public WrapPipelineAsync( Lease> messageMapperLease, IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync, IEnumerable> transformLeases, InstrumentationOptions instrumentationOptions, + ILoggerFactory loggerFactory, IAmAMessageMapperRegistryAsync? mapperRegistry = null ) : base(messageMapperLease, transformLeases, mapperRegistry) { + _logger = loggerFactory.CreateLogger>(); _instrumentationOptions = instrumentationOptions; if (messageTransformerFactoryAsync != null) { - InstanceScope = new TransformLifetimeScopeAsync(messageTransformerFactoryAsync); + InstanceScope = new TransformLifetimeScopeAsync(messageTransformerFactoryAsync, loggerFactory); TransformLeases.Each(lease => InstanceScope.Add(lease)); } } @@ -95,36 +97,36 @@ public async Task WrapAsync(TRequest request, RequestContext requestCon requestContext.Span ??= Activity.Current; MessageMapper.Context = requestContext; - - MessageMapper.Context = requestContext; - var message = await MessageMapper.MapToMessageAsync(request, publication, cancellationToken); - + + MessageMapper.Context = requestContext; + var message = await MessageMapper.MapToMessageAsync(request, publication, cancellationToken); + if (message.Header.Topic != publication.Topic) { - Log.DifferentPublicationAndMessageTopic(s_logger, publication.Topic?.Value ?? string.Empty, message.Header.Topic.Value); + Log.DifferentPublicationAndMessageTopic(_logger, publication.Topic?.Value ?? string.Empty, message.Header.Topic.Value); if (publication.Topic is not null) { message.Header.Bag[Message.ProducerTopicHeaderName] = publication.Topic.Value; } } - + BrighterTracer.WriteMapperEvent(message, publication, requestContext.Span, MessageMapper.GetType().Name, true, _instrumentationOptions, true); - + await Transforms.EachAsync(async transform => { transform.Context = requestContext; message = await transform.WrapAsync(message, publication, cancellationToken); BrighterTracer.WriteMapperEvent(message, publication, requestContext.Span, transform.GetType().Name, true, _instrumentationOptions); - }); - + }); + if (!string.IsNullOrEmpty(publication.ReplyTo)) { message.Header.ReplyTo = publication.ReplyTo!; - } - + } + return message; } - + private static partial class Log { [LoggerMessage(LogLevel.Warning, "Topic mismatch detected: The found topic ({FindPublicationTopic}) differs from the message topic ({MessageTopic}). This discrepancy could lead to invalid data in the pipeline")] @@ -132,3 +134,4 @@ private static partial class Log } } } + diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs index 862e2bf303..2fc5239e22 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -54,16 +54,16 @@ public AwsAssumeInfrastructureTestsAsync() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Assume, TopicAttributes = topicAttributes }); + new SnsPublication { MakeChannels = OnMissingChannel.Assume, TopicAttributes = topicAttributes }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs index c8c8fd99b3..238dc10665 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -25,7 +25,7 @@ public class AwsValidateInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AwsValidateInfrastructureTestsAsync() { _myCommand = new MyCommand { Value = "Test" }; - var replyTo = new RoutingKey("http:\\queueUrl"); + var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Id.Random(); var channelName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,9 +39,9 @@ public AwsValidateInfrastructureTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -52,7 +52,7 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -66,10 +66,10 @@ public AwsValidateInfrastructureTestsAsync() MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName), TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs index a467732eec..4c64630178 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -38,9 +38,9 @@ public AwsValidateInfrastructureByArnTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public AwsValidateInfrastructureByArnTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.ToValidSNSTopicName(true)).Result; @@ -70,9 +70,9 @@ public AwsValidateInfrastructureByArnTestsAsync() FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs index d9fce2ac68..f971cdb2ff 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net.Mime; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); @@ -36,17 +36,17 @@ public SqsRawMessageDeliveryTestsAsync() channelType: ChannelType.PubSub, routingKey: _routingKey, bufferSize: bufferSize, - queueAttributes:new SqsAttributes(rawMessageDelivery: false, type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(rawMessageDelivery: false, type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create)); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, - Topic = _routingKey, + MakeChannels = OnMissingChannel.Create, + Topic = _routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -62,7 +62,8 @@ public async Task When_raw_message_delivery_disabled_async() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 213f6bf20d..c485f17551 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -26,7 +26,7 @@ public SqsMessageConsumerRejectTestsAsync() _myCommand = new MyCommand { Value = "Test" }; var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); - var correlationId =Id.Random(); + var correlationId = Id.Random(); var channelName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var topicName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -38,9 +38,9 @@ public SqsMessageConsumerRejectTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), - topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + topicAttributes: topicAttributes, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SnsMessageProducer(awsConnection, @@ -60,7 +60,7 @@ public SqsMessageConsumerRejectTestsAsync() MakeChannels = OnMissingChannel.Create, Topic = routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 54949c21ca..276e3930b3 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net; @@ -72,11 +72,11 @@ public SnsReDrivePolicySDlqTestsAsync() Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create, - TopicAttributes = topicAttributes - } - ); + TopicAttributes = topicAttributes + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -90,8 +90,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -99,11 +99,11 @@ public SnsReDrivePolicySDlqTestsAsync() ); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs index a03390536d..570c5b0166 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,15 +36,15 @@ public AwsAssumeInfrastructureTests() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -66,7 +66,7 @@ public AwsAssumeInfrastructureTests() subscriptionName: new SubscriptionName(queueName), channelName: channelName, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Assume); @@ -74,12 +74,12 @@ public AwsAssumeInfrastructureTests() _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Assume, + MakeChannels = OnMissingChannel.Assume, Topic = routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs index 57ae1fb0ed..4089259123 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,15 +36,15 @@ public AwsValidateInfrastructureTests() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -73,10 +73,10 @@ public AwsValidateInfrastructureTests() MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName), TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs index 11f34ad0bf..6242698116 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -39,9 +39,9 @@ public AwsValidateInfrastructureByArnTests() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -55,7 +55,7 @@ public AwsValidateInfrastructureByArnTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.ToValidSNSTopicName(true)); @@ -74,9 +74,9 @@ public AwsValidateInfrastructureByArnTests() FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs index e0a058fc17..dff8081d94 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -38,14 +38,14 @@ public AwsValidateInfrastructureByConventionTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(channelName!), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create); @@ -60,7 +60,7 @@ public AwsValidateInfrastructureByConventionTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call @@ -69,14 +69,14 @@ public AwsValidateInfrastructureByConventionTests() _messageProducer = new SnsMessageProducer( awsConnection, - new SnsPublication(topicAttributes:topicAttributes ) + new SnsPublication(topicAttributes: topicAttributes) { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate, - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs index 693ca776a6..48063d4da1 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -43,7 +43,7 @@ public AwsValidateInfrastructureByConventionTestsAsync() queueAttributes: new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), - topicAttributes: topicAttributes, + topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -54,7 +54,7 @@ public AwsValidateInfrastructureByConventionTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.FindTopicBy = TopicFindBy.Convention; @@ -67,10 +67,10 @@ public AwsValidateInfrastructureByConventionTestsAsync() FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs index 161d284ab9..1ed38b9ea7 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net.Mime; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTests() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); @@ -40,16 +40,16 @@ public SqsRawMessageDeliveryTests() queueAttributes: new SqsAttributes( rawMessageDelivery: false, type: SqsType.Fifo, - tags: new Dictionary { { "Environment", "Test" } }), + tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create)); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, + MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -65,7 +65,8 @@ public void When_raw_message_delivery_disabled() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index 9afe77a823..5ebc44a367 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -38,7 +38,7 @@ public SqsMessageConsumerRejectTests() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create @@ -54,14 +54,15 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + MakeChannels = OnMissingChannel.Create, + TopicAttributes = topicAttributes + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs index e4b0a59851..a6e489070c 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net; using System.Net.Mime; using System.Text.Json; @@ -80,11 +80,11 @@ public SnsReDrivePolicySDlqTests() RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -101,8 +101,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -111,10 +111,12 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_creating_a_topic_with_custom_tags_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_creating_a_topic_with_custom_tags_async.cs index 5a1cafba9d..24a060ac0c 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_creating_a_topic_with_custom_tags_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_creating_a_topic_with_custom_tags_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; @@ -51,7 +51,7 @@ public SqsMessageProducerCreateTopicWithTagsAsyncTests() _awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SnsMessageProducer( @@ -61,7 +61,7 @@ public SqsMessageProducerCreateTopicWithTagsAsyncTests() Topic = new RoutingKey(_topicName), MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs index f5e616ea86..d71a1f4953 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -34,7 +34,7 @@ public CustomisingAwsClientConfigTestsAsync() subscriptionName: new SubscriptionName(channelName), channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, - routingKey: routingKey, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); @@ -51,7 +51,7 @@ public CustomisingAwsClientConfigTestsAsync() new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("async_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -62,9 +62,12 @@ public CustomisingAwsClientConfigTestsAsync() _messageProducer = new SnsMessageProducer( publishAwsConnection, - new SnsPublication { Topic = new RoutingKey(topicName), - MakeChannels = OnMissingChannel.Create } - ); + new SnsPublication + { + Topic = new RoutingKey(topicName), + MakeChannels = OnMissingChannel.Create + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -84,7 +87,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("async_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["async_pub"]) > (0)); - + Assert.Contains("async_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["async_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs index 1dde7e9866..073ef6ff58 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -14,8 +14,9 @@ namespace Paramore.Brighter.AWS.Tests.MessagingGateway.Sns.Standard.Proactor; [Trait("Category", "AWS")] -public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable -{ private readonly Message _message; +public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable +{ + private readonly Message _message; private readonly SqsMessageConsumer _consumer; private readonly SnsMessageProducer _messageProducer; private readonly ChannelFactory _channelFactory; @@ -23,7 +24,7 @@ public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AwsAssumeInfrastructureTestsAsync() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; var correlationId = Id.Random(); var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -32,7 +33,7 @@ public AwsAssumeInfrastructureTestsAsync() var routingKey = new RoutingKey(topicName); var channelName = new ChannelName(queueName); - + SqsSubscription subscription = new( subscriptionName: new SubscriptionName(queueName), channelName: channelName, @@ -42,40 +43,40 @@ public AwsAssumeInfrastructureTestsAsync() makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); - + _message = new Message( - new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, + new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); var awsConnection = GatewayFactory.CreateFactory(); - + //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); - + //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SnsMessageProducer( - awsConnection, - new SnsPublication{Topic = routingKey, MakeChannels = OnMissingChannel.Assume} - ); + awsConnection, + new SnsPublication { Topic = routingKey, MakeChannels = OnMissingChannel.Assume }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] public async Task When_infastructure_exists_can_assume() { //arrange - await _messageProducer.SendAsync(_message); - + await _messageProducer.SendAsync(_message); + var messages = await _consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)); - + //Assert var message = messages.First(); Assert.Equal(_myCommand.Id, message.Id); @@ -83,7 +84,7 @@ public async Task When_infastructure_exists_can_assume() //clear the queue await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs index 3213747301..be952b5825 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -50,11 +50,11 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -63,10 +63,10 @@ public AwsValidateInfrastructureTestsAsync() FindTopicBy = TopicFindBy.Name, MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName) - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] @@ -83,7 +83,7 @@ public async Task When_infrastructure_exists_can_verify_async() await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs index 2ff22482e1..3262a158a0 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -52,12 +52,12 @@ public AwsValidateInfrastructureByArnTestsAsync() (AWSCredentials credentials, RegionEndpoint region) = CredentialsChain.GetAwsCredentials(); var awsConnection = GatewayFactory.CreateFactory(credentials, region); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.Value).Result; var routingKeyArn = new RoutingKey(topicArn); - + subscription.MakeChannels = OnMissingChannel.Validate; subscription.RoutingKey = routingKeyArn; subscription.FindTopicBy = TopicFindBy.Arn; @@ -70,9 +70,9 @@ public AwsValidateInfrastructureByArnTestsAsync() TopicArn = topicArn, FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs index 8f75a4f3b6..0d95d0042c 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -49,13 +49,13 @@ public AwsValidateInfrastructureByConventionTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call subscription.FindQueueBy = QueueFindBy.Name; subscription.FindTopicBy = TopicFindBy.Convention; - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -63,10 +63,10 @@ public AwsValidateInfrastructureByConventionTestsAsync() { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] @@ -83,7 +83,7 @@ public async Task When_infrastructure_exists_can_verify_async() await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs index a071c847be..975ae740bf 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; @@ -57,7 +57,7 @@ public SqsMessageProducerResourcesAreTaggedAsyncTests() _awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SnsMessageProducer( @@ -67,7 +67,7 @@ public SqsMessageProducerResourcesAreTaggedAsyncTests() Topic = new RoutingKey(_topicName), MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs index fab7c0236c..d942c25dff 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); @@ -38,7 +38,7 @@ public SqsRawMessageDeliveryTestsAsync() messagePumpType: MessagePumpType.Proactor, queueAttributes: new SqsAttributes( rawMessageDelivery: false, - tags: new Dictionary { { "Environment", "Test" } }), + tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Create, topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]))); @@ -46,7 +46,7 @@ public SqsRawMessageDeliveryTestsAsync() new SnsPublication { MakeChannels = OnMissingChannel.Create - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -84,10 +84,10 @@ public async Task When_raw_message_delivery_disabled_async() Assert.Equal(customHeaderItem.Value, messageReceived.Header.Bag[customHeaderItem.Key]); Assert.Equal(messageToSend.Body.Value, messageReceived.Body.Value); } - + public void Dispose() { - _channelFactory.DeleteTopicAsync().Wait(); + _channelFactory.DeleteTopicAsync().Wait(); _channelFactory.DeleteQueueAsync().Wait(); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 1b16155982..d39738640c 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -49,10 +49,10 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); - _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }); + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 85d06f8ce1..9b7ad09f65 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -72,10 +72,10 @@ public SnsReDrivePolicySDlqTestsAsync() Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -89,8 +89,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -98,10 +98,12 @@ public SnsReDrivePolicySDlqTestsAsync() ); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor , (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs index 1d9e282fbc..a6bcdbe840 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -33,7 +33,7 @@ public CustomisingAwsClientConfigTests() var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(channelName), channelName: new ChannelName(channelName), - routingKey: routingKey, + routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); @@ -49,7 +49,7 @@ public CustomisingAwsClientConfigTests() config.HttpClientFactory = new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sync_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -59,8 +59,11 @@ public CustomisingAwsClientConfigTests() _messageProducer = new SnsMessageProducer( publishAwsConnection, - new SnsPublication { Topic = new RoutingKey(topicName), - MakeChannels = OnMissingChannel.Create }); + new SnsPublication + { + Topic = new RoutingKey(topicName), + MakeChannels = OnMissingChannel.Create + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -79,7 +82,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("sync_sub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sync_sub"]) > (0)); - + Assert.Contains("sync_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sync_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs index 72304c61a9..b74c6b7e97 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -53,16 +53,16 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Assume }); + new SnsPublication { MakeChannels = OnMissingChannel.Assume }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs index 180f2fb00b..3b02e633a2 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -52,11 +52,11 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -65,10 +65,10 @@ public AwsValidateInfrastructureTests() FindTopicBy = TopicFindBy.Name, MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName) - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs index eb01114833..5b5bc389a9 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -55,7 +55,7 @@ public AwsValidateInfrastructureByArnTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.Value); @@ -74,9 +74,9 @@ public AwsValidateInfrastructureByArnTests() TopicArn = topicArn, FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs index 69c3669b13..7ae7351bed 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -53,20 +53,20 @@ public AwsValidateInfrastructureByConventionTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call subscription.FindQueueBy = QueueFindBy.Name; subscription.FindTopicBy = TopicFindBy.Convention; - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, - new SnsPublication { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate } - ); + new SnsPublication { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs index 043a6650da..dd9b03ff5a 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -10,7 +10,7 @@ namespace Paramore.Brighter.AWS.Tests.MessagingGateway.Sns.Standard.Reactor; -[Trait("Category", "AWS")] +[Trait("Category", "AWS")] public class SqsRawMessageDeliveryTests : IDisposable, IAsyncDisposable { private readonly SnsMessageProducer _messageProducer; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTests() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); @@ -41,11 +41,11 @@ public SqsRawMessageDeliveryTests() tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Create, topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]))); - _messageProducer = new SnsMessageProducer(awsConnection, + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create - }); + MakeChannels = OnMissingChannel.Create + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -53,11 +53,11 @@ public void When_raw_message_delivery_disabled() { //arrange var messageHeader = new MessageHeader( - Guid.NewGuid().ToString(), - _routingKey, - MessageType.MT_COMMAND, - correlationId: Guid.NewGuid().ToString(), - replyTo: RoutingKey.Empty, + Guid.NewGuid().ToString(), + _routingKey, + MessageType.MT_COMMAND, + correlationId: Guid.NewGuid().ToString(), + replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain)); var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); @@ -86,13 +86,13 @@ public void When_raw_message_delivery_disabled() public void Dispose() { - _channelFactory.DeleteTopicAsync().Wait(); + _channelFactory.DeleteTopicAsync().Wait(); _channelFactory.DeleteQueueAsync().Wait(); } - + public async ValueTask DisposeAsync() { - await _channelFactory.DeleteTopicAsync(); + await _channelFactory.DeleteTopicAsync(); await _channelFactory.DeleteQueueAsync(); } } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index 3a1198376a..c2d2b76752 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Text.Json; @@ -23,7 +23,7 @@ public class SqsMessageConsumerRejectTests : IDisposable public SqsMessageConsumerRejectTests() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; string correlationId = Guid.NewGuid().ToString(); string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -40,21 +40,21 @@ public SqsMessageConsumerRejectTests() makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); - + _message = new Message( new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); //Must have credentials stored in the SDK Credentials store or shared credentials file var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); - _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication{MakeChannels = OnMissingChannel.Create}); + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs index 1e4fee6a5b..1a3e3bc19a 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -77,12 +77,14 @@ public SnsReDrivePolicySDlqTests() _awsConnection, new SnsPublication { - Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create - } - ); + Topic = routingKey, + RequestType = typeof(MyDeferredCommand), + MakeChannels = OnMissingChannel.Create + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -99,8 +101,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -109,16 +111,18 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } private int GetDLQCount(string queueName) { - using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); + using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); var queueUrlResponse = sqsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); var response = sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest { diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs index 9ea786813c..c6e1408f7f 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -106,7 +106,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -121,7 +121,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -141,7 +141,7 @@ public IAmAMessageProducerSync CreateProducer(SnsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -156,7 +156,7 @@ public Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return Task.FromResult(producer); } @@ -174,7 +174,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( queueAttributes: new SqsAttributes(type: SqsType.Fifo) ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs index 067df48344..dcf307e1f0 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -106,7 +106,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -121,7 +121,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -141,7 +141,7 @@ public IAmAMessageProducerSync CreateProducer(SnsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -156,7 +156,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -173,7 +173,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( makeChannels: OnMissingChannel.Assume ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs index 3666f01d34..b486835ce4 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -35,14 +35,14 @@ public AwsAssumeInfrastructureTestsAsync() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -56,7 +56,7 @@ public AwsAssumeInfrastructureTestsAsync() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -64,10 +64,10 @@ public AwsAssumeInfrastructureTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume) - ); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs index 429c27e08a..962a394809 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -31,14 +31,14 @@ public AwsValidateInfrastructureTestsAsync() var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var channelName = new ChannelName(queueName); - var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); + var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, - channelType: ChannelType.PointToPoint, - queueAttributes: queueAttributes, - messagePumpType: MessagePumpType.Proactor, + channelType: ChannelType.PointToPoint, + queueAttributes: queueAttributes, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -49,7 +49,7 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.MakeChannels = OnMissingChannel.Validate; @@ -57,13 +57,13 @@ public AwsValidateInfrastructureTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: channelName, - queueAttributes: queueAttributes, - findQueueBy: QueueFindBy.Name, - makeChannels: OnMissingChannel.Validate) - ); + channelName: channelName, + queueAttributes: queueAttributes, + findQueueBy: QueueFindBy.Name, + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs index 6d2b239642..6fac2b7518 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -33,14 +33,14 @@ public AwsValidateInfrastructureByUrlTestsAsync() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.ToValidSQSQueueName(true)).Result; @@ -65,10 +65,10 @@ public AwsValidateInfrastructureByUrlTestsAsync() queueAttributes: queueAttributes, findQueueBy: QueueFindBy.Url, makeChannels: OnMissingChannel.Validate - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs index 27bf19707f..af8b8c785b 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -21,7 +21,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey(queueName); @@ -33,7 +33,7 @@ public SqsRawMessageDeliveryTestsAsync() type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var channelName = new ChannelName(queueName); - + _channel = _channelFactory.CreateAsyncChannel(new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, @@ -41,17 +41,17 @@ public SqsRawMessageDeliveryTestsAsync() routingKey: _routingKey, bufferSize: bufferSize, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) ); _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: channelName, - queueAttributes: queueAttributes, - makeChannels: OnMissingChannel.Create) - ); + channelName: channelName, + queueAttributes: queueAttributes, + makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -67,7 +67,8 @@ public async Task When_raw_message_delivery_disabled_async() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 54bab1adf3..451596b6d4 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -34,14 +34,14 @@ public SqsMessageConsumerRejectTestsAsync() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create ); @@ -53,13 +53,13 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs index cbc6c30636..13ef2a11b9 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -86,12 +86,12 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var dlqSubscription = new SqsSubscription( subscriptionName: new SubscriptionName($"DLQ-Reader-{Guid.NewGuid().ToString()}".Truncate(45)), @@ -102,7 +102,7 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTestsAsync() queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateAsyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 0565aaca88..15bdc17824 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -44,7 +44,7 @@ public SnsReDrivePolicySDlqTestsAsync() type: SqsType.Fifo, redrivePolicy: new RedrivePolicy(new ChannelName(_dlqChannelName)!, 2), tags: new Dictionary { { "Environment", "Test" } }); - + _subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -67,13 +67,13 @@ public SnsReDrivePolicySDlqTestsAsync() _sender = new SqsMessageProducer( _awsConnection, - new SqsPublication( channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) { RequestType = typeof(MyDeferredCommand), - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -87,8 +87,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -96,11 +96,11 @@ public SnsReDrivePolicySDlqTestsAsync() ); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs index fa8364a737..15bf7ab887 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -24,7 +24,7 @@ public class AwsAssumeInfrastructureTests : IDisposable, IAsyncDisposable public AwsAssumeInfrastructureTests() { _myCommand = new MyCommand { Value = "Test" }; - var replyTo = new RoutingKey("http:\\queueUrl"); + var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Id.Random(); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -35,14 +35,14 @@ public AwsAssumeInfrastructureTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -56,16 +56,16 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made subscription.MakeChannels = OnMissingChannel.Assume; _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume)); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs index 1e47757a0e..4634e9f62a 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,14 +36,14 @@ public AwsValidateInfrastructureTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -57,20 +57,20 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - + subscription.MakeChannels = OnMissingChannel.Validate; subscription.FindQueueBy = QueueFindBy.Name; _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName,queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Validate) - ); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs index afb36e024b..3a2741debb 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -21,7 +21,7 @@ public class AwsValidateInfrastructureByUrlTests : IDisposable, IAsyncDisposable private readonly ChannelFactory _channelFactory; private readonly MyCommand _myCommand; - public AwsValidateInfrastructureByUrlTests () + public AwsValidateInfrastructureByUrlTests() { var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -37,14 +37,14 @@ public AwsValidateInfrastructureByUrlTests () var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsValidateInfrastructureByUrlTests () //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.ToValidSQSQueueName(true)); @@ -70,14 +70,14 @@ public AwsValidateInfrastructureByUrlTests () _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication ( - channelName: new ChannelName(queueUrl), - queueAttributes: queueAttributes, - findQueueBy: QueueFindBy.Url, - makeChannels: OnMissingChannel.Validate) - ); - - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + new SqsPublication( + channelName: new ChannelName(queueUrl), + queueAttributes: queueAttributes, + findQueueBy: QueueFindBy.Url, + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] @@ -117,7 +117,7 @@ public async ValueTask DisposeAsync() private static string FindQueueUrl(AWSMessagingGatewayConnection connection, string queueName) { - using var snsClient = new AWSClientFactory(connection).CreateSqsClient(); + using var snsClient = new AWSClientFactory(connection).CreateSqsClient(); var topicResponse = snsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); return topicResponse.QueueUrl; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index d6f5afec8f..40855c6c88 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,16 +30,16 @@ public SqsMessageConsumerRejectTests() var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var routingKey = new RoutingKey(queueName); - var queueAttributes = new SqsAttributes(type:SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); + var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -50,12 +50,12 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs index 6dfce0c720..b6df84f5a1 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -86,12 +86,12 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var dlqSubscription = new SqsSubscription( subscriptionName: new SubscriptionName($"DLQ-Reader-{Guid.NewGuid().ToString()}".Truncate(45)), @@ -102,7 +102,7 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTests() queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs index 2afa7a1efa..e8e30dc8e7 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -45,7 +45,7 @@ public SnsReDrivePolicySDlqTests() new ChannelName(_dlqChannelName), 2), type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + _subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -68,13 +68,13 @@ public SnsReDrivePolicySDlqTests() _sender = new SqsMessageProducer( _awsConnection, new SqsPublication( - channelName: channelName, + channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); IHandleRequests handler = new MyDeferredCommandHandler(); @@ -88,8 +88,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -98,9 +98,11 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs index 8ae5d61eb0..4bf5466526 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -29,12 +29,12 @@ public CustomisingAwsClientConfigTestsAsync() var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -51,7 +51,7 @@ public CustomisingAwsClientConfigTestsAsync() new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sqs_async_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -61,8 +61,8 @@ public CustomisingAwsClientConfigTestsAsync() }); _messageProducer = new SqsMessageProducer(publishAwsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_assume_async.cs index bf56ec7814..c6dbb1d792 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -13,8 +13,8 @@ namespace Paramore.Brighter.AWS.Tests.MessagingGateway.Sqs.Standard.Proactor; [Trait("Category", "AWS")] -public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable -{ +public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable +{ private readonly Message _message; private readonly SqsMessageConsumer _consumer; private readonly SqsMessageProducer _messageProducer; @@ -23,7 +23,7 @@ public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AWSAssumeInfrastructureTestsAsync() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Guid.NewGuid().ToString(); @@ -31,39 +31,39 @@ public AWSAssumeInfrastructureTestsAsync() var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); - + _message = new Message( - new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, + new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); var awsConnection = GatewayFactory.CreateFactory(); - + //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); - + //Now change the subscription to validate, just check what we made subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channel.Name, makeChannels: OnMissingChannel.Assume) - ); + awsConnection, + new SqsPublication(channelName: channel.Name, makeChannels: OnMissingChannel.Assume), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -71,9 +71,9 @@ public async Task When_infastructure_exists_can_assume() { //arrange await _messageProducer.SendAsync(_message); - + var messages = await _consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)); - + //Assert var message = messages.First(); Assert.Equal(_myCommand.Id, message.Id); @@ -81,7 +81,7 @@ public async Task When_infastructure_exists_can_assume() //clear the queue await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs index 12b309653e..5034c0c2c6 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,19 +26,19 @@ public AwsValidateInfrastructureTestsAsync() _myCommand = new MyCommand { Value = "Test" }; var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); - var correlationId =Id.Random(); + var correlationId = Id.Random(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, + channelType: ChannelType.PointToPoint, findQueueBy: QueueFindBy.Name, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -50,17 +50,17 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Validate) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url.cs index 93fca9c390..f121139ea2 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -47,7 +47,7 @@ public AWSValidateInfrastructureByUrlTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.Value); @@ -67,12 +67,12 @@ public AWSValidateInfrastructureByUrlTests() new SqsPublication { Topic = routingKey, - ChannelName= new ChannelName(queueUrl), + ChannelName = new ChannelName(queueUrl), FindQueueBy = QueueFindBy.Url, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs index decc98896d..000f661dea 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -32,7 +32,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -50,7 +50,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.Value).Result; @@ -67,13 +67,13 @@ public AwsValidateInfrastructureByUrlTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: new ChannelName(queueUrl), + channelName: new ChannelName(queueUrl), findQueueBy: QueueFindBy.Url, - makeChannels: OnMissingChannel.Validate) - ); - + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs index fa323d48f0..e6116852cc 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_posting_a_message_resources_are_tagged_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; @@ -47,7 +47,7 @@ public SqsMessageProducerResourcesAreTaggedAsyncTests() _awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( @@ -56,7 +56,7 @@ public SqsMessageProducerResourcesAreTaggedAsyncTests() { ChannelName = channelName, MakeChannels = OnMissingChannel.Create - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index f6f0e69123..042a01d6c0 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,14 +30,14 @@ public SqsMessageConsumerRejectTestsAsync() var queueName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, + channelType: ChannelType.PointToPoint, findQueueBy: QueueFindBy.Name, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -49,14 +49,14 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName, makeChannels: OnMissingChannel.Create) - ); + awsConnection, + new SqsPublication(channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index f2f99edbf7..9bb2d5fda5 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -75,12 +75,12 @@ public SqsMessageConsumerDeliveryErrorDlqTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate async channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -91,7 +91,7 @@ public SqsMessageConsumerDeliveryErrorDlqTestsAsync() messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateAsyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 3823574f09..06d2e74032 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -32,13 +32,13 @@ public SnsReDrivePolicySDlqTestsAsync() { const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + _dlqQueueName = $"Redrive-DLQ-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); - + var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes( redrivePolicy: new RedrivePolicy(new ChannelName(_dlqQueueName), 2), @@ -53,7 +53,7 @@ public SnsReDrivePolicySDlqTestsAsync() requeueCount: -1, requeueDelay: TimeSpan.FromMilliseconds(50), messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes + queueAttributes: queueAttributes ); var myCommand = new MyDeferredCommand { Value = "Hello Redrive", GroupId = Guid.NewGuid().ToString() }; @@ -68,13 +68,13 @@ public SnsReDrivePolicySDlqTestsAsync() _sender = new SqsMessageProducer( _awsConnection, new SqsPublication( - channelName: channelName, + channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -88,8 +88,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -98,9 +98,11 @@ public SnsReDrivePolicySDlqTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs index 396a5cffa2..f4eb7e5bc4 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,7 +30,7 @@ public CustomisingAwsClientConfigTests() var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -48,7 +48,7 @@ public CustomisingAwsClientConfigTests() config.HttpClientFactory = new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sqs_sync_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -57,7 +57,7 @@ public CustomisingAwsClientConfigTests() }); _messageProducer = new SqsMessageProducer(publishAwsConnection, - new SqsPublication { ChannelName = channelName, MakeChannels = OnMissingChannel.Create }); + new SqsPublication { ChannelName = channelName, MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -76,7 +76,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("sqs_sync_sub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sqs_sync_sub"]) > (0)); - + Assert.Contains("sqs_sync_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sqs_sync_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs index 66b290d849..7a0e1cc05c 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,19 +26,19 @@ public AWSAssumeInfrastructureTests() _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -53,7 +53,7 @@ public AWSAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -61,10 +61,10 @@ public AWSAssumeInfrastructureTests() subscription.ChannelName = channel.Name; _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Assume)); + awsConnection, + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Assume), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infrastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infrastructure_exists_can_verify.cs index f7a9fe9542..f857ff8f55 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infrastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infrastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,7 +26,7 @@ public AWSValidateInfrastructureTests() _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -49,7 +49,7 @@ public AWSValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -64,12 +64,12 @@ public AWSValidateInfrastructureTests() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName:channel.Name, + channelName: channel.Name, makeChannels: OnMissingChannel.Validate - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs index 41e5ad966a..6354da6efc 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs @@ -28,7 +28,7 @@ public void When_queue_missing_verify_throws() //arrange var producer = new SqsMessageProducer( _awsConnection, - new SqsPublication(channelName: new ChannelName(_routingKey), makeChannels: OnMissingChannel.Validate)); + new SqsPublication(channelName: new ChannelName(_routingKey), makeChannels: OnMissingChannel.Validate), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act && assert Assert.Throws(() => producer.Send(new Message( diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index a254fba7be..7f7526c099 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,12 +30,12 @@ public SqsMessageConsumerRejectTests() var queueName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -50,14 +50,14 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + awsConnection, + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index 7a526c582b..16f7653701 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -75,12 +75,12 @@ public SqsMessageConsumerDeliveryErrorDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -91,7 +91,7 @@ public SqsMessageConsumerDeliveryErrorDlqTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs index 6b652ab83e..90c3cdc6c5 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -70,12 +70,12 @@ public SqsMessageConsumerNoChannelsRejectTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 1e69c18560..5985180937 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -76,12 +76,12 @@ public SqsMessageConsumerUnacceptableFallbackToDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -92,7 +92,7 @@ public SqsMessageConsumerUnacceptableFallbackToDlqTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index 3749f09023..b014765183 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -81,12 +81,12 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the invalid message queue var invalidSubscription = new SqsSubscription( @@ -97,7 +97,7 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _invalidChannelFactory = new ChannelFactory(awsConnection); + _invalidChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _invalidChannel = _invalidChannelFactory.CreateSyncChannel(invalidSubscription); // Create a separate channel to consume from the DLQ queue (to verify it stays empty) @@ -109,7 +109,7 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs index acdeb39f04..4e69b468e5 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -32,7 +32,7 @@ public SnsReDrivePolicySDlqTests() { const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + _dlqChannelName = $"Redrive-DLQ-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -78,11 +78,11 @@ public SnsReDrivePolicySDlqTests() //how do we send to the queue _sender = new SqsMessageProducer( _awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -99,8 +99,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -109,16 +109,18 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } private int GetDLQCount(string queueName) { - using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); + using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); var queueUrlResponse = sqsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); var response = sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest { diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs index 53f42d5b1a..a122ebdd70 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -43,7 +43,7 @@ public SqsMessageConsumerFactoryDlqTests() var connection = new AWSMessagingGatewayConnection( new BasicAWSCredentials("test", "test"), RegionEndpoint.EUWest1); - _factory = new SqsMessageConsumerFactory(connection); + _factory = new SqsMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs index 36a41725b2..78099efcff 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -113,7 +113,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -128,7 +128,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -148,7 +148,7 @@ public IAmAMessageProducerSync CreateProducer(SqsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -163,7 +163,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -181,7 +181,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( queueAttributes: new SqsAttributes(type: SqsType.Fifo) ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs index b572133c5d..5f06e4a222 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -110,7 +110,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -125,7 +125,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -145,7 +145,7 @@ public IAmAMessageProducerSync CreateProducer(SqsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -160,7 +160,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -177,7 +177,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( makeChannels: OnMissingChannel.Assume ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs index 6306c78fd0..7c3d93f187 100644 --- a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs +++ b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs @@ -13,13 +13,13 @@ public class S3LuggageUploadMissingParametersTests { private readonly IHttpClientFactory _httpClientFactory; private readonly string _bucketName; - + public S3LuggageUploadMissingParametersTests() { var services = new ServiceCollection(); services.AddHttpClient(); var provider = services.BuildServiceProvider(); - + _httpClientFactory = provider.GetRequiredService(); _bucketName = $"brightertestbucket-{Guid.NewGuid()}"; } @@ -28,7 +28,7 @@ public S3LuggageUploadMissingParametersTests() public void When_creating_luggagestore_missing_client() { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(null!, null!))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(null!, null!), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); @@ -40,38 +40,38 @@ public void When_creating_luggagestore_missing_client() public void When_creating_luggagestore_missing_bucketName(string? bucketName) { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName!))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName!), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] public async Task When_creating_luggagestore_bad_bucketName() { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), "A" ))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), "A"), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] public async Task When_creating_luggagestore_missing_httpClient() { //arrange var exception = await Catch.ExceptionAsync(async () => { - var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName)); + var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await store.EnsureStoreExistsAsync(); }); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] - public async Task When_creating_luggagestore_missing_ACL() + public async Task When_creating_luggagestore_missing_ACL() { //arrange var exception = await Catch.ExceptionAsync(async () => @@ -79,11 +79,11 @@ public async Task When_creating_luggagestore_missing_ACL() var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName) { HttpClientFactory = _httpClientFactory, - BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate() - }); + BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate() + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await store.EnsureStoreExistsAsync(); }); - + Assert.NotNull(exception); Assert.IsType(exception); } diff --git a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_unwrapping_a_large_message.cs index b9f40a3824..b20aefcca3 100644 --- a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_unwrapping_a_large_message.cs @@ -16,7 +16,7 @@ namespace Paramore.Brighter.AWS.Tests.Transformers; [Trait("Category", "AWS")] -public class LargeMessagePaylodUnwrapTests : IAsyncDisposable +public class LargeMessagePaylodUnwrapTests : IAsyncDisposable { private readonly TransformPipelineBuilderAsync _pipelineBuilder; private readonly AmazonS3Client _client; @@ -48,14 +48,14 @@ public LargeMessagePaylodUnwrapTests() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }] - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _luggageStore.EnsureStoreExists(); var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_uploading_luggage_to_S3.cs b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_uploading_luggage_to_S3.cs index 915825fd33..be3d8d04b3 100644 --- a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_uploading_luggage_to_S3.cs +++ b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_uploading_luggage_to_S3.cs @@ -30,7 +30,7 @@ public S3LuggageUploadTests() _httpClientFactory = provider.GetRequiredService(); _bucketName = $"brightertestbucket-{Guid.NewGuid()}"; } - + [Fact] public async Task When_uploading_luggage_to_S3() { @@ -42,10 +42,10 @@ public async Task When_uploading_luggage_to_S3() ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], RetryPolicy = GetSimpleHandlerRetryPolicy() - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + await luggageStore.EnsureStoreExistsAsync(); - + //act //Upload the test stream to S3 const string testContent = "Well, always know that you shine Brighter"; @@ -60,7 +60,7 @@ public async Task When_uploading_luggage_to_S3() //assert //do we have a claim? Assert.True((await luggageStore.HasClaimAsync(claim))); - + //check for the contents indicated by the claim id on S3 var result = await luggageStore.RetrieveAsync(claim); var resultAsString = await new StreamReader(result).ReadToEndAsync(); @@ -69,13 +69,13 @@ public async Task When_uploading_luggage_to_S3() await luggageStore.DeleteAsync(claim); } - + public static AsyncRetryPolicy GetSimpleHandlerRetryPolicy() { - var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(50), retryCount: 3, fastFirst:true); + var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(50), retryCount: 3, fastFirst: true); //TODO: Its not worth retrying malformed XML, error code: MalformedXML - + return Policy .Handle(e => { diff --git a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_validating_a_luggage_store_exists.cs b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_validating_a_luggage_store_exists.cs index 64c807714a..d2b7f3714f 100644 --- a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_validating_a_luggage_store_exists.cs +++ b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_validating_a_luggage_store_exists.cs @@ -12,8 +12,8 @@ namespace Paramore.Brighter.AWS.Tests.Transformers; -[Trait("Category", "AWS")] -public class S3LuggageStoreExistsTests +[Trait("Category", "AWS")] +public class S3LuggageStoreExistsTests { private readonly IHttpClientFactory _httpClientFactory; @@ -25,12 +25,12 @@ public S3LuggageStoreExistsTests() var provider = services.BuildServiceProvider(); _httpClientFactory = provider.GetRequiredService(); } - + [Fact] public async Task When_checking_store_that_exists() { var bucketName = $"brightertestbucket-{Guid.NewGuid()}"; - + //arrange var luggageStore = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName) { @@ -38,8 +38,8 @@ public async Task When_checking_store_that_exists() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + await luggageStore.EnsureStoreExistsAsync(); //allow bucket endpoint to come into existence @@ -49,39 +49,39 @@ public async Task When_checking_store_that_exists() luggageStore = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName) { Strategy = StorageStrategy.Validate, - HttpClientFactory = _httpClientFactory, + HttpClientFactory = _httpClientFactory, BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); Assert.NotNull(luggageStore); - + //teardown var factory = new AWSClientFactory(GatewayFactory.CreateFactory()); var client = factory.CreateS3Client(); await client.DeleteBucketAsync(bucketName); } - + [Fact] public async Task When_checking_store_that_does_not_exist() { //act - var doesNotExist = await Catch.ExceptionAsync(async () => - { - var luggageStore = new S3LuggageStore( - new S3LuggageOptions(GatewayFactory.CreateS3Connection(), $"brightertestbucket-{Guid.NewGuid()}") - { - Strategy = StorageStrategy.Validate, - HttpClientFactory = _httpClientFactory, - BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), - ACLs = S3CannedACL.Private, - Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); + var doesNotExist = await Catch.ExceptionAsync(async () => + { + var luggageStore = new S3LuggageStore( + new S3LuggageOptions(GatewayFactory.CreateS3Connection(), $"brightertestbucket-{Guid.NewGuid()}") + { + Strategy = StorageStrategy.Validate, + HttpClientFactory = _httpClientFactory, + BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), + ACLs = S3CannedACL.Private, + Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + + await luggageStore.EnsureStoreExistsAsync(); + }); - await luggageStore.EnsureStoreExistsAsync(); - }); - - Assert.NotNull(doesNotExist); - Assert.True(doesNotExist is InvalidOperationException); + Assert.NotNull(doesNotExist); + Assert.True(doesNotExist is InvalidOperationException); } } diff --git a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_wrapping_a_large_message.cs index 88fdc1f76d..bd9d1e2e73 100644 --- a/tests/Paramore.Brighter.AWS.Tests/Transformers/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.AWS.Tests/Transformers/When_wrapping_a_large_message.cs @@ -15,7 +15,7 @@ namespace Paramore.Brighter.AWS.Tests.Transformers; [Trait("Category", "AWS")] -public class LargeMessagePayloadWrapTests : IAsyncDisposable +public class LargeMessagePayloadWrapTests : IAsyncDisposable { private string? _id; private WrapPipelineAsync? _transformPipeline; @@ -31,14 +31,14 @@ public LargeMessagePayloadWrapTests() { //arrange TransformPipelineBuilderAsync.ClearPipelineCache(); - + var mapperRegistry = new MessageMapperRegistry(null, new SimpleMessageMapperFactoryAsync( _ => new MyLargeCommandMessageMapperAsync()) ); - + mapperRegistry.RegisterAsync(); - + _myCommand = new MyLargeCommand(6000); var factory = new AWSClientFactory(GatewayFactory.CreateFactory()); @@ -57,15 +57,15 @@ public LargeMessagePayloadWrapTests() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _luggageStore.EnsureStoreExists(); var transformerFactoryAsync = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } [Fact] @@ -80,18 +80,18 @@ public async Task When_wrapping_a_large_message() Assert.NotNull(message.Header.DataRef); _id = (string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK]; Assert.Equal($"Claim Check {_id}", message.Body.Value); - + Assert.True(await _luggageStore.HasClaimAsync(_id)); } public async ValueTask DisposeAsync() { - //We have to empty objects from a bucket before deleting it - if (_id != null) - { - await _luggageStore.DeleteAsync(_id); - } + //We have to empty objects from a bucket before deleting it + if (_id != null) + { + await _luggageStore.DeleteAsync(_id); + } - await _client.DeleteBucketAsync(_bucketName); + await _client.DeleteBucketAsync(_bucketName); } } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs index 887ed2a737..073924d0b1 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -54,16 +54,16 @@ public AwsAssumeInfrastructureTestsAsync() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Assume, TopicAttributes = topicAttributes }); + new SnsPublication { MakeChannels = OnMissingChannel.Assume, TopicAttributes = topicAttributes }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs index 16e7a84224..96a3846fbf 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -25,7 +25,7 @@ public class AwsValidateInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AwsValidateInfrastructureTestsAsync() { _myCommand = new MyCommand { Value = "Test" }; - var replyTo = new RoutingKey("http:\\queueUrl"); + var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Id.Random(); var channelName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,9 +39,9 @@ public AwsValidateInfrastructureTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -52,7 +52,7 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -66,10 +66,10 @@ public AwsValidateInfrastructureTestsAsync() MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName), TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs index 6d0e0d1985..cafe1ea98c 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -38,9 +38,9 @@ public AwsValidateInfrastructureByArnTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public AwsValidateInfrastructureByArnTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.ToValidSNSTopicName(true)).Result; @@ -70,9 +70,9 @@ public AwsValidateInfrastructureByArnTestsAsync() FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs index d838eeb249..526ce77013 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net.Mime; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); @@ -36,17 +36,17 @@ public SqsRawMessageDeliveryTestsAsync() channelType: ChannelType.PubSub, routingKey: _routingKey, bufferSize: bufferSize, - queueAttributes:new SqsAttributes(rawMessageDelivery: false, type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(rawMessageDelivery: false, type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create)); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, - Topic = _routingKey, + MakeChannels = OnMissingChannel.Create, + Topic = _routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -62,7 +62,8 @@ public async Task When_raw_message_delivery_disabled_async() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index bd2f33144b..a157b6d4f7 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -26,7 +26,7 @@ public SqsMessageConsumerRejectTestsAsync() _myCommand = new MyCommand { Value = "Test" }; var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); - var correlationId =Id.Random(); + var correlationId = Id.Random(); var channelName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var topicName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -38,9 +38,9 @@ public SqsMessageConsumerRejectTestsAsync() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), - topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Proactor, + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + topicAttributes: topicAttributes, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SnsMessageProducer(awsConnection, @@ -60,7 +60,7 @@ public SqsMessageConsumerRejectTestsAsync() MakeChannels = OnMissingChannel.Create, Topic = routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs index a5b7c1bbea..f64481037e 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net; @@ -72,11 +72,11 @@ public SnsReDrivePolicySDlqTestsAsync() Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create, - TopicAttributes = topicAttributes - } - ); + TopicAttributes = topicAttributes + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -90,8 +90,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -100,10 +100,10 @@ public SnsReDrivePolicySDlqTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_topic_missing_verify_throws_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_topic_missing_verify_throws_async.cs index 466ee29c79..b5b68508ed 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_topic_missing_verify_throws_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Proactor/When_topic_missing_verify_throws_async.cs @@ -33,7 +33,7 @@ public async Task When_topic_missing_verify_throws_async() { MakeChannels = OnMissingChannel.Validate, TopicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]) - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs index e73ad84547..1401263be6 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,15 +36,15 @@ public AwsAssumeInfrastructureTests() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -66,7 +66,7 @@ public AwsAssumeInfrastructureTests() subscriptionName: new SubscriptionName(queueName), channelName: channelName, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Assume); @@ -74,12 +74,12 @@ public AwsAssumeInfrastructureTests() _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Assume, + MakeChannels = OnMissingChannel.Assume, Topic = routingKey, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs index d12331a5b3..9d9b25453f 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,15 +36,15 @@ public AwsValidateInfrastructureTests() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -73,10 +73,10 @@ public AwsValidateInfrastructureTests() MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName), TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs index 932f6f6635..c07ce8e2f5 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_arn.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -39,9 +39,9 @@ public AwsValidateInfrastructureByArnTests() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -55,7 +55,7 @@ public AwsValidateInfrastructureByArnTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.ToValidSNSTopicName(true)); @@ -74,9 +74,9 @@ public AwsValidateInfrastructureByArnTests() FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs index bb8145d181..0d4e709d26 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -38,14 +38,14 @@ public AwsValidateInfrastructureByConventionTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(channelName!), channelName: channelName, channelType: ChannelType.PubSub, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create); @@ -60,7 +60,7 @@ public AwsValidateInfrastructureByConventionTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call @@ -69,14 +69,14 @@ public AwsValidateInfrastructureByConventionTests() _messageProducer = new SnsMessageProducer( awsConnection, - new SnsPublication(topicAttributes:topicAttributes ) + new SnsPublication(topicAttributes: topicAttributes) { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate, - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs index ab8c8f1b58..3b88e4fe3e 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_infrastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -43,7 +43,7 @@ public AwsValidateInfrastructureByConventionTestsAsync() queueAttributes: new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), - topicAttributes: topicAttributes, + topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -54,7 +54,7 @@ public AwsValidateInfrastructureByConventionTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.FindTopicBy = TopicFindBy.Convention; @@ -67,10 +67,10 @@ public AwsValidateInfrastructureByConventionTestsAsync() FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate, TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs index 3ed9b3952d..6a9a2b36fa 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_raw_message_delivery_disabled.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; using System.Net.Mime; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTests() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); var topicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]); @@ -40,16 +40,16 @@ public SqsRawMessageDeliveryTests() queueAttributes: new SqsAttributes( rawMessageDelivery: false, type: SqsType.Fifo, - tags: new Dictionary { { "Environment", "Test" } }), + tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create)); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, + MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -65,7 +65,8 @@ public void When_raw_message_delivery_disabled() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index e3e8f80e0a..a8a41c46f9 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -38,7 +38,7 @@ public SqsMessageConsumerRejectTests() channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, + messagePumpType: MessagePumpType.Reactor, queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: topicAttributes, makeChannels: OnMissingChannel.Create @@ -54,14 +54,15 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - }); + MakeChannels = OnMissingChannel.Create, + TopicAttributes = topicAttributes + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs index e2a3510962..334da79554 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net; using System.Net.Mime; using System.Text.Json; @@ -80,11 +80,11 @@ public SnsReDrivePolicySDlqTests() RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create, TopicAttributes = topicAttributes - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -101,8 +101,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -112,9 +112,11 @@ public SnsReDrivePolicySDlqTests() //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - null, new InMemoryRequestContextFactory(), _channel) + null, new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_topic_missing_verify_throws.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_topic_missing_verify_throws.cs index 067fc3aa91..a70de3d3c3 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_topic_missing_verify_throws.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Fifo/Reactor/When_topic_missing_verify_throws.cs @@ -31,7 +31,7 @@ public void When_topic_missing_verify_throws() { MakeChannels = OnMissingChannel.Validate, TopicAttributes = new SnsAttributes(type: SqsType.Fifo, tags: [new Tag { Key = "Environment", Value = "Test" }]) - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs index 8063220d2c..532aba2c67 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_customising_aws_client_config_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -34,7 +34,7 @@ public CustomisingAwsClientConfigTestsAsync() subscriptionName: new SubscriptionName(channelName), channelName: new ChannelName(channelName), channelType: ChannelType.PubSub, - routingKey: routingKey, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); @@ -51,7 +51,7 @@ public CustomisingAwsClientConfigTestsAsync() new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("async_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -62,9 +62,12 @@ public CustomisingAwsClientConfigTestsAsync() _messageProducer = new SnsMessageProducer( publishAwsConnection, - new SnsPublication { Topic = new RoutingKey(topicName), - MakeChannels = OnMissingChannel.Create } - ); + new SnsPublication + { + Topic = new RoutingKey(topicName), + MakeChannels = OnMissingChannel.Create + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -84,7 +87,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("async_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["async_pub"]) > (0)); - + Assert.Contains("async_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["async_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs index 1eef276308..c06695f4c8 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -14,8 +14,9 @@ namespace Paramore.Brighter.AWS.V4.Tests.MessagingGateway.Sns.Standard.Proactor; [Trait("Category", "AWS")] -public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable -{ private readonly Message _message; +public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable +{ + private readonly Message _message; private readonly SqsMessageConsumer _consumer; private readonly SnsMessageProducer _messageProducer; private readonly ChannelFactory _channelFactory; @@ -23,7 +24,7 @@ public class AwsAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AwsAssumeInfrastructureTestsAsync() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; var correlationId = Id.Random(); var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -32,7 +33,7 @@ public AwsAssumeInfrastructureTestsAsync() var routingKey = new RoutingKey(topicName); var channelName = new ChannelName(queueName); - + SqsSubscription subscription = new( subscriptionName: new SubscriptionName(queueName), channelName: channelName, @@ -42,40 +43,40 @@ public AwsAssumeInfrastructureTestsAsync() makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); - + _message = new Message( - new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, + new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); var awsConnection = GatewayFactory.CreateFactory(); - + //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); - + //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SnsMessageProducer( - awsConnection, - new SnsPublication{Topic = routingKey, MakeChannels = OnMissingChannel.Assume} - ); + awsConnection, + new SnsPublication { Topic = routingKey, MakeChannels = OnMissingChannel.Assume }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] public async Task When_infastructure_exists_can_assume() { //arrange - await _messageProducer.SendAsync(_message); - + await _messageProducer.SendAsync(_message); + var messages = await _consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)); - + //Assert var message = messages.First(); Assert.Equal(_myCommand.Id, message.Id); @@ -83,7 +84,7 @@ public async Task When_infastructure_exists_can_assume() //clear the queue await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs index 54c1b2ab2e..e5893b13c2 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -50,11 +50,11 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -63,10 +63,10 @@ public AwsValidateInfrastructureTestsAsync() FindTopicBy = TopicFindBy.Name, MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName) - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] @@ -83,7 +83,7 @@ public async Task When_infrastructure_exists_can_verify_async() await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs index 3bca81d33d..1f3c439f6c 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_arn_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -52,12 +52,12 @@ public AwsValidateInfrastructureByArnTestsAsync() (AWSCredentials credentials, RegionEndpoint region) = CredentialsChain.GetAwsCredentials(); var awsConnection = GatewayFactory.CreateFactory(credentials, region); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.Value).Result; var routingKeyArn = new RoutingKey(topicArn); - + subscription.MakeChannels = OnMissingChannel.Validate; subscription.RoutingKey = routingKeyArn; subscription.FindTopicBy = TopicFindBy.Arn; @@ -70,9 +70,9 @@ public AwsValidateInfrastructureByArnTestsAsync() TopicArn = topicArn, FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs index 0a53861b7b..7b8135ac56 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_infrastructure_exists_can_verify_by_convention_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -49,13 +49,13 @@ public AwsValidateInfrastructureByConventionTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call subscription.FindQueueBy = QueueFindBy.Name; subscription.FindTopicBy = TopicFindBy.Convention; - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -63,10 +63,10 @@ public AwsValidateInfrastructureByConventionTestsAsync() { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] @@ -83,7 +83,7 @@ public async Task When_infrastructure_exists_can_verify_async() await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs index ce9dd23838..49f080b70a 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); @@ -38,7 +38,7 @@ public SqsRawMessageDeliveryTestsAsync() messagePumpType: MessagePumpType.Proactor, queueAttributes: new SqsAttributes( rawMessageDelivery: false, - tags: new Dictionary { { "Environment", "Test" } }), + tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Create, topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]))); @@ -46,7 +46,7 @@ public SqsRawMessageDeliveryTestsAsync() new SnsPublication { MakeChannels = OnMissingChannel.Create - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -84,10 +84,10 @@ public async Task When_raw_message_delivery_disabled_async() Assert.Equal(customHeaderItem.Value, messageReceived.Header.Bag[customHeaderItem.Key]); Assert.Equal(messageToSend.Body.Value, messageReceived.Body.Value); } - + public void Dispose() { - _channelFactory.DeleteTopicAsync().Wait(); + _channelFactory.DeleteTopicAsync().Wait(); _channelFactory.DeleteQueueAsync().Wait(); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 7212a3ef5d..d89a86cefc 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -49,10 +49,10 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); - _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }); + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 2a8a704542..f0ad8da58b 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -72,10 +72,10 @@ public SnsReDrivePolicySDlqTestsAsync() Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -89,8 +89,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -99,9 +99,11 @@ public SnsReDrivePolicySDlqTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_topic_missing_verify_throws_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_topic_missing_verify_throws_async.cs index 468fb32603..0cd9c11263 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_topic_missing_verify_throws_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Proactor/When_topic_missing_verify_throws_async.cs @@ -7,7 +7,7 @@ namespace Paramore.Brighter.AWS.V4.Tests.MessagingGateway.Sns.Standard.Proactor; [Trait("Category", "AWS")] -public class AwsValidateMissingTopicTestsAsync +public class AwsValidateMissingTopicTestsAsync { private readonly AWSMessagingGatewayConnection _awsConnection; private readonly RoutingKey _routingKey; @@ -30,10 +30,10 @@ public async Task When_topic_missing_verify_throws_async() new SnsPublication { MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // act & assert - await Assert.ThrowsAsync(async () => + await Assert.ThrowsAsync(async () => await producer.SendAsync(new Message( new MessageHeader("", _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("plain/text")), new MessageBody("Test")))); diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs index ea2a7116a2..0d1df3ff00 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_customising_aws_client_config.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -33,7 +33,7 @@ public CustomisingAwsClientConfigTests() var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(channelName), channelName: new ChannelName(channelName), - routingKey: routingKey, + routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }), topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }])); @@ -49,7 +49,7 @@ public CustomisingAwsClientConfigTests() config.HttpClientFactory = new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sync_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -59,8 +59,11 @@ public CustomisingAwsClientConfigTests() _messageProducer = new SnsMessageProducer( publishAwsConnection, - new SnsPublication { Topic = new RoutingKey(topicName), - MakeChannels = OnMissingChannel.Create }); + new SnsPublication + { + Topic = new RoutingKey(topicName), + MakeChannels = OnMissingChannel.Create + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -79,7 +82,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("sync_sub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sync_sub"]) > (0)); - + Assert.Contains("sync_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sync_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs index a2c44ac4e7..cc4f4af308 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -53,16 +53,16 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to assume that it exists subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Assume }); + new SnsPublication { MakeChannels = OnMissingChannel.Assume }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs index 3d78c8c794..629a63b344 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -52,11 +52,11 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, @@ -65,10 +65,10 @@ public AwsValidateInfrastructureTests() FindTopicBy = TopicFindBy.Name, MakeChannels = OnMissingChannel.Validate, Topic = new RoutingKey(topicName) - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs index e5246ed530..7dc4dd9781 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_arn.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -55,7 +55,7 @@ public AwsValidateInfrastructureByArnTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var topicArn = FindTopicArn(awsConnection, routingKey.Value); @@ -74,9 +74,9 @@ public AwsValidateInfrastructureByArnTests() TopicArn = topicArn, FindTopicBy = TopicFindBy.Arn, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs index ab5e3cc3b8..cfa5daf0eb 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_infastructure_exists_can_verify_by_convention.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -53,20 +53,20 @@ public AwsValidateInfrastructureByConventionTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - will make the SNS Arn to prevent ListTopics call subscription.FindQueueBy = QueueFindBy.Name; subscription.FindTopicBy = TopicFindBy.Convention; - subscription.MakeChannels = OnMissingChannel.Validate; + subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SnsMessageProducer( awsConnection, - new SnsPublication { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate } - ); + new SnsPublication { FindTopicBy = TopicFindBy.Convention, MakeChannels = OnMissingChannel.Validate }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs index 0e7968e4a0..35ad6ab468 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_raw_message_delivery_disabled.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -10,7 +10,7 @@ namespace Paramore.Brighter.AWS.V4.Tests.MessagingGateway.Sns.Standard.Reactor; -[Trait("Category", "AWS")] +[Trait("Category", "AWS")] public class SqsRawMessageDeliveryTests : IDisposable, IAsyncDisposable { private readonly SnsMessageProducer _messageProducer; @@ -22,7 +22,7 @@ public SqsRawMessageDeliveryTests() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey($"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45)); @@ -41,11 +41,11 @@ public SqsRawMessageDeliveryTests() tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Create, topicAttributes: new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]))); - _messageProducer = new SnsMessageProducer(awsConnection, + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { - MakeChannels = OnMissingChannel.Create - }); + MakeChannels = OnMissingChannel.Create + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -53,11 +53,11 @@ public void When_raw_message_delivery_disabled() { //arrange var messageHeader = new MessageHeader( - Guid.NewGuid().ToString(), - _routingKey, - MessageType.MT_COMMAND, - correlationId: Guid.NewGuid().ToString(), - replyTo: RoutingKey.Empty, + Guid.NewGuid().ToString(), + _routingKey, + MessageType.MT_COMMAND, + correlationId: Guid.NewGuid().ToString(), + replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain)); var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); @@ -86,13 +86,13 @@ public void When_raw_message_delivery_disabled() public void Dispose() { - _channelFactory.DeleteTopicAsync().Wait(); + _channelFactory.DeleteTopicAsync().Wait(); _channelFactory.DeleteQueueAsync().Wait(); } - + public async ValueTask DisposeAsync() { - await _channelFactory.DeleteTopicAsync(); + await _channelFactory.DeleteTopicAsync(); await _channelFactory.DeleteQueueAsync(); } } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index c95f0f76a0..0ccdeae251 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -23,7 +23,7 @@ public class SqsMessageConsumerRejectTests : IDisposable public SqsMessageConsumerRejectTests() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; string correlationId = Guid.NewGuid().ToString(); string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -44,17 +44,17 @@ public SqsMessageConsumerRejectTests() _message = new Message( new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); //Must have credentials stored in the SDK Credentials store or shared credentials file var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); - _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication{MakeChannels = OnMissingChannel.Create}); + _messageProducer = new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs index 7ceb3c389c..7ee3723f06 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -77,12 +77,14 @@ public SnsReDrivePolicySDlqTests() _awsConnection, new SnsPublication { - Topic = routingKey, RequestType = typeof(MyDeferredCommand), MakeChannels = OnMissingChannel.Create - } - ); + Topic = routingKey, + RequestType = typeof(MyDeferredCommand), + MakeChannels = OnMissingChannel.Create + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -99,8 +101,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -109,16 +111,18 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } private int GetDLQCount(string queueName) { - using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); + using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); var queueUrlResponse = sqsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); var response = sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest { diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_topic_missing_verify_throws.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_topic_missing_verify_throws.cs index c335ee196f..e4558f142e 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_topic_missing_verify_throws.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sns/Standard/Reactor/When_topic_missing_verify_throws.cs @@ -29,7 +29,7 @@ public void When_topic_missing_verify_throws() new SnsPublication { MakeChannels = OnMissingChannel.Validate, - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act && assert Assert.Throws(() => producer.Send(new Message( diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs index c1831138ad..bcd20fe130 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsFifoMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -111,7 +111,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -126,7 +126,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -146,7 +146,7 @@ public IAmAMessageProducerSync CreateProducer(SnsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -161,7 +161,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -179,7 +179,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( queueAttributes: new SqsAttributes(type: SqsType.Fifo) ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs index 18da11d3ac..02837dc844 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SnsStandardMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -106,7 +106,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -121,7 +121,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -141,7 +141,7 @@ public IAmAMessageProducerSync CreateProducer(SnsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -156,7 +156,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SnsMessageProducer(connection, publication); + var producer = new SnsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -173,7 +173,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( makeChannels: OnMissingChannel.Assume ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs index 7e1f9bf24e..3975092b0d 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -35,14 +35,14 @@ public AwsAssumeInfrastructureTestsAsync() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -56,7 +56,7 @@ public AwsAssumeInfrastructureTestsAsync() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -64,10 +64,10 @@ public AwsAssumeInfrastructureTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume) - ); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs index a60a1b1ea8..2ed7681c8b 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -31,14 +31,14 @@ public AwsValidateInfrastructureTestsAsync() var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var channelName = new ChannelName(queueName); - var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); + var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, - channelType: ChannelType.PointToPoint, - queueAttributes: queueAttributes, - messagePumpType: MessagePumpType.Proactor, + channelType: ChannelType.PointToPoint, + queueAttributes: queueAttributes, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -49,7 +49,7 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.MakeChannels = OnMissingChannel.Validate; @@ -57,13 +57,13 @@ public AwsValidateInfrastructureTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: channelName, - queueAttributes: queueAttributes, - findQueueBy: QueueFindBy.Name, - makeChannels: OnMissingChannel.Validate) - ); + channelName: channelName, + queueAttributes: queueAttributes, + findQueueBy: QueueFindBy.Name, + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs index 57fd7a2123..8805772e29 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -33,14 +33,14 @@ public AwsValidateInfrastructureByUrlTestsAsync() var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -51,7 +51,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.ToValidSQSQueueName(true)).Result; @@ -65,10 +65,10 @@ public AwsValidateInfrastructureByUrlTestsAsync() queueAttributes: queueAttributes, findQueueBy: QueueFindBy.Url, makeChannels: OnMissingChannel.Validate - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs index 5eac866f42..84ba21671a 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_raw_message_delivery_disabled_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net.Mime; using System.Threading.Tasks; @@ -21,7 +21,7 @@ public SqsRawMessageDeliveryTestsAsync() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = $"Raw-Msg-Delivery-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey(queueName); @@ -33,7 +33,7 @@ public SqsRawMessageDeliveryTestsAsync() type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var channelName = new ChannelName(queueName); - + _channel = _channelFactory.CreateAsyncChannel(new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, @@ -41,17 +41,17 @@ public SqsRawMessageDeliveryTestsAsync() routingKey: _routingKey, bufferSize: bufferSize, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) ); _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: channelName, - queueAttributes: queueAttributes, - makeChannels: OnMissingChannel.Create) - ); + channelName: channelName, + queueAttributes: queueAttributes, + makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -67,7 +67,8 @@ public async Task When_raw_message_delivery_disabled_async() correlationId: Guid.NewGuid().ToString(), replyTo: RoutingKey.Empty, contentType: new ContentType(MediaTypeNames.Text.Plain), - partitionKey: messageGroupId) { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; + partitionKey: messageGroupId) + { Bag = { [HeaderNames.DeduplicationId] = deduplicationId } }; var customHeaderItem = new KeyValuePair("custom-header-item", "custom-header-item-value"); messageHeader.Bag.Add(customHeaderItem.Key, customHeaderItem.Value); diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 452da90166..39c6f57e0f 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -34,14 +34,14 @@ public SqsMessageConsumerRejectTestsAsync() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create ); @@ -53,13 +53,13 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs index 302b21f2f0..710f725304 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq_async.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -86,12 +86,12 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var dlqSubscription = new SqsSubscription( subscriptionName: new SubscriptionName($"DLQ-Reader-{Guid.NewGuid().ToString()}".Truncate(45)), @@ -102,7 +102,7 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTestsAsync() queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateAsyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 1f0170cdc3..32c7d0906f 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -44,7 +44,7 @@ public SnsReDrivePolicySDlqTestsAsync() type: SqsType.Fifo, redrivePolicy: new RedrivePolicy(new ChannelName(_dlqChannelName)!, 2), tags: new Dictionary { { "Environment", "Test" } }); - + _subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -67,13 +67,13 @@ public SnsReDrivePolicySDlqTestsAsync() _sender = new SqsMessageProducer( _awsConnection, - new SqsPublication( channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create) { RequestType = typeof(MyDeferredCommand), - } - ); + }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -87,8 +87,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -97,10 +97,10 @@ public SnsReDrivePolicySDlqTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_topic_missing_verify_throws_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_topic_missing_verify_throws_async.cs index af8f1bc651..c96ff3a934 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_topic_missing_verify_throws_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Proactor/When_topic_missing_verify_throws_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Amazon.SQS.Model; using Paramore.Brighter.AWS.V4.Tests.Helpers; @@ -16,7 +16,7 @@ public class AwsValidateMissingTopicTestsAsync private readonly ChannelName _channelName; public AwsValidateMissingTopicTestsAsync() - { + { var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _channelName = new ChannelName(queueName); _routingKey = new RoutingKey(_channelName); @@ -35,7 +35,7 @@ public async Task When_queue_missing_verify_throws_async() channelName: new ChannelName(_channelName!), queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Validate - )); + ), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs index 9a63ff01c6..fa02812626 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -24,7 +24,7 @@ public class AwsAssumeInfrastructureTests : IDisposable, IAsyncDisposable public AwsAssumeInfrastructureTests() { _myCommand = new MyCommand { Value = "Test" }; - var replyTo = new RoutingKey("http:\\queueUrl"); + var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Id.Random(); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -35,14 +35,14 @@ public AwsAssumeInfrastructureTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -56,16 +56,16 @@ public AwsAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made subscription.MakeChannels = OnMissingChannel.Assume; _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume)); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Assume), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true)); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(true), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs index d17b7474be..ae0fb564f4 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -36,14 +36,14 @@ public AwsValidateInfrastructureTests() var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, channelType: ChannelType.PointToPoint, routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -57,20 +57,20 @@ public AwsValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made - + subscription.MakeChannels = OnMissingChannel.Validate; subscription.FindQueueBy = QueueFindBy.Name; _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName,queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Validate) - ); + new SqsPublication(channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs index 6113440d23..f920e6c9bf 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_infastructure_exists_can_verify_by_url.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -21,7 +21,7 @@ public class AwsValidateInfrastructureByUrlTests : IDisposable, IAsyncDisposable private readonly ChannelFactory _channelFactory; private readonly MyCommand _myCommand; - public AwsValidateInfrastructureByUrlTests () + public AwsValidateInfrastructureByUrlTests() { var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); @@ -37,14 +37,14 @@ public AwsValidateInfrastructureByUrlTests () var queueAttributes = new SqsAttributes( type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -58,7 +58,7 @@ public AwsValidateInfrastructureByUrlTests () //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.ToValidSQSQueueName(true)); @@ -70,14 +70,14 @@ public AwsValidateInfrastructureByUrlTests () _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication ( - channelName: new ChannelName(queueUrl), - queueAttributes: queueAttributes, - findQueueBy: QueueFindBy.Url, - makeChannels: OnMissingChannel.Validate) - ); - - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + new SqsPublication( + channelName: new ChannelName(queueUrl), + queueAttributes: queueAttributes, + findQueueBy: QueueFindBy.Url, + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] @@ -117,7 +117,7 @@ public async ValueTask DisposeAsync() private static string FindQueueUrl(AWSMessagingGatewayConnection connection, string queueName) { - using var snsClient = new AWSClientFactory(connection).CreateSqsClient(); + using var snsClient = new AWSClientFactory(connection).CreateSqsClient(); var topicResponse = snsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); return topicResponse.QueueUrl; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index 819e845fc9..3cd5767b73 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,16 +30,16 @@ public SqsMessageConsumerRejectTests() var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; var routingKey = new RoutingKey(queueName); - var queueAttributes = new SqsAttributes(type:SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); + var queueAttributes = new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(queueName), channelName: channelName, channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, - queueAttributes: queueAttributes, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, + queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); _message = new Message( @@ -50,12 +50,12 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs index db3c8811df..5c01e82306 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_rejecting_fifo_message_with_delivery_error_should_send_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -86,12 +86,12 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create, queueAttributes: queueAttributes), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var dlqSubscription = new SqsSubscription( subscriptionName: new SubscriptionName($"DLQ-Reader-{Guid.NewGuid().ToString()}".Truncate(45)), @@ -102,7 +102,7 @@ public SqsMessageConsumerFifoDeliveryErrorDlqTests() queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs index 72dbb5b881..183d75f0c3 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -45,7 +45,7 @@ public SnsReDrivePolicySDlqTests() new ChannelName(_dlqChannelName), 2), type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }); - + _subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -68,13 +68,13 @@ public SnsReDrivePolicySDlqTests() _sender = new SqsMessageProducer( _awsConnection, new SqsPublication( - channelName: channelName, + channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); IHandleRequests handler = new MyDeferredCommandHandler(); @@ -88,8 +88,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -98,9 +98,11 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_topic_missing_verify_throws.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_topic_missing_verify_throws.cs index 22e4bcf28e..cb7b88052e 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_topic_missing_verify_throws.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Fifo/Reactor/When_topic_missing_verify_throws.cs @@ -30,11 +30,11 @@ public void When_channel_missing_verify_throws() var producer = new SqsMessageProducer( _awsConnection, new SqsPublication( - channelName: new ChannelName(Guid.NewGuid().ToString()), - queueAttributes: new SqsAttributes (type:SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), + channelName: new ChannelName(Guid.NewGuid().ToString()), + queueAttributes: new SqsAttributes(type: SqsType.Fifo, tags: new Dictionary { { "Environment", "Test" } }), makeChannels: OnMissingChannel.Validate - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageGroupId = $"MessageGroup{Guid.NewGuid():N}"; diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs index 56a030fe07..26d6dacf67 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_customising_aws_client_config_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -29,12 +29,12 @@ public CustomisingAwsClientConfigTestsAsync() var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -51,7 +51,7 @@ public CustomisingAwsClientConfigTestsAsync() new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sqs_async_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -61,8 +61,8 @@ public CustomisingAwsClientConfigTestsAsync() }); _messageProducer = new SqsMessageProducer(publishAwsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_assume_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_assume_async.cs index a1b6db9ed9..1b51b2f03d 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_assume_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_assume_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -13,8 +13,8 @@ namespace Paramore.Brighter.AWS.V4.Tests.MessagingGateway.Sqs.Standard.Proactor; [Trait("Category", "AWS")] -public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable -{ +public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable +{ private readonly Message _message; private readonly SqsMessageConsumer _consumer; private readonly SqsMessageProducer _messageProducer; @@ -23,7 +23,7 @@ public class AWSAssumeInfrastructureTestsAsync : IDisposable, IAsyncDisposable public AWSAssumeInfrastructureTestsAsync() { - _myCommand = new MyCommand{Value = "Test"}; + _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); var correlationId = Guid.NewGuid().ToString(); @@ -31,39 +31,39 @@ public AWSAssumeInfrastructureTestsAsync() var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); - + _message = new Message( - new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, + new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, correlationId: correlationId, replyTo: new RoutingKey(replyTo), contentType: contentType), - new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options)) + new MessageBody(JsonSerializer.Serialize((object)_myCommand, JsonSerialisationOptions.Options)) ); var awsConnection = GatewayFactory.CreateFactory(); - + //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); - + //Now change the subscription to validate, just check what we made subscription.MakeChannels = OnMissingChannel.Assume; - + _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channel.Name, makeChannels: OnMissingChannel.Assume) - ); + awsConnection, + new SqsPublication(channelName: channel.Name, makeChannels: OnMissingChannel.Assume), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName()); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -71,9 +71,9 @@ public async Task When_infastructure_exists_can_assume() { //arrange await _messageProducer.SendAsync(_message); - + var messages = await _consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)); - + //Assert var message = messages.First(); Assert.Equal(_myCommand.Id, message.Id); @@ -81,7 +81,7 @@ public async Task When_infastructure_exists_can_assume() //clear the queue await _consumer.AcknowledgeAsync(message); } - + public void Dispose() { //Clean up resources that we have created diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_verify_by_url.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_verify_by_url.cs index 4571cdb8d2..9c82f3980a 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_verify_by_url.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infastructure_exists_can_verify_by_url.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -47,7 +47,7 @@ public AWSValidateInfrastructureByUrlTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.Value); @@ -67,12 +67,12 @@ public AWSValidateInfrastructureByUrlTests() new SqsPublication { Topic = routingKey, - ChannelName= new ChannelName(queueUrl), + ChannelName = new ChannelName(queueUrl), FindQueueBy = QueueFindBy.Url, MakeChannels = OnMissingChannel.Validate - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs index 79ab2f2cea..184d2d014d 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,19 +26,19 @@ public AwsValidateInfrastructureTestsAsync() _myCommand = new MyCommand { Value = "Test" }; var replyTo = new RoutingKey("http:\\queueUrl"); var contentType = new ContentType(MediaTypeNames.Text.Plain); - var correlationId =Id.Random(); + var correlationId = Id.Random(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, + channelType: ChannelType.PointToPoint, findQueueBy: QueueFindBy.Name, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -50,17 +50,17 @@ public AwsValidateInfrastructureTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); subscription.MakeChannels = OnMissingChannel.Validate; _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Validate) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs index 8b16bce193..d072037ac9 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_infrastructure_exists_can_verify_by_url_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -32,7 +32,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -50,7 +50,7 @@ public AwsValidateInfrastructureByUrlTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateAsyncChannel(subscription); var queueUrl = FindQueueUrl(awsConnection, routingKey.Value).Result; @@ -67,13 +67,13 @@ public AwsValidateInfrastructureByUrlTestsAsync() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName: new ChannelName(queueUrl), + channelName: new ChannelName(queueUrl), findQueueBy: QueueFindBy.Url, - makeChannels: OnMissingChannel.Validate) - ); - + makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + - _consumer = new SqsMessageConsumerFactory(awsConnection).CreateAsync(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs index 017b9fd674..8f4cfd8767 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_a_message_should_delete_from_queue_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,14 +30,14 @@ public SqsMessageConsumerRejectTestsAsync() var queueName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, + channelType: ChannelType.PointToPoint, findQueueBy: QueueFindBy.Name, - routingKey: routingKey, - messagePumpType: MessagePumpType.Proactor, + routingKey: routingKey, + messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -49,14 +49,14 @@ public SqsMessageConsumerRejectTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName, makeChannels: OnMissingChannel.Create) - ); + awsConnection, + new SqsPublication(channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index 05eb8eb480..436540f40b 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -75,12 +75,12 @@ public SqsMessageConsumerDeliveryErrorDlqTestsAsync() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate async channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -91,7 +91,7 @@ public SqsMessageConsumerDeliveryErrorDlqTestsAsync() messagePumpType: MessagePumpType.Proactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateAsyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs index 84b0382422..062915ae0f 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_throwing_defer_action_respect_redrive_async.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -32,13 +32,13 @@ public SnsReDrivePolicySDlqTestsAsync() { const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + _dlqQueueName = $"Redrive-DLQ-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); - + var channelName = new ChannelName(queueName); var queueAttributes = new SqsAttributes( redrivePolicy: new RedrivePolicy(new ChannelName(_dlqQueueName), 2), @@ -53,7 +53,7 @@ public SnsReDrivePolicySDlqTestsAsync() requeueCount: -1, requeueDelay: TimeSpan.FromMilliseconds(50), messagePumpType: MessagePumpType.Proactor, - queueAttributes: queueAttributes + queueAttributes: queueAttributes ); var myCommand = new MyDeferredCommand { Value = "Hello Redrive", GroupId = Guid.NewGuid().ToString() }; @@ -68,13 +68,13 @@ public SnsReDrivePolicySDlqTestsAsync() _sender = new SqsMessageProducer( _awsConnection, new SqsPublication( - channelName: channelName, + channelName: channelName, queueAttributes: queueAttributes, makeChannels: OnMissingChannel.Create - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateAsyncChannel(_subscription); IHandleRequestsAsync handler = new MyDeferredCommandHandlerAsync(); @@ -88,8 +88,8 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -98,9 +98,11 @@ public SnsReDrivePolicySDlqTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_topic_missing_verify_throws_async.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_topic_missing_verify_throws_async.cs index 282915de96..fe36ab560f 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_topic_missing_verify_throws_async.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Proactor/When_topic_missing_verify_throws_async.cs @@ -8,7 +8,7 @@ namespace Paramore.Brighter.AWS.V4.Tests.MessagingGateway.Sqs.Standard.Proactor; [Trait("Category", "AWS")] -public class AWSValidateMissingTopicTestsAsync +public class AWSValidateMissingTopicTestsAsync { private readonly AWSMessagingGatewayConnection _awsConnection; private readonly RoutingKey _routingKey; @@ -16,7 +16,7 @@ public class AWSValidateMissingTopicTestsAsync public AWSValidateMissingTopicTestsAsync() { - _queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); + _queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _routingKey = new RoutingKey(_queueName); _awsConnection = GatewayFactory.CreateFactory(); @@ -30,11 +30,11 @@ public async Task When_topic_missing_verify_throws_async() // arrange var producer = new SqsMessageProducer( _awsConnection, - new SqsPublication(channelName: new ChannelName(_queueName), makeChannels: OnMissingChannel.Validate) - ); + new SqsPublication(channelName: new ChannelName(_queueName), makeChannels: OnMissingChannel.Validate), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // act & assert - await Assert.ThrowsAsync(async () => + await Assert.ThrowsAsync(async () => await producer.SendAsync(new Message( new MessageHeader("", _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("plain/text")), new MessageBody("Test")))); diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs index c614a3a799..bddf68bbab 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_customising_aws_client_config.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,7 +30,7 @@ public CustomisingAwsClientConfigTests() var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, @@ -48,7 +48,7 @@ public CustomisingAwsClientConfigTests() config.HttpClientFactory = new InterceptingHttpClientFactory(new InterceptingDelegatingHandler("sqs_sync_sub")); }); - _channelFactory = new ChannelFactory(subscribeAwsConnection); + _channelFactory = new ChannelFactory(subscribeAwsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); var publishAwsConnection = GatewayFactory.CreateFactory(config => @@ -57,7 +57,7 @@ public CustomisingAwsClientConfigTests() }); _messageProducer = new SqsMessageProducer(publishAwsConnection, - new SqsPublication { ChannelName = channelName, MakeChannels = OnMissingChannel.Create }); + new SqsPublication { ChannelName = channelName, MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -76,7 +76,7 @@ public async Task When_customising_aws_client_config() //publish_and_subscribe_should_use_custom_http_client_factory Assert.Contains("sqs_sync_sub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sqs_sync_sub"]) > (0)); - + Assert.Contains("sqs_sync_pub", InterceptingDelegatingHandler.RequestCount); Assert.True((InterceptingDelegatingHandler.RequestCount["sqs_sync_pub"]) > (0)); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs index 922bbde89c..a2b560e085 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_assume.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,19 +26,19 @@ public AWSAssumeInfrastructureTests() _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, - messagePumpType: MessagePumpType.Reactor, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, + messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -53,7 +53,7 @@ public AWSAssumeInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -61,10 +61,10 @@ public AWSAssumeInfrastructureTests() subscription.ChannelName = channel.Name; _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Assume)); + awsConnection, + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Assume), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumer(awsConnection, channel.Name); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_verify.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_verify.cs index 5b2ae63b23..6d0adcb183 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_verify.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_infastructure_exists_can_verify.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net.Mime; using System.Text.Json; @@ -26,7 +26,7 @@ public AWSValidateInfrastructureTests() _myCommand = new MyCommand { Value = "Test" }; const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var queueName = $"Producer-Send-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -49,7 +49,7 @@ public AWSValidateInfrastructureTests() //We need to do this manually in a test - will create the channel from subscriber parameters //This doesn't look that different from our create tests - this is because we create using the channel factory in //our AWS transport, not the consumer (as it's a more likely to use infrastructure declared elsewhere) - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channel = _channelFactory.CreateSyncChannel(subscription); //Now change the subscription to validate, just check what we made @@ -64,12 +64,12 @@ public AWSValidateInfrastructureTests() _messageProducer = new SqsMessageProducer( awsConnection, new SqsPublication( - channelName:channel.Name, + channelName: channel.Name, makeChannels: OnMissingChannel.Validate - ) - ); + ), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = new SqsMessageConsumerFactory(awsConnection).Create(subscription); + _consumer = new SqsMessageConsumerFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(subscription); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs index 5df29621c4..10d247e2e8 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_queue_missing_verify_throws.cs @@ -28,7 +28,7 @@ public void When_queue_missing_verify_throws() //arrange var producer = new SqsMessageProducer( _awsConnection, - new SqsPublication(channelName: new ChannelName(_routingKey), makeChannels: OnMissingChannel.Validate)); + new SqsPublication(channelName: new ChannelName(_routingKey), makeChannels: OnMissingChannel.Validate), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act && assert Assert.Throws(() => producer.Send(new Message( diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs index ef1ce6684e..af6552eef4 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_a_message_should_delete_from_queue.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; @@ -30,12 +30,12 @@ public SqsMessageConsumerRejectTests() var queueName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var routingKey = new RoutingKey(queueName); var channelName = new ChannelName(queueName); - + var subscription = new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: channelName, - channelType: ChannelType.PointToPoint, - routingKey: routingKey, + channelType: ChannelType.PointToPoint, + routingKey: routingKey, messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create, queueAttributes: new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } })); @@ -50,14 +50,14 @@ public SqsMessageConsumerRejectTests() var awsConnection = GatewayFactory.CreateFactory(); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( - awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + awsConnection, + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index 65e84fc0b0..ac2ff71151 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -75,12 +75,12 @@ public SqsMessageConsumerDeliveryErrorDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -91,7 +91,7 @@ public SqsMessageConsumerDeliveryErrorDlqTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs index 23e4d28d19..ec230bf017 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -70,12 +70,12 @@ public SqsMessageConsumerNoChannelsRejectTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 4872f1ac88..cb52ccfc6e 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -76,12 +76,12 @@ public SqsMessageConsumerUnacceptableFallbackToDlqTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the DLQ queue var dlqSubscription = new SqsSubscription( @@ -92,7 +92,7 @@ public SqsMessageConsumerUnacceptableFallbackToDlqTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index cd75aca49e..d93664df7d 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2025 Ian Cooper @@ -81,12 +81,12 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(subscription); _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create)); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Create a separate channel to consume from the invalid message queue var invalidSubscription = new SqsSubscription( @@ -97,7 +97,7 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _invalidChannelFactory = new ChannelFactory(awsConnection); + _invalidChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _invalidChannel = _invalidChannelFactory.CreateSyncChannel(invalidSubscription); // Create a separate channel to consume from the DLQ queue (to verify it stays empty) @@ -109,7 +109,7 @@ public SqsMessageConsumerUnacceptableInvalidChannelTests() messagePumpType: MessagePumpType.Reactor, makeChannels: OnMissingChannel.Create); - _dlqChannelFactory = new ChannelFactory(awsConnection); + _dlqChannelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqChannel = _dlqChannelFactory.CreateSyncChannel(dlqSubscription); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs index 897af19546..42c009a9eb 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/Standard/Reactor/When_throwing_defer_action_respect_redrive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Mime; @@ -32,7 +32,7 @@ public SnsReDrivePolicySDlqTests() { const string replyTo = "http:\\queueUrl"; var contentType = new ContentType(MediaTypeNames.Text.Plain); - + _dlqChannelName = $"Redrive-DLQ-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var correlationId = Guid.NewGuid().ToString(); var subscriptionName = $"Redrive-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -78,11 +78,11 @@ public SnsReDrivePolicySDlqTests() //how do we send to the queue _sender = new SqsMessageProducer( _awsConnection, - new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create) - ); + new SqsPublication(channelName: channelName, makeChannels: OnMissingChannel.Create), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //We need to do this manually in a test - will create the channel from subscriber parameters - _channelFactory = new ChannelFactory(_awsConnection); + _channelFactory = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channel = _channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -99,8 +99,8 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -109,16 +109,18 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence, we are building our own dispatcher in this test - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { - Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3 }; } private int GetDLQCount(string queueName) { - using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); + using var sqsClient = new AWSClientFactory(_awsConnection).CreateSqsClient(); var queueUrlResponse = sqsClient.GetQueueUrlAsync(queueName).GetAwaiter().GetResult(); var response = sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest { diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs index c81a6c270d..c8ed5a5d05 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/Sqs/When_creating_sqs_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -43,7 +43,7 @@ public SqsMessageConsumerFactoryDlqTests() var connection = new AWSMessagingGatewayConnection( new BasicAWSCredentials("test", "test"), RegionEndpoint.EUWest1); - _factory = new SqsMessageConsumerFactory(connection); + _factory = new SqsMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs index b1ea110c0c..667529e59b 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsFifoMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -113,7 +113,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -128,7 +128,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -148,7 +148,7 @@ public IAmAMessageProducerSync CreateProducer(SqsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -163,7 +163,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -181,7 +181,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( queueAttributes: new SqsAttributes(type: SqsType.Fifo) ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs index 71a9357c63..1fc7583988 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/MessagingGateway/SqsStandardMessageGatewayProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -110,7 +110,7 @@ public async Task CleanUpAsync( public IAmAChannelSync CreateChannel(SqsSubscription subscription) { - var channel = new ChannelFactory(_awsConnection) + var channel = new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -125,7 +125,7 @@ public async Task CreateChannelAsync( SqsSubscription subscription, CancellationToken cancellationToken = default) { - var channel = await new ChannelFactory(_awsConnection) + var channel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -145,7 +145,7 @@ public IAmAMessageProducerSync CreateProducer(SqsPublication publication) connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -160,7 +160,7 @@ public async Task CreateProducerAsync( connection = GatewayFactory.CreateFactory(); } - var producer = new SqsMessageProducer(connection, publication); + var producer = new SqsMessageProducer(connection, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return producer; } @@ -177,7 +177,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( makeChannels: OnMissingChannel.Assume ); - var dlqChannel = await new ChannelFactory(_awsConnection) + var dlqChannel = await new ChannelFactory(_awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(dlqSubscription, cancellationToken); try diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs index 92b49ad90c..1868f3423b 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs @@ -13,13 +13,13 @@ public class S3LuggageUploadMissingParametersTests { private readonly IHttpClientFactory _httpClientFactory; private readonly string _bucketName; - + public S3LuggageUploadMissingParametersTests() { var services = new ServiceCollection(); services.AddHttpClient(); var provider = services.BuildServiceProvider(); - + _httpClientFactory = provider.GetRequiredService(); _bucketName = $"brightertestbucket-{Guid.NewGuid()}"; } @@ -28,7 +28,7 @@ public S3LuggageUploadMissingParametersTests() public void When_creating_luggagestore_missing_client() { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(null!, null!))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(null!, null!), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); @@ -40,38 +40,38 @@ public void When_creating_luggagestore_missing_client() public void When_creating_luggagestore_missing_bucketName(string? bucketName) { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName!))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName!), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] public async Task When_creating_luggagestore_bad_bucketName() { //arrange - var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), "A" ))); + var exception = Catch.Exception(() => new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), "A"), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] public async Task When_creating_luggagestore_missing_httpClient() { //arrange var exception = await Catch.ExceptionAsync(async () => { - var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName)); + var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await store.EnsureStoreExistsAsync(); }); Assert.NotNull(exception); Assert.IsType(exception); } - + [Fact] - public async Task When_creating_luggagestore_missing_ACL() + public async Task When_creating_luggagestore_missing_ACL() { //arrange var exception = await Catch.ExceptionAsync(async () => @@ -79,11 +79,11 @@ public async Task When_creating_luggagestore_missing_ACL() var store = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), _bucketName) { HttpClientFactory = _httpClientFactory, - BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate() - }); + BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate() + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await store.EnsureStoreExistsAsync(); }); - + Assert.NotNull(exception); Assert.IsType(exception); } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_unwrapping_a_large_message.cs index 72867fa5ff..d68e5c19d1 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_unwrapping_a_large_message.cs @@ -16,7 +16,7 @@ namespace Paramore.Brighter.AWS.V4.Tests.Transformers; [Trait("Category", "AWS")] -public class LargeMessagePaylodUnwrapTests : IAsyncDisposable +public class LargeMessagePaylodUnwrapTests : IAsyncDisposable { private readonly TransformPipelineBuilderAsync _pipelineBuilder; private readonly AmazonS3Client _client; @@ -48,14 +48,14 @@ public LargeMessagePaylodUnwrapTests() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }] - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _luggageStore.EnsureStoreExists(); var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.None); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); } [Fact] diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_uploading_luggage_to_S3.cs b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_uploading_luggage_to_S3.cs index 5ec27a975b..05d4e3eefe 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_uploading_luggage_to_S3.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_uploading_luggage_to_S3.cs @@ -30,7 +30,7 @@ public S3LuggageUploadTests() _httpClientFactory = provider.GetRequiredService(); _bucketName = $"brightertestbucket-{Guid.NewGuid()}"; } - + [Fact] public async Task When_uploading_luggage_to_S3() { @@ -42,10 +42,10 @@ public async Task When_uploading_luggage_to_S3() ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], RetryPolicy = GetSimpleHandlerRetryPolicy() - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + await luggageStore.EnsureStoreExistsAsync(); - + //act //Upload the test stream to S3 const string testContent = "Well, always know that you shine Brighter"; @@ -60,7 +60,7 @@ public async Task When_uploading_luggage_to_S3() //assert //do we have a claim? Assert.True((await luggageStore.HasClaimAsync(claim))); - + //check for the contents indicated by the claim id on S3 var result = await luggageStore.RetrieveAsync(claim); var resultAsString = await new StreamReader(result).ReadToEndAsync(); @@ -69,13 +69,13 @@ public async Task When_uploading_luggage_to_S3() await luggageStore.DeleteAsync(claim); } - + public static AsyncRetryPolicy GetSimpleHandlerRetryPolicy() { - var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(50), retryCount: 3, fastFirst:true); + var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(50), retryCount: 3, fastFirst: true); //TODO: Its not worth retrying malformed XML, error code: MalformedXML - + return Policy .Handle(e => { diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_validating_a_luggage_store_exists.cs b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_validating_a_luggage_store_exists.cs index d55e763db4..ea0fcfa0a0 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_validating_a_luggage_store_exists.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_validating_a_luggage_store_exists.cs @@ -12,8 +12,8 @@ namespace Paramore.Brighter.AWS.V4.Tests.Transformers; -[Trait("Category", "AWS")] -public class S3LuggageStoreExistsTests +[Trait("Category", "AWS")] +public class S3LuggageStoreExistsTests { private readonly IHttpClientFactory _httpClientFactory; @@ -25,12 +25,12 @@ public S3LuggageStoreExistsTests() var provider = services.BuildServiceProvider(); _httpClientFactory = provider.GetRequiredService(); } - + [Fact] public async Task When_checking_store_that_exists() { var bucketName = $"brightertestbucket-{Guid.NewGuid()}"; - + //arrange var luggageStore = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName) { @@ -38,8 +38,8 @@ public async Task When_checking_store_that_exists() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + await luggageStore.EnsureStoreExistsAsync(); //allow bucket endpoint to come into existence @@ -49,39 +49,39 @@ public async Task When_checking_store_that_exists() luggageStore = new S3LuggageStore(new S3LuggageOptions(GatewayFactory.CreateS3Connection(), bucketName) { Strategy = StorageStrategy.Validate, - HttpClientFactory = _httpClientFactory, + HttpClientFactory = _httpClientFactory, BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); Assert.NotNull(luggageStore); - + //teardown var factory = new AWSClientFactory(GatewayFactory.CreateFactory()); var client = factory.CreateS3Client(); await client.DeleteBucketAsync(bucketName); } - + [Fact] public async Task When_checking_store_that_does_not_exist() { //act - var doesNotExist = await Catch.ExceptionAsync(async () => - { - var luggageStore = new S3LuggageStore( - new S3LuggageOptions(GatewayFactory.CreateS3Connection(), $"brightertestbucket-{Guid.NewGuid()}") - { - Strategy = StorageStrategy.Validate, - HttpClientFactory = _httpClientFactory, - BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), - ACLs = S3CannedACL.Private, - Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); + var doesNotExist = await Catch.ExceptionAsync(async () => + { + var luggageStore = new S3LuggageStore( + new S3LuggageOptions(GatewayFactory.CreateS3Connection(), $"brightertestbucket-{Guid.NewGuid()}") + { + Strategy = StorageStrategy.Validate, + HttpClientFactory = _httpClientFactory, + BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), + ACLs = S3CannedACL.Private, + Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + + await luggageStore.EnsureStoreExistsAsync(); + }); - await luggageStore.EnsureStoreExistsAsync(); - }); - - Assert.NotNull(doesNotExist); - Assert.True(doesNotExist is InvalidOperationException); + Assert.NotNull(doesNotExist); + Assert.True(doesNotExist is InvalidOperationException); } } diff --git a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_wrapping_a_large_message.cs index 471f37b1cd..3ef8e4d409 100644 --- a/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.AWS.V4.Tests/Transformers/When_wrapping_a_large_message.cs @@ -15,7 +15,7 @@ namespace Paramore.Brighter.AWS.V4.Tests.Transformers; [Trait("Category", "AWS")] -public class LargeMessagePayloadWrapTests : IAsyncDisposable +public class LargeMessagePayloadWrapTests : IAsyncDisposable { private string? _id; private WrapPipelineAsync? _transformPipeline; @@ -31,14 +31,14 @@ public LargeMessagePayloadWrapTests() { //arrange TransformPipelineBuilderAsync.ClearPipelineCache(); - + var mapperRegistry = new MessageMapperRegistry(null, new SimpleMessageMapperFactoryAsync( _ => new MyLargeCommandMessageMapperAsync()) ); - + mapperRegistry.RegisterAsync(); - + _myCommand = new MyLargeCommand(6000); var factory = new AWSClientFactory(GatewayFactory.CreateFactory()); @@ -57,15 +57,15 @@ public LargeMessagePayloadWrapTests() BucketAddressTemplate = CredentialsChain.GetBucketAddressTemplate(), ACLs = S3CannedACL.Private, Tags = [new Tag { Key = "BrighterTests", Value = "S3LuggageUploadTests" }], - }); - + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _luggageStore.EnsureStoreExists(); var transformerFactoryAsync = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, InstrumentationOptions.None); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); } [Fact] @@ -80,18 +80,18 @@ public async Task When_wrapping_a_large_message() Assert.NotNull(message.Header.DataRef); _id = (string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK]; Assert.Equal($"Claim Check {_id}", message.Body.Value); - + Assert.True(await _luggageStore.HasClaimAsync(_id)); } public async ValueTask DisposeAsync() { - //We have to empty objects from a bucket before deleting it - if (_id != null) - { - await _luggageStore.DeleteAsync(_id); - } + //We have to empty objects from a bucket before deleting it + if (_id != null) + { + await _luggageStore.DeleteAsync(_id); + } - await _client.DeleteBucketAsync(_bucketName); + await _client.DeleteBucketAsync(_bucketName); } } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs index f5682ae6a7..3d89fce6f5 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs @@ -23,7 +23,7 @@ public SnsSchedulingMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,9 +40,9 @@ public SnsSchedulingMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -55,7 +55,8 @@ public SnsSchedulingMessageTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = true, MakeRole = OnMissingRole.Create + UseMessageTopicAsTarget = true, + MakeRole = OnMissingRole.Create }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs index 0d463d96e7..1f758c49de 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs @@ -23,7 +23,7 @@ public SnsSchedulingAsyncMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,9 +40,9 @@ public SnsSchedulingAsyncMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.SendAsync(new Message( diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs index 701784ab69..64d9a5b6b0 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs @@ -25,7 +25,7 @@ public SnsSchedulingMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Fire-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Fire-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -42,9 +42,9 @@ public SnsSchedulingMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -56,7 +56,9 @@ public SnsSchedulingMessageViaFireSchedulerTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs index b897a9ac3c..2efd2e765d 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs @@ -13,7 +13,7 @@ namespace Paramore.Brighter.AWSScheduler.Tests.Scheduler.Messages.Sns; [Collection("Scheduler SNS")] public class SnsSchedulingMessageViaFireSchedulerAsyncTest : IDisposable { - private readonly ContentType _contentType = new( MediaTypeNames.Text.Plain); + private readonly ContentType _contentType = new(MediaTypeNames.Text.Plain); private const int BufferSize = 3; private readonly SnsMessageProducer _messageProducer; private readonly SqsMessageConsumer _consumer; @@ -25,7 +25,7 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Fire-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Fire-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -42,9 +42,9 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -56,7 +56,9 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } @@ -74,7 +76,7 @@ public async Task When_Scheduling_A_Sns_Message_Async() await scheduler.ScheduleAsync(message, TimeSpan.FromMinutes(1)); await Task.Delay(TimeSpan.FromMinutes(1)); - + var stopAt = DateTimeOffset.UtcNow.AddMinutes(2); while (stopAt > DateTimeOffset.UtcNow) { diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs index fd82304378..a16a01da39 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs @@ -22,7 +22,7 @@ public SqsSchedulingMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -37,13 +37,13 @@ public SqsSchedulingMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = true, + UseMessageTopicAsTarget = true, MakeRole = OnMissingRole.Create }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs index bbbcf3a85e..63e00991f3 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs @@ -22,7 +22,7 @@ public SqsSchedulingAsyncMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -37,9 +37,9 @@ public SqsSchedulingAsyncMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs index fea42f40b3..745887bfe8 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs @@ -12,7 +12,7 @@ namespace Paramore.Brighter.AWSScheduler.Tests.Scheduler.Messages.Sqs; [Collection("Scheduler SQS")] public class SqsSchedulingMessageViaFireSchedulerTest : IDisposable { - private readonly ContentType _contentType = new (MediaTypeNames.Text.Plain); + private readonly ContentType _contentType = new(MediaTypeNames.Text.Plain); private const int BufferSize = 3; private readonly SqsMessageProducer _messageProducer; private readonly SqsMessageConsumer _consumer; @@ -24,7 +24,7 @@ public SqsSchedulingMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,13 +39,13 @@ public SqsSchedulingMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, + UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey }; diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs index 47242b271e..1e7b44a3ac 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs @@ -24,7 +24,7 @@ public SqsSchedulingAsyncMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,14 +39,14 @@ public SqsSchedulingAsyncMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { UseMessageTopicAsTarget = false, - MakeRole = OnMissingRole.Create, + MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs index 100dbc67c1..649bed0cbb 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs @@ -28,7 +28,7 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications string topicName = $"Producer-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -45,9 +45,9 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -61,7 +61,9 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } @@ -126,7 +128,7 @@ public async Task When_Scheduling_A_Sns_Request_With_SpecificDateTime(RequestSch while (stopAt > DateTimeOffset.UtcNow) { var messages = _consumer.Receive(TimeSpan.FromMinutes(1)); - + Assert.Single(messages); if (messages[0].Header.MessageType != MessageType.MT_NONE) @@ -229,7 +231,7 @@ public async Task When_Cancel_A_Sns_Request(RequestSchedulerType schedulerType) Assert.NotNull(ex); Assert.True((ex) is ResourceNotFoundException); } - + public void Dispose() { _channelFactory.DeleteQueueAsync().GetAwaiter().GetResult(); diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs index 4e4530a0ee..68a6202679 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs @@ -28,7 +28,7 @@ public SnsSchedulingRequestAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications string topicName = $"Producer-FSRA-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-FSRA-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -45,9 +45,9 @@ public SnsSchedulingRequestAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -61,7 +61,9 @@ public SnsSchedulingRequestAsyncTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs index 210b2c3bdb..324f564ca5 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs @@ -25,7 +25,7 @@ public SqsSchedulingRequestTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,15 +40,17 @@ public SqsSchedulingRequestTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new AWSClientFactory(awsConnection).CreateSchedulerClient(); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs index d426c83597..70e70b044c 100644 --- a/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs @@ -26,7 +26,7 @@ public SqsSchedulingRequestAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,7 +39,7 @@ public SqsSchedulingRequestAsyncTest() delaySeconds: TimeSpan.Zero, tags: new Dictionary { { "Environment", "Test" } } ); - + var channel = _channelFactory.CreateAsyncChannelAsync(new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: new ChannelName(_queueName), @@ -48,17 +48,19 @@ public SqsSchedulingRequestAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); - + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); + //in principle, for point-to-point, we don't need both sides to create the queue; whoever does not own the API can just validate _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication{ QueueAttributes = sqsAttributes, MakeChannels = OnMissingChannel.Create }); - + new SqsPublication { QueueAttributes = sqsAttributes, MakeChannels = OnMissingChannel.Create }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _scheduler = new AWSClientFactory(awsConnection).CreateSchedulerClient(); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs index efe9e4527a..f7b6ac5b9b 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message.cs @@ -23,7 +23,7 @@ public SnsSchedulingMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,9 +40,9 @@ public SnsSchedulingMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -55,7 +55,8 @@ public SnsSchedulingMessageTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = true, MakeRole = OnMissingRole.Create + UseMessageTopicAsTarget = true, + MakeRole = OnMissingRole.Create }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs index d60f4c4d4e..a4ca50068e 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Async.cs @@ -23,7 +23,7 @@ public SnsSchedulingAsyncMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,9 +40,9 @@ public SnsSchedulingAsyncMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SnsMessageProducer(awsConnection, - new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.SendAsync(new Message( diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs index b1eef4a099..b8e2598985 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler.cs @@ -25,7 +25,7 @@ public SnsSchedulingMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Fire-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Fire-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -42,9 +42,9 @@ public SnsSchedulingMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -56,7 +56,9 @@ public SnsSchedulingMessageViaFireSchedulerTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs index 4d55c7466a..e782a00887 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sns/When_Scheduling_A_Sns_Message_Via_FireScheduler_Async.cs @@ -13,7 +13,7 @@ namespace Paramore.Brighter.AWSScheduler.V4.Tests.Scheduler.Messages.Sns; [Collection("Scheduler SNS")] public class SnsSchedulingMessageViaFireSchedulerAsyncTest : IDisposable { - private readonly ContentType _contentType = new( MediaTypeNames.Text.Plain); + private readonly ContentType _contentType = new(MediaTypeNames.Text.Plain); private const int BufferSize = 3; private readonly SnsMessageProducer _messageProducer; private readonly SqsMessageConsumer _consumer; @@ -25,7 +25,7 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications _topicName = $"Producer-Fire-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-Fire-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -42,9 +42,9 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new Tag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -56,7 +56,9 @@ public SnsSchedulingMessageViaFireSchedulerAsyncTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } @@ -74,7 +76,7 @@ public async Task When_Scheduling_A_Sns_Message_Async() await scheduler.ScheduleAsync(message, TimeSpan.FromMinutes(1)); await Task.Delay(TimeSpan.FromMinutes(1)); - + var stopAt = DateTimeOffset.UtcNow.AddMinutes(2); while (stopAt > DateTimeOffset.UtcNow) { diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs index 5443445b96..b0a5cc6e37 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message.cs @@ -22,7 +22,7 @@ public SqsSchedulingMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -37,13 +37,13 @@ public SqsSchedulingMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = true, + UseMessageTopicAsTarget = true, MakeRole = OnMissingRole.Create }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs index c88dbbba15..520678efa6 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Async.cs @@ -22,7 +22,7 @@ public SqsSchedulingAsyncMessageTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -37,9 +37,9 @@ public SqsSchedulingAsyncMessageTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs index 616934e94b..dae91db3a2 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler.cs @@ -12,7 +12,7 @@ namespace Paramore.Brighter.AWSScheduler.V4.Tests.Scheduler.Messages.Sqs; [Collection("Scheduler SQS")] public class SqsSchedulingMessageViaFireSchedulerTest : IDisposable { - private readonly ContentType _contentType = new (MediaTypeNames.Text.Plain); + private readonly ContentType _contentType = new(MediaTypeNames.Text.Plain); private const int BufferSize = 3; private readonly SqsMessageProducer _messageProducer; private readonly SqsMessageConsumer _consumer; @@ -24,7 +24,7 @@ public SqsSchedulingMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,13 +39,13 @@ public SqsSchedulingMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, + UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey }; diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs index 37cd1007f4..f2ac8f2f93 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Messages/Sqs/When_Scheduling_A_Sqs_Message_Via_FireScheduler_Async.cs @@ -24,7 +24,7 @@ public SqsSchedulingAsyncMessageViaFireSchedulerTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,14 +39,14 @@ public SqsSchedulingAsyncMessageViaFireSchedulerTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { UseMessageTopicAsTarget = false, - MakeRole = OnMissingRole.Create, + MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs index 52cf63bdac..fe676fb1b7 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request.cs @@ -28,7 +28,7 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications string topicName = $"Producer-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -45,9 +45,9 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -61,7 +61,9 @@ public SnsSchedulingMessageViaFireSchedulerRequestTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } @@ -126,7 +128,7 @@ public async Task When_Scheduling_A_Sns_Request_With_SpecificDateTime(RequestSch while (stopAt > DateTimeOffset.UtcNow) { var messages = _consumer.Receive(TimeSpan.FromMinutes(1)); - + Assert.Single(messages); if (messages[0].Header.MessageType != MessageType.MT_NONE) @@ -229,7 +231,7 @@ public async Task When_Cancel_A_Sns_Request(RequestSchedulerType schedulerType) Assert.NotNull(ex); Assert.True((ex) is ResourceNotFoundException); } - + public void Dispose() { _channelFactory.DeleteQueueAsync().GetAwaiter().GetResult(); diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs index 069a3ff558..f8dba6710b 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sns/When_Scheduling_A_Sns_Request_Async.cs @@ -28,7 +28,7 @@ public SnsSchedulingRequestAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //we need the channel to create the queues and notifications string topicName = $"Producer-FSRA-Tests-{Guid.NewGuid().ToString()}".Truncate(45); var channelName = $"Producer-FSRA-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -45,9 +45,9 @@ public SnsSchedulingRequestAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = - new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }); + new SnsMessageProducer(awsConnection, new SnsPublication { MakeChannels = OnMissingChannel.Create, TopicAttributes = new SnsAttributes(tags: [new SnsTag { Key = "Environment", Value = "Test" }]) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Enforce topic to be created _messageProducer.Send(new Message( @@ -61,7 +61,9 @@ public SnsSchedulingRequestAsyncTest() _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs index f8ac5889ae..17fcc759f5 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request.cs @@ -25,7 +25,7 @@ public SqsSchedulingRequestTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-FSR-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -40,15 +40,17 @@ public SqsSchedulingRequestTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); _messageProducer = new SqsMessageProducer(awsConnection, - new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }); + new SqsPublication { MakeChannels = OnMissingChannel.Create, QueueAttributes = new SqsAttributes(tags: new Dictionary { { "Environment", "Test" } }) }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new AWSClientFactory(awsConnection).CreateSchedulerClient(); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs index 3982ee9c3b..9971b1c209 100644 --- a/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs +++ b/tests/Paramore.Brighter.AWSScheduler.V4.Tests/Scheduler/Requests/Sqs/When_Scheduling_A_Sqs_Request_Async.cs @@ -26,7 +26,7 @@ public SqsSchedulingRequestAsyncTest() { var awsConnection = GatewayFactory.CreateFactory(); - _channelFactory = new ChannelFactory(awsConnection); + _channelFactory = new ChannelFactory(awsConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscriptionName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); _queueName = $"Buffered-Scheduler-Async-Tests-{Guid.NewGuid().ToString()}".Truncate(45); @@ -39,7 +39,7 @@ public SqsSchedulingRequestAsyncTest() delaySeconds: TimeSpan.Zero, tags: new Dictionary { { "Environment", "Test" } } ); - + var channel = _channelFactory.CreateAsyncChannelAsync(new SqsSubscription( subscriptionName: new SubscriptionName(subscriptionName), channelName: new ChannelName(_queueName), @@ -48,18 +48,20 @@ public SqsSchedulingRequestAsyncTest() //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel //just for the tests, so create a new consumer from the properties - _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), BufferSize); - + _consumer = new SqsMessageConsumer(awsConnection, channel.Name.ToValidSQSQueueName(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, BufferSize); + //in principle, for point-to-point, we don't need both sides to create the queue; whoever does not own the API can just validate _messageProducer = new SqsMessageProducer( awsConnection, - new SqsPublication{QueueAttributes = sqsAttributes, MakeChannels = OnMissingChannel.Create} - ); + new SqsPublication { QueueAttributes = sqsAttributes, MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new AWSClientFactory(awsConnection).CreateSchedulerClient(); _factory = new AwsSchedulerFactory(awsConnection, "brighter-scheduler") { - UseMessageTopicAsTarget = false, MakeRole = OnMissingRole.Create, SchedulerTopicOrQueue = routingKey + UseMessageTopicAsTarget = false, + MakeRole = OnMissingRole.Create, + SchedulerTopicOrQueue = routingKey }; } diff --git a/tests/Paramore.Brighter.Azure.Tests/AzureBlobArchiveProviderTests.cs b/tests/Paramore.Brighter.Azure.Tests/AzureBlobArchiveProviderTests.cs index f29b9525c1..5df755303d 100644 --- a/tests/Paramore.Brighter.Azure.Tests/AzureBlobArchiveProviderTests.cs +++ b/tests/Paramore.Brighter.Azure.Tests/AzureBlobArchiveProviderTests.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; using Azure.Identity; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; @@ -29,16 +29,16 @@ public AzureBlobArchiveProviderTests() _storageLocationFunction = (message) => $"{message.Header.Topic}/{message.Id}".ToLower(); } - + [Test] public async Task GivenARequestToArchiveAMessage_TheMessageIsArchived() { var publication = new Publication { - Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeCommand"), + Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeCommand"), RequestType = typeof(SuperAwesomeCommand) }; - + var commandMessage = _commandMapper?.MapToMessage(_command, publication); if (commandMessage == null) @@ -48,7 +48,7 @@ public async Task GivenARequestToArchiveAMessage_TheMessageIsArchived() } var blobClient = GetClient(AccessTier.Cool).GetBlobClient(_storageLocationFunction?.Invoke(commandMessage)); - + _provider?.ArchiveMessage(commandMessage); Assert.That((bool)await blobClient.ExistsAsync(), Is.True); @@ -57,12 +57,12 @@ public async Task GivenARequestToArchiveAMessage_TheMessageIsArchived() Assert.That(tags.Count, Is.EqualTo(0)); var body = (await blobClient.DownloadContentAsync()).Value.Content.ToString(); - + Assert.That(body, Is.EqualTo(commandMessage.Body.Value)); var tier = await blobClient.GetPropertiesAsync(); Assert.That(tier.Value.AccessTier, Is.EqualTo(AccessTier.Cool.ToString())); - + } [Test] @@ -70,19 +70,19 @@ public async Task GivenARequestToArchiveAMessage_WhenTagsAreTurnedOn_ThenTagsAre { var publication = new Publication { - Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), + Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), RequestType = typeof(SuperAwesomeEvent) }; - + var eventMessage = _eventMapper.MapToMessage(_event, publication); - + var blobClient = GetClient(AccessTier.Hot, true).GetBlobClient(_storageLocationFunction.Invoke(eventMessage)); - + _provider?.ArchiveMessage(eventMessage); - + var tier = await blobClient.GetPropertiesAsync(); Assert.That(tier.Value.AccessTier, Is.EqualTo(AccessTier.Hot.ToString())); - + var tags = (await blobClient.GetTagsAsync()).Value.Tags; Assert.That(tags["topic"], Is.EqualTo(eventMessage.Header.Topic.Value)); @@ -100,9 +100,9 @@ public async Task GivenARequestToArchiveAMessageAsync_TheMessageIsArchived() Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeCommand"), RequestType = typeof(SuperAwesomeCommand) }; - + var commandMessage = _commandMapper.MapToMessage(_command, publication); - + if (commandMessage == null) { Assert.Fail("Failed to map command to message"); @@ -110,7 +110,7 @@ public async Task GivenARequestToArchiveAMessageAsync_TheMessageIsArchived() } var blobClient = GetClient(AccessTier.Cool).GetBlobClient(_storageLocationFunction.Invoke(commandMessage)); - + await _provider?.ArchiveMessageAsync(commandMessage, CancellationToken.None)!; Assert.That((bool)await blobClient.ExistsAsync(), Is.True); @@ -119,12 +119,12 @@ public async Task GivenARequestToArchiveAMessageAsync_TheMessageIsArchived() Assert.That(tags.Count, Is.EqualTo(0)); var body = (await blobClient.DownloadContentAsync()).Value.Content.ToString(); - + Assert.That(body, Is.EqualTo(commandMessage.Body.Value)); var tier = await blobClient.GetPropertiesAsync(); Assert.That(tier.Value.AccessTier, Is.EqualTo(AccessTier.Cool.ToString())); - + } [Test] @@ -132,16 +132,16 @@ public async Task GivenARequestToArchiveAMessageAsync_WhenParallel_TheMessageIsA { var cmdPublication = new Publication { - Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeCommand"), + Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeCommand"), RequestType = typeof(SuperAwesomeCommand) }; - + var evtPublication = new Publication { - Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), + Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), RequestType = typeof(SuperAwesomeEvent) }; - + var superAwesomeCommands = new List(); var superAwesomeEvents = new List(); @@ -174,7 +174,7 @@ public async Task GivenARequestToArchiveAMessageAsync_WhenParallel_TheMessageIsA brighterBody = JsonSerializer.Serialize(superAwesomeCommands.First(c => c.Id == message.Id)); else if (message.Header.MessageType == MessageType.MT_EVENT) brighterBody = JsonSerializer.Serialize(superAwesomeEvents.First(c => c.Id == message.Id)); - + Assert.That(body, Is.EqualTo(brighterBody)); var tier = await blobClient.GetPropertiesAsync(); @@ -188,19 +188,19 @@ public async Task GivenARequestToArchiveAMessageAsync_WhenTagsAreTurnedOn_ThenTa { var publication = new Publication { - Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), + Topic = new RoutingKey($"{Guid.NewGuid()}-SuperAwesomeEvent"), RequestType = typeof(SuperAwesomeEvent) }; - + var eventMessage = _eventMapper.MapToMessage(_event, publication); - + var blobClient = GetClient(AccessTier.Hot, true).GetBlobClient(_storageLocationFunction.Invoke(eventMessage)); - + await _provider?.ArchiveMessageAsync(eventMessage, CancellationToken.None)!; - + var tier = await blobClient.GetPropertiesAsync(); Assert.That(tier.Value.AccessTier, Is.EqualTo(AccessTier.Hot.ToString())); - + var tags = (await blobClient.GetTagsAsync()).Value.Tags; Assert.That(tags["topic"], Is.EqualTo(eventMessage.Header.Topic.Value)); @@ -210,16 +210,16 @@ public async Task GivenARequestToArchiveAMessageAsync_WhenTagsAreTurnedOn_ThenTa Assert.That(tags["content_type"], Is.EqualTo(eventMessage.Header.ContentType!.ToString())); } - private BlobContainerClient GetClient(AccessTier tier , bool tags = false ) + private BlobContainerClient GetClient(AccessTier tier, bool tags = false) { var options = new AzureBlobArchiveProviderOptions ( - new Uri("https://brighterarchivertest.blob.core.windows.net/messagearchive"), + new Uri("https://brighterarchivertest.blob.core.windows.net/messagearchive"), new AzureCliCredential(), tier, tags ); - _provider = new AzureBlobArchiveProvider(options); + _provider = new AzureBlobArchiveProvider(options, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new BlobContainerClient(options.BlobContainerUri, options.TokenCredential); } diff --git a/tests/Paramore.Brighter.Azure.Tests/AzureBlobLockingProviderTests.cs b/tests/Paramore.Brighter.Azure.Tests/AzureBlobLockingProviderTests.cs index ed15483717..d187f49ddf 100644 --- a/tests/Paramore.Brighter.Azure.Tests/AzureBlobLockingProviderTests.cs +++ b/tests/Paramore.Brighter.Azure.Tests/AzureBlobLockingProviderTests.cs @@ -1,4 +1,4 @@ -using Azure.Identity; +using Azure.Identity; using Paramore.Brighter.Locking.Azure; namespace Paramore.Brighter.Azure.Tests; @@ -11,8 +11,8 @@ public AzureBlobLockingProviderTests() { var options = new AzureBlobLockingProviderOptions( new Uri("https://brighterarchivertest.blob.core.windows.net/locking"), new AzureCliCredential()); - - _blobLocking = new AzureBlobLockingProvider(options); + + _blobLocking = new AzureBlobLockingProvider(options, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Test] @@ -21,12 +21,12 @@ public async Task GivenAnAzureBlobLockingProvider_WhenLockIsCalled_ItCanOnlyBeOb var resourceName = $"TestLock-{Guid.NewGuid()}"; var firstLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); - var secondLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); - + var secondLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); + Assert.That(firstLock, Is.Not.Null); Assert.That(secondLock, Is.Null, "A Lock should not be able to be acquired"); } - + [Test] public async Task GivenAnAzureBlobLockingProviderWithALockedBlob_WhenReleaseLockIsCalled_ItCanOnlyBeLockedAgain() { @@ -34,12 +34,12 @@ public async Task GivenAnAzureBlobLockingProviderWithALockedBlob_WhenReleaseLock var firstLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); await _blobLocking.ReleaseLockAsync(resourceName, firstLock, CancellationToken.None); - var secondLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); - var thirdLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); - + var secondLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); + var thirdLock = await _blobLocking.ObtainLockAsync(resourceName, CancellationToken.None); + Assert.That(firstLock, Is.Not.Null); Assert.That(secondLock, Is.Not.Null, "A Lock should be able to be acquired"); Assert.That(thirdLock, Is.Null, "A Lock should not be able to be acquired"); } - + } diff --git a/tests/Paramore.Brighter.Azure.Tests/Scheduler/When_scheduling_a_message_should_set_message_type_to_command.cs b/tests/Paramore.Brighter.Azure.Tests/Scheduler/When_scheduling_a_message_should_set_message_type_to_command.cs index 64a7c22e54..b93f37e779 100644 --- a/tests/Paramore.Brighter.Azure.Tests/Scheduler/When_scheduling_a_message_should_set_message_type_to_command.cs +++ b/tests/Paramore.Brighter.Azure.Tests/Scheduler/When_scheduling_a_message_should_set_message_type_to_command.cs @@ -1,4 +1,4 @@ -using Azure.Messaging.ServiceBus; +using Azure.Messaging.ServiceBus; using Paramore.Brighter.Azure.Tests.TestDoubles; using Paramore.Brighter.MessageScheduler.Azure; @@ -18,7 +18,7 @@ public class AzureServiceBusSchedulerMessageTypeTests private readonly DateTimeOffset _fireAt = DateTimeOffset.UtcNow.AddDays(1); public AzureServiceBusSchedulerMessageTypeTests() - => _scheduler = new AzureServiceBusScheduler(_sender, new RoutingKey("scheduler-topic"), TimeProvider.System); + => _scheduler = new AzureServiceBusScheduler(_sender, new RoutingKey("scheduler-topic"), TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); [Test] public async Task When_scheduling_a_message_async_should_set_message_type_to_command() diff --git a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message.cs index e9ae33bef7..77f237ef5a 100644 --- a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message.cs @@ -29,31 +29,31 @@ public LargeMessagePayloadAUnwrapTests() ContainerUri = bucketUrl, Credential = new AzureCliCredential() }); - + TransformPipelineBuilder.ClearPipelineCache(); var mapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyLargeCommandMessageMapper()), null); mapperRegistry.Register(); - + var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } - + [Test] public void When_unwrapping_a_large_message_async() { //arrange Thread.Sleep(3000); //allow bucket definition to propagate - + //store our luggage and get the claim check var contents = DataGenerator.CreateString(6000); var myCommand = new MyLargeCommand(1) { Value = contents }; var commandAsJson = JsonSerializer.Serialize(myCommand, new JsonSerializerOptions(JsonSerializerDefaults.General)); - - var stream = new MemoryStream(); + + var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(commandAsJson); writer.Flush(); @@ -62,7 +62,7 @@ public void When_unwrapping_a_large_message_async() //pretend we ran through the claim check myCommand.Value = $"Claim Check {id}"; - + //set the headers, so that we have a claim check listed var message = new Message( new MessageHeader(myCommand.Id, new RoutingKey("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), @@ -70,18 +70,18 @@ public void When_unwrapping_a_large_message_async() ); message.Header.DataRef = id; - message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK] = id; - + message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK] = id; + //act var transformPipeline = _pipelineBuilder.BuildUnwrapPipeline(); var transformedMessage = transformPipeline.Unwrap(message, new RequestContext()); - + //assert //contents should be from storage Assert.Equals(contents, transformedMessage.Value); Assert.That(_luggageStore.HasClaim(id)); } - + public void Dispose() { _client.Delete(); diff --git a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message_async.cs index daa6963e8d..0a0ed7d165 100644 --- a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_unwrapping_a_large_message_async.cs @@ -11,7 +11,7 @@ namespace Paramore.Brighter.Azure.Tests.Transformers; [Category("Azure")] [Property("Fragile", "CI")] -public class LargeMessagePayloadAUnwrapAsyncTests : IAsyncDisposable +public class LargeMessagePayloadAUnwrapAsyncTests : IAsyncDisposable { private readonly BlobContainerClient _client; private readonly AzureBlobLuggageStore _luggageStore; @@ -30,31 +30,31 @@ public LargeMessagePayloadAUnwrapAsyncTests() ContainerUri = bucketUrl, Credential = new AzureCliCredential() }); - + TransformPipelineBuilder.ClearPipelineCache(); var mapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyLargeCommandMessageMapper()), null); mapperRegistry.Register(); - + var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } - + [Test] public async Task When_unwrapping_a_large_message_async() { //arrange await Task.Delay(3000); //allow bucket definition to propagate - + //store our luggage and get the claim check var contents = DataGenerator.CreateString(6000); var myCommand = new MyLargeCommand(1) { Value = contents }; var commandAsJson = JsonSerializer.Serialize(myCommand, new JsonSerializerOptions(JsonSerializerDefaults.General)); - - var stream = new MemoryStream(); + + var stream = new MemoryStream(); var writer = new StreamWriter(stream); await writer.WriteAsync(commandAsJson); await writer.FlushAsync(); @@ -63,7 +63,7 @@ public async Task When_unwrapping_a_large_message_async() //pretend we ran through the claim check myCommand.Value = $"Claim Check {id}"; - + //set the headers, so that we have a claim check listed var message = new Message( new MessageHeader(myCommand.Id, new RoutingKey("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), @@ -71,12 +71,12 @@ public async Task When_unwrapping_a_large_message_async() ); message.Header.DataRef = id; - message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK] = id; - + message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK] = id; + //act var transformPipeline = _pipelineBuilder.BuildUnwrapPipeline(); var transformedMessage = await transformPipeline.UnwrapAsync(message, new RequestContext()); - + //assert //contents should be from storage Assert.Equals(contents, transformedMessage.Value); diff --git a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message.cs index 9683941f5d..f17594b4d9 100644 --- a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message.cs @@ -27,9 +27,9 @@ public LargeMessagePayloadWrapTests() var mapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyLargeCommandMessageMapper()), null); - mapperRegistry.Register(); - - _publication = new Publication{ Topic = new RoutingKey("transform.event") }; + mapperRegistry.Register(); + + _publication = new Publication { Topic = new RoutingKey("transform.event") }; _myCommand = new MyLargeCommand(6000); var bucketName = $"brightertestbucket-{Guid.NewGuid()}"; @@ -42,16 +42,16 @@ public LargeMessagePayloadWrapTests() ContainerUri = bucketUrl, Credential = new AzureCliCredential() }); - + var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } - + [Test] public void When_wrapping_a_large_message() { _luggageStore.EnsureStoreExists(); - + //act _transformPipeline = _pipelineBuilder.BuildWrapPipeline(); var message = _transformPipeline.Wrap(_myCommand, new RequestContext(), _publication); @@ -60,13 +60,13 @@ public void When_wrapping_a_large_message() Assert.That(message.Header.DataRef, Is.Not.Null); Assert.That(message.Header.Bag.ContainsKey(ClaimCheckTransformer.CLAIM_CHECK)); Assert.That(message.Header.DataRef, Is.EqualTo((string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK])); - + _id = (string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK]; Assert.Equals($"Claim Check {_id}", message.Body.Value); Assert.That(_luggageStore.HasClaim(_id)); } - + public void Dispose() { _client.Delete(); diff --git a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message_async.cs index 8ebeeed9d1..1f5ea993be 100644 --- a/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Azure.Tests/Transformers/When_wrapping_a_large_message_async.cs @@ -28,9 +28,9 @@ public LargeMessagePayloadAsyncWrapTests() var mapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyLargeCommandMessageMapper()), null); - mapperRegistry.Register(); - - _publication = new Publication{ Topic = new RoutingKey("transform.event") }; + mapperRegistry.Register(); + + _publication = new Publication { Topic = new RoutingKey("transform.event") }; _myCommand = new MyLargeCommand(6000); var bucketName = $"brightertestbucket-{Guid.NewGuid()}"; @@ -43,16 +43,16 @@ public LargeMessagePayloadAsyncWrapTests() ContainerUri = bucketUrl, Credential = new AzureCliCredential() }); - + var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } - + [Test] public async Task When_wrapping_a_large_message_async() { await _luggageStore.EnsureStoreExistsAsync(); - + //act _transformPipeline = _pipelineBuilder.BuildWrapPipeline(); var message = await _transformPipeline.WrapAsync(_myCommand, new RequestContext(), _publication); @@ -61,13 +61,13 @@ public async Task When_wrapping_a_large_message_async() Assert.That(message.Header.DataRef, Is.Not.Null); Assert.That(message.Header.Bag.ContainsKey(ClaimCheckTransformer.CLAIM_CHECK)); Assert.That(message.Header.DataRef, Is.EqualTo((string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK])); - + _id = (string)message.Header.Bag[ClaimCheckTransformer.CLAIM_CHECK]; Assert.Equals($"Claim Check {_id}", message.Body.Value); Assert.That(await _luggageStore.HasClaimAsync(_id, CancellationToken.None)); } - + public void Dispose() { _client.Delete(); diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/AzureServiceBusChannelFactoryTests.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/AzureServiceBusChannelFactoryTests.cs index 2cbf452974..be7c48fc83 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/AzureServiceBusChannelFactoryTests.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/AzureServiceBusChannelFactoryTests.cs @@ -11,36 +11,36 @@ public class AzureServiceBusChannelFactoryTests [Fact] public void When_the_timeout_is_below_400_ms_it_should_throw_an_exception() { - var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="))); + var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var subscription = new AzureServiceBusSubscription(new SubscriptionName("name"), new ChannelName("name"), new RoutingKey("name"), bufferSize: 1, noOfPerformers: 1, messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(399)); - + ArgumentException exception = Assert.Throws(() => factory.CreateSyncChannel(subscription)); Assert.Equal("The minimum allowed timeout is 400 milliseconds", exception.Message); } - + [Fact] public void When_the_timeout_is_below_400_ms_it_should_throw_an_exception_async_channel() { - var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="))); + var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var subscription = new AzureServiceBusSubscription(new SubscriptionName("name"), new ChannelName("name"), new RoutingKey("name"), - bufferSize:1, noOfPerformers:1, messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(399)); - + bufferSize: 1, noOfPerformers: 1, messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(399)); + ArgumentException exception = Assert.Throws(() => factory.CreateAsyncChannel(subscription)); Assert.Equal("The minimum allowed timeout is 400 milliseconds", exception.Message); } - + [Fact] public async Task When_the_timeout_is_below_400_ms_it_should_throw_an_exception_async_channel_async() { - var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="))); + var factory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(new AzureServiceBusConfiguration("Endpoint=sb://someString.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=oUWJw7777s7ydjdafqFqhk9O7TOs="), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var subscription = new AzureServiceBusSubscription(new SubscriptionName("name"), new ChannelName("name"), new RoutingKey("name"), - bufferSize:1, noOfPerformers:1, messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(399)); + bufferSize: 1, noOfPerformers: 1, messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(399)); ArgumentException exception = await Assert.ThrowsAsync(() => factory.CreateAsyncChannelAsync(subscription)); diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusBulkMessageProducerTestsAsync.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusBulkMessageProducerTestsAsync.cs index 9989eb0001..c4dafef35f 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusBulkMessageProducerTestsAsync.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusBulkMessageProducerTestsAsync.cs @@ -28,14 +28,14 @@ public AzureServiceBusBulkMessageProducerTestsAsync() _producer = new AzureServiceBusTopicMessageProducer( _nameSpaceManagerWrapper, topicClientProvider, - new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create } - ); + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _queueProducer = new AzureServiceBusQueueMessageProducer( _nameSpaceManagerWrapper, topicClientProvider, - new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create } - ); + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusConsumerTestsAsync.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusConsumerTestsAsync.cs index bfbb9984d5..e615df88af 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusConsumerTestsAsync.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusConsumerTestsAsync.cs @@ -28,13 +28,13 @@ public AzureServiceBusConsumerTestsAsync() _fakeMessageProducer = new FakeMessageProducer(); _messageReceiver = new FakeServiceBusReceiverWrapper(); _fakeMessageReceiver = new FakeServiceBusReceiverProvider(_messageReceiver); - + var sub = new AzureServiceBusSubscription(routingKey: new RoutingKey("topic"), channelName: new ChannelName("subscription") - ,makeChannels: OnMissingChannel.Create, bufferSize: 10, subscriptionConfiguration: _subConfig); - + , makeChannels: OnMissingChannel.Create, bufferSize: 10, subscriptionConfiguration: _subConfig); + _azureServiceBusConsumer = new AzureServiceBusTopicConsumer(sub, _fakeMessageProducer, - _nameSpaceManagerWrapper, _fakeMessageReceiver); + _nameSpaceManagerWrapper, _fakeMessageReceiver, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -48,14 +48,14 @@ public async Task When_a_subscription_exists_and_messages_are_in_the_queue_the_m { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; - + }; + var message2 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody2"), ApplicationProperties = new Dictionary { { "MessageType", "MT_DOCUMENT" } } - }; - + }; + brokeredMessageList.Add(message1); brokeredMessageList.Add(message2); @@ -76,19 +76,19 @@ public async Task When_a_subscription_exists_and_messages_are_in_the_queue_the_m public async Task When_a_subscription_does_not_exist_and_messages_are_in_the_queue_then_the_subscription_is_created_and_messages_are_returned() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; - Message[] result =await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.FromMilliseconds(400)); - + Message[] result = await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.FromMilliseconds(400)); + await _nameSpaceManagerWrapper.SubscriptionExistsAsync("topic", "subscription"); Assert.Equal("somebody", result[0].Body.Value); } @@ -104,12 +104,12 @@ public async Task When_a_message_is_a_command_type_then_the_message_type_is_set_ { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_COMMAND" } } - }; + }; brokeredMessageList.Add(message1); - + _messageReceiver.MessageQueue = brokeredMessageList; - Message[] result =await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.FromMilliseconds(400)); + Message[] result = await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.FromMilliseconds(400)); Assert.Equal("somebody", result[0].Body.Value); Assert.Equal("topic", result[0].Header.Topic); @@ -127,7 +127,7 @@ public async Task When_a_message_is_a_command_type_and_it_is_specified_in_funny_ { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_COmmAND" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -150,7 +150,7 @@ public async Task When_the_specified_message_type_is_unknown_then_it_should_defa { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "wrong_message_type" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -170,8 +170,8 @@ public async Task When_the_message_type_is_not_specified_it_should_default_to_MT var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), - ApplicationProperties = new Dictionary() - }; + ApplicationProperties = new Dictionary() + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -195,7 +195,7 @@ public async Task When_the_user_properties_on_the_azure_sb_message_is_null_it_sh { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary() - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -232,13 +232,13 @@ public async Task When_trying_to_create_a_subscription_which_was_already_created { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.FromMilliseconds(400)); - + Assert.Equal("somebody", result[0].Body.Value); } @@ -246,7 +246,7 @@ public async Task When_trying_to_create_a_subscription_which_was_already_created public async Task When_dispose_is_called_the_close_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); await _azureServiceBusConsumer.ReceiveAsync(TimeSpan.Zero); await _azureServiceBusConsumer.DisposeAsync(); @@ -257,7 +257,7 @@ public async Task When_dispose_is_called_the_close_method_is_called() public async Task When_requeue_is_called_and_the_delay_is_zero_the_send_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _fakeMessageProducer.SentMessages.Clear(); var messageLockTokenOne = Guid.NewGuid(); var messageHeader = new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey("topic"), MessageType.MT_EVENT); @@ -273,9 +273,9 @@ public async Task When_requeue_is_called_and_the_delay_is_zero_the_send_method_i public void When_requeue_is_called_and_the_delay_is_more_than_zero_the_sendWithDelay_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _fakeMessageProducer.SentMessages.Clear(); - + var messageLockTokenOne = Guid.NewGuid(); var messageHeader = new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey("topic"), MessageType.MT_EVENT); var message = new Message(messageHeader, new MessageBody("body")); @@ -328,22 +328,23 @@ public void When_there_is_an_error_talking_to_servicebus_when_receiving_then_a_C public async Task Once_the_subscription_is_created_or_exits_it_does_not_check_if_it_exists_every_time(bool subscriptionExists) { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _messageReceiver.MessageQueue.Clear(); - if (subscriptionExists) await _nameSpaceManagerWrapper.CreateSubscriptionAsync("topic", "subscription", new()); + if (subscriptionExists) + await _nameSpaceManagerWrapper.CreateSubscriptionAsync("topic", "subscription", new()); var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + //Subscription is only created once Assert.Equal(1, _nameSpaceManagerWrapper.Topics["topic"].Count(s => s.Equals("subscription"))); @@ -354,24 +355,24 @@ public async Task Once_the_subscription_is_created_or_exits_it_does_not_check_if public void When_MessagingEntityAlreadyExistsException_does_not_check_if_subscription_exists() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _nameSpaceManagerWrapper.CreateSubscriptionException = new ServiceBusException("whatever", ServiceBusFailureReason.MessagingEntityAlreadyExists); _messageReceiver.MessageQueue.Clear(); - + var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + Assert.Equal("somebody", result[0].Body.Value); Assert.Equal(1, _nameSpaceManagerWrapper.ExistCount); @@ -381,16 +382,16 @@ public void When_MessagingEntityAlreadyExistsException_does_not_check_if_subscri public void When_a_message_contains_a_null_body_message_is_still_processed() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); - + _nameSpaceManagerWrapper.Topics.Add("topic", new()); + _messageReceiver.MessageQueue.Clear(); - + var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = null, ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); @@ -404,7 +405,7 @@ public void When_a_message_contains_a_null_body_message_is_still_processed() [Fact] public void When_receiving_messages_and_the_receiver_is_closing_a_MT_QUIT_message_is_sent() { - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _messageReceiver.Close(); Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); @@ -453,10 +454,10 @@ public void When_a_subscription_does_not_exist_and_Missing_is_set_to_Validate_a_ _nameSpaceManagerWrapper.ResetState(); var sub = new AzureServiceBusSubscription(routingKey: new RoutingKey("topic"), channelName: new ChannelName("subscription") - ,makeChannels: OnMissingChannel.Validate, subscriptionConfiguration: _subConfig); - + , makeChannels: OnMissingChannel.Validate, subscriptionConfiguration: _subConfig); + var azureServiceBusConsumerValidate = new AzureServiceBusTopicConsumer(sub, _fakeMessageProducer, - _nameSpaceManagerWrapper, _fakeMessageReceiver); + _nameSpaceManagerWrapper, _fakeMessageReceiver, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); Assert.Throws(() => azureServiceBusConsumerValidate.Receive(TimeSpan.FromMilliseconds(400))); } diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusMessageProducerTestsAsync.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusMessageProducerTestsAsync.cs index 6893c2525f..d654640227 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusMessageProducerTestsAsync.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Proactor/AzureServiceBusMessageProducerTestsAsync.cs @@ -23,19 +23,19 @@ public AzureServiceBusMessageProducerTestsAsync() _nameSpaceManagerWrapper = new FakeAdministrationClient(); _topicClient = new FakeServiceBusSenderWrapper(); _topicClientProvider = new FakeServiceBusSenderProvider(_topicClient); - + _producer = new AzureServiceBusTopicMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Create} - ); - + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _queueProducer = new AzureServiceBusQueueMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Create} - ); + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -45,12 +45,12 @@ public async Task When_the_topic_exists_and_sending_a_message_with_no_delay_it_s _nameSpaceManagerWrapper.ResetState(); _nameSpaceManagerWrapper.Topics.Add("topic", []); - + await _producer.SendAsync(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -70,12 +70,12 @@ public async Task When_sending_a_command_message_type_message_with_no_delay_it_s _nameSpaceManagerWrapper.Queues.Add("topic"); var producer = useQueues ? _queueProducer : _producer; - + await producer.SendAsync(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -93,11 +93,11 @@ public async Task When_the_topic_does_not_exist_it_should_be_created_and_the_mes _nameSpaceManagerWrapper.ResetState(); var producer = useQueues ? _queueProducer : _producer; - + await producer.SendAsync(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json)))); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(1, _nameSpaceManagerWrapper.CreateCount); @@ -118,9 +118,9 @@ public async Task When_a_message_is_send_and_an_exception_occurs_close_is_still_ try { var producer = useQueues ? _queueProducer : _producer; - + await producer.SendAsync(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody("Message", new ContentType(MediaTypeNames.Application.Json)))); } catch (Exception) @@ -143,12 +143,12 @@ public async Task When_the_topic_exists_and_sending_a_message_with_a_delay_it_sh _nameSpaceManagerWrapper.Queues.Add("topic"); var producer = useQueues ? _queueProducer : _producer; - + await producer.SendWithDelayAsync( new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -172,7 +172,7 @@ public async Task When_sending_a_command_message_type_message_with_delay_it_shou await producer.SendWithDelayAsync(new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -193,12 +193,12 @@ public async Task When_the_topic_does_not_exist_and_sending_a_message_with_a_del await producer.SendWithDelayAsync(new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), - new MessageBody(messageBody,new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(1, _nameSpaceManagerWrapper.CreateCount); - + Assert.Equal(messageBody, sentMessage.Body.ToArray()); Assert.Equal(1, _topicClient.ClosedCount); } @@ -216,18 +216,18 @@ public async Task Once_the_topic_is_created_it_then_does_not_check_if_it_exists_ if (topicExists) { _nameSpaceManagerWrapper.Topics.Add("topic", []); - _nameSpaceManagerWrapper.Queues.Add("topic"); + _nameSpaceManagerWrapper.Queues.Add("topic"); } var producer = useQueues ? _queueProducer : _producer; var routingKey = new RoutingKey("topic"); - + await producer.SendWithDelayAsync(new Message( - new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), + new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); await producer.SendWithDelayAsync(new Message( - new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), + new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); if (topicExists == false) @@ -246,10 +246,10 @@ public async Task When_there_is_an_error_talking_to_servicebus_when_creating_the _nameSpaceManagerWrapper.ExistsException = new Exception(); var producer = useQueues ? _queueProducer : _producer; - + await Assert.ThrowsAsync(() => producer.SendWithDelayAsync( new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)) ); Assert.Equal(1, _nameSpaceManagerWrapper.ResetCount); @@ -270,9 +270,9 @@ public void When_there_is_an_error_getting_a_topic_client_the_connection_for_top _topicClientProvider.SingleThrowGetException = new Exception(); var producer = useQueues ? _queueProducer : _producer; - + producer.SendWithDelay(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); @@ -285,14 +285,14 @@ public async Task When_the_topic_does_not_exist_and_Missing_is_set_to_Validate_a var messageBody = Encoding.UTF8.GetBytes("A message body"); var producerValidate = new AzureServiceBusTopicMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Validate}) + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Validate }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ; await Assert.ThrowsAsync(() => producerValidate.SendAsync( new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json)))) ); } diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusConsumerTests.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusConsumerTests.cs index 2ca1185e64..44b9036ccc 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusConsumerTests.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusConsumerTests.cs @@ -28,13 +28,13 @@ public AzureServiceBusConsumerTests() _fakeMessageProducer = new FakeMessageProducer(); _messageReceiver = new FakeServiceBusReceiverWrapper(); _fakeMessageReceiver = new FakeServiceBusReceiverProvider(_messageReceiver); - + var sub = new AzureServiceBusSubscription(routingKey: new RoutingKey("topic"), channelName: new ChannelName("subscription") - ,makeChannels: OnMissingChannel.Create, bufferSize: 10, subscriptionConfiguration: _subConfig); - + , makeChannels: OnMissingChannel.Create, bufferSize: 10, subscriptionConfiguration: _subConfig); + _azureServiceBusConsumer = new AzureServiceBusTopicConsumer(sub, _fakeMessageProducer, - _nameSpaceManagerWrapper, _fakeMessageReceiver); + _nameSpaceManagerWrapper, _fakeMessageReceiver, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -48,14 +48,14 @@ public void When_a_subscription_exists_and_messages_are_in_the_queue_the_message { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; - + }; + var message2 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody2"), ApplicationProperties = new Dictionary { { "MessageType", "MT_DOCUMENT" } } - }; - + }; + brokeredMessageList.Add(message1); brokeredMessageList.Add(message2); @@ -76,19 +76,19 @@ public void When_a_subscription_exists_and_messages_are_in_the_queue_the_message public async Task When_a_subscription_does_not_exist_and_messages_are_in_the_queue_then_the_subscription_is_created_and_messages_are_returned() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + await _nameSpaceManagerWrapper.SubscriptionExistsAsync("topic", "subscription"); //A.CallTo(() => _nameSpaceManagerWrapper.f => f.CreateSubscription("topic", "subscription", _subConfig)).MustHaveHappened(); Assert.Equal("somebody", result[0].Body.Value); @@ -105,9 +105,9 @@ public void When_a_message_is_a_command_type_then_the_message_type_is_set_correc { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_COMMAND" } } - }; + }; brokeredMessageList.Add(message1); - + _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); @@ -128,7 +128,7 @@ public void When_a_message_is_a_command_type_and_it_is_specified_in_funny_casing { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_COmmAND" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -151,7 +151,7 @@ public void When_the_specified_message_type_is_unknown_then_it_should_default_to { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "wrong_message_type" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -171,8 +171,8 @@ public void When_the_message_type_is_not_specified_it_should_default_to_MT_EVENT var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), - ApplicationProperties = new Dictionary() - }; + ApplicationProperties = new Dictionary() + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -196,7 +196,7 @@ public void When_the_user_properties_on_the_azure_sb_message_is_null_it_should_d { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary() - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; @@ -233,13 +233,13 @@ public void When_trying_to_create_a_subscription_which_was_already_created_by_an { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + Assert.Equal("somebody", result[0].Body.Value); } @@ -247,7 +247,7 @@ public void When_trying_to_create_a_subscription_which_was_already_created_by_an public void When_dispose_is_called_the_close_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _azureServiceBusConsumer.Receive(TimeSpan.Zero); _azureServiceBusConsumer.Dispose(); @@ -258,7 +258,7 @@ public void When_dispose_is_called_the_close_method_is_called() public void When_requeue_is_called_and_the_delay_is_zero_the_send_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _fakeMessageProducer.SentMessages.Clear(); var messageLockTokenOne = Guid.NewGuid(); var messageHeader = new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey("topic"), MessageType.MT_EVENT); @@ -274,9 +274,9 @@ public void When_requeue_is_called_and_the_delay_is_zero_the_send_method_is_call public void When_requeue_is_called_and_the_delay_is_more_than_zero_the_sendWithDelay_method_is_called() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _fakeMessageProducer.SentMessages.Clear(); - + var messageLockTokenOne = Guid.NewGuid(); var messageHeader = new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey("topic"), MessageType.MT_EVENT); var message = new Message(messageHeader, new MessageBody("body")); @@ -329,22 +329,23 @@ public void When_there_is_an_error_talking_to_servicebus_when_receiving_then_a_C public async Task Once_the_subscription_is_created_or_exits_it_does_not_check_if_it_exists_every_time(bool subscriptionExists) { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _messageReceiver.MessageQueue.Clear(); - if (subscriptionExists) await _nameSpaceManagerWrapper.CreateSubscriptionAsync("topic", "subscription", new()); + if (subscriptionExists) + await _nameSpaceManagerWrapper.CreateSubscriptionAsync("topic", "subscription", new()); var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + //Subscription is only created once Assert.Equal(1, _nameSpaceManagerWrapper.Topics["topic"].Count(s => s.Equals("subscription"))); @@ -355,24 +356,24 @@ public async Task Once_the_subscription_is_created_or_exits_it_does_not_check_if public void When_MessagingEntityAlreadyExistsException_does_not_check_if_subscription_exists() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _nameSpaceManagerWrapper.CreateSubscriptionException = new ServiceBusException("whatever", ServiceBusFailureReason.MessagingEntityAlreadyExists); _messageReceiver.MessageQueue.Clear(); - + var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = Encoding.UTF8.GetBytes("somebody"), ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); _messageReceiver.MessageQueue = brokeredMessageList; Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); - + Assert.Equal("somebody", result[0].Body.Value); Assert.Equal(1, _nameSpaceManagerWrapper.ExistCount); @@ -382,16 +383,16 @@ public void When_MessagingEntityAlreadyExistsException_does_not_check_if_subscri public void When_a_message_contains_a_null_body_message_is_still_processed() { _nameSpaceManagerWrapper.ResetState(); - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); - + _nameSpaceManagerWrapper.Topics.Add("topic", new()); + _messageReceiver.MessageQueue.Clear(); - + var brokeredMessageList = new List(); var message1 = new BrokeredMessage() { MessageBodyValue = null, ApplicationProperties = new Dictionary { { "MessageType", "MT_EVENT" } } - }; + }; brokeredMessageList.Add(message1); @@ -405,7 +406,7 @@ public void When_a_message_contains_a_null_body_message_is_still_processed() [Fact] public void When_receiving_messages_and_the_receiver_is_closing_a_MT_QUIT_message_is_sent() { - _nameSpaceManagerWrapper.Topics.Add("topic", new ()); + _nameSpaceManagerWrapper.Topics.Add("topic", new()); _messageReceiver.Close(); Message[] result = _azureServiceBusConsumer.Receive(TimeSpan.FromMilliseconds(400)); @@ -454,10 +455,10 @@ public void When_a_subscription_does_not_exist_and_Missing_is_set_to_Validate_a_ _nameSpaceManagerWrapper.ResetState(); var sub = new AzureServiceBusSubscription(routingKey: new RoutingKey("topic"), channelName: new ChannelName("subscription") - ,makeChannels: OnMissingChannel.Validate, subscriptionConfiguration: _subConfig); - + , makeChannels: OnMissingChannel.Validate, subscriptionConfiguration: _subConfig); + var azureServiceBusConsumerValidate = new AzureServiceBusTopicConsumer(sub, _fakeMessageProducer, - _nameSpaceManagerWrapper, _fakeMessageReceiver); + _nameSpaceManagerWrapper, _fakeMessageReceiver, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); Assert.Throws(() => azureServiceBusConsumerValidate.Receive(TimeSpan.FromMilliseconds(400))); } diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusMessageProducerTests.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusMessageProducerTests.cs index 3a0233dba6..4425a2c61a 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusMessageProducerTests.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/Reactor/AzureServiceBusMessageProducerTests.cs @@ -23,19 +23,19 @@ public AzureServiceBusMessageProducerTests() _nameSpaceManagerWrapper = new FakeAdministrationClient(); _topicClient = new FakeServiceBusSenderWrapper(); _topicClientProvider = new FakeServiceBusSenderProvider(_topicClient); - + _producer = new AzureServiceBusTopicMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Create} - ); - + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _queueProducer = new AzureServiceBusQueueMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Create} - ); + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Create }, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -45,12 +45,12 @@ public void When_the_topic_exists_and_sending_a_message_with_no_delay_it_should_ _nameSpaceManagerWrapper.ResetState(); _nameSpaceManagerWrapper.Topics.Add("topic", []); - + _producer.Send(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -70,12 +70,12 @@ public void When_sending_a_command_message_type_message_with_no_delay_it_should_ _nameSpaceManagerWrapper.Queues.Add("topic"); var producer = useQueues ? _queueProducer : _producer; - + producer.Send(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -93,11 +93,11 @@ public void When_the_topic_does_not_exist_it_should_be_created_and_the_message_i _nameSpaceManagerWrapper.ResetState(); var producer = useQueues ? _queueProducer : _producer; - + producer.Send(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json)))); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(1, _nameSpaceManagerWrapper.CreateCount); @@ -118,9 +118,9 @@ public void When_a_message_is_send_and_an_exception_occurs_close_is_still_called try { var producer = useQueues ? _queueProducer : _producer; - + producer.Send(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody("Message", new ContentType(MediaTypeNames.Application.Json)))); } catch (Exception) @@ -144,12 +144,12 @@ public void _nameSpaceManagerWrapper.Queues.Add("topic"); var producer = useQueues ? _queueProducer : _producer; - + producer.SendWithDelay( new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_EVENT), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -175,7 +175,7 @@ public void producer.SendWithDelay(new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_COMMAND), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(messageBody, sentMessage.Body.ToArray()); @@ -199,11 +199,11 @@ public void producer.SendWithDelay(new Message( new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); - + ServiceBusMessage sentMessage = _topicClient.SentMessages.First(); Assert.Equal(1, _nameSpaceManagerWrapper.CreateCount); - + Assert.Equal(messageBody, sentMessage.Body.ToArray()); Assert.Equal(1, _topicClient.ClosedCount); } @@ -221,18 +221,18 @@ public void Once_the_topic_is_created_it_then_does_not_check_if_it_exists_every_ if (topicExists) { _nameSpaceManagerWrapper.Topics.Add("topic", []); - _nameSpaceManagerWrapper.Queues.Add("topic"); + _nameSpaceManagerWrapper.Queues.Add("topic"); } var producer = useQueues ? _queueProducer : _producer; var routingKey = new RoutingKey("topic"); - + producer.SendWithDelay(new Message( - new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), + new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); producer.SendWithDelay(new Message( - new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), + new MessageHeader(Id.Random(), routingKey, MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)); if (topicExists == false) @@ -251,10 +251,10 @@ public async Task When_there_is_an_error_talking_to_servicebus_when_creating_the _nameSpaceManagerWrapper.ExistsException = new Exception(); var producer = useQueues ? _queueProducer : _producer; - + await Assert.ThrowsAsync(() => producer.SendWithDelayAsync( new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))), TimeSpan.FromSeconds(1)) ); Assert.Equal(1, _nameSpaceManagerWrapper.ResetCount); @@ -275,9 +275,9 @@ public void When_there_is_an_error_getting_a_topic_client_the_connection_for_top _topicClientProvider.SingleThrowGetException = new Exception(); var producer = useQueues ? _queueProducer : _producer; - + producer.SendWithDelay(new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json))) ); @@ -290,14 +290,14 @@ public async Task When_the_topic_does_not_exist_and_Missing_is_set_to_Validate_a var messageBody = Encoding.UTF8.GetBytes("A message body"); var producerValidate = new AzureServiceBusTopicMessageProducer( - _nameSpaceManagerWrapper, - _topicClientProvider, - new AzureServiceBusPublication{MakeChannels = OnMissingChannel.Validate}) + _nameSpaceManagerWrapper, + _topicClientProvider, + new AzureServiceBusPublication { MakeChannels = OnMissingChannel.Validate }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ; await Assert.ThrowsAsync(() => producerValidate.SendAsync( new Message( - new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), + new MessageHeader(Id.Random(), new RoutingKey("topic"), MessageType.MT_NONE), new MessageBody(messageBody, new ContentType(MediaTypeNames.Application.Json)))) ); } diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_A_Deferred_Message_Is_Redelivered.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_A_Deferred_Message_Is_Redelivered.cs index e2be7673b9..49207f82cc 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_A_Deferred_Message_Is_Redelivered.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_A_Deferred_Message_Is_Redelivered.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -29,7 +29,7 @@ public When_A_Deferred_Message_Is_Redelivered() routingKey: new RoutingKey("test-topic"), messagePumpType: MessagePumpType.Reactor); - _creator = new AzureServiceBusMessageCreator(subscription); + _creator = new AzureServiceBusMessageCreator(subscription, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Creating_Message_From_ServiceBus_Should_Use_Memory.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Creating_Message_From_ServiceBus_Should_Use_Memory.cs index 89d6294b2b..007bd44045 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Creating_Message_From_ServiceBus_Should_Use_Memory.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Creating_Message_From_ServiceBus_Should_Use_Memory.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Paramore.Brighter.AzureServiceBus.Tests.TestDoubles; @@ -20,7 +20,7 @@ public AzureServiceBusMessageMemoryTests() routingKey: new RoutingKey("test-topic"), messagePumpType: MessagePumpType.Reactor); - _creator = new AzureServiceBusMessageCreator(subscription); + _creator = new AzureServiceBusMessageCreator(subscription, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Mapping_Message_SequenceNumber_Is_Added_To_Bag.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Mapping_Message_SequenceNumber_Is_Added_To_Bag.cs index 90cd1d911c..4e712a17be 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Mapping_Message_SequenceNumber_Is_Added_To_Bag.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_Mapping_Message_SequenceNumber_Is_Added_To_Bag.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Paramore.Brighter.AzureServiceBus.Tests.TestDoubles; @@ -23,7 +23,7 @@ public AzureServiceBusMessageSequenceNumberTests() routingKey: new RoutingKey("test-topic"), messagePumpType: MessagePumpType.Reactor); - _creator = new AzureServiceBusMessageCreator(subscription); + _creator = new AzureServiceBusMessageCreator(subscription, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_consuming_a_message_via_the_consumer.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_consuming_a_message_via_the_consumer.cs index 7d73b7def3..12e4feb742 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_consuming_a_message_via_the_consumer.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_consuming_a_message_via_the_consumer.cs @@ -34,11 +34,11 @@ public ASBConsumerTests() CommandValue = "Do the things.", CommandNumber = 26 }; - + _channelName = "test-channel"; _topicName = $"Consumer-Tests-{Guid.NewGuid()}"; var routingKey = new RoutingKey(_topicName); - + AzureServiceBusSubscription subscription = new( subscriptionName: new SubscriptionName(_channelName), channelName: new ChannelName(_channelName), @@ -90,7 +90,7 @@ public ASBConsumerTests() }; var clientProvider = ASBCreds.ASBClientProvider; - _administrationClient = new AdministrationClientWrapper(clientProvider); + _administrationClient = new AdministrationClientWrapper(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _administrationClient.CreateSubscriptionAsync(_topicName, _channelName, _subscriptionConfiguration) .GetAwaiter() .GetResult(); @@ -98,18 +98,18 @@ public ASBConsumerTests() _serviceBusClient = clientProvider.GetServiceBusClient(); var channelFactory = - new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider)); + new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); _channel = channelFactory.CreateSyncChannel(subscription); _producerRegistry = new AzureServiceBusProducerRegistryFactory( clientProvider, [ new AzureServiceBusPublication { Topic = new RoutingKey(_topicName) } - ] - ) + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); } - + [Fact] public async Task When_receiving_a_message_via_the_consumer() { @@ -135,14 +135,14 @@ public async Task When_receiving_a_message_via_the_consumer() Assert.Equal(_message.Header.DataSchema, message.Header.DataSchema); Assert.Equal(_message.Header.Subject, message.Header.Subject); Assert.Equal(_message.Header.HandledCount, message.Header.HandledCount); - Assert.Equal(_message.Header.Delayed.TotalMilliseconds, message.Header.Delayed.TotalMilliseconds) ; + Assert.Equal(_message.Header.Delayed.TotalMilliseconds, message.Header.Delayed.TotalMilliseconds); Assert.Equal(_message.Header.TraceParent?.Value, message.Header.TraceParent?.Value); Assert.Equal(_message.Header.TraceState?.Value, message.Header.TraceState?.Value); Assert.Equal(MessageHeader.DefaultSpecVersion, message.Header.SpecVersion); Assert.Equal(_message.Header.Baggage, message.Header.Baggage); - + Assert.Equal(_message.Body.Value, message.Body.Value); - + Assert.False(message.Redelivered); //clear the channel diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_large_message_via_the_producer.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_large_message_via_the_producer.cs index 2649aa9e95..bbbaaed3f6 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_large_message_via_the_producer.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_large_message_via_the_producer.cs @@ -53,7 +53,7 @@ public LargeAsbMessageProducerTests() subscriptionName: new SubscriptionName(queueChannelName), channelName: new ChannelName(queueChannelName), routingKey: queueRoutingKey, - subscriptionConfiguration : new AzureServiceBusSubscriptionConfiguration() + subscriptionConfiguration: new AzureServiceBusSubscriptionConfiguration() { UseServiceBusQueue = true } @@ -62,7 +62,7 @@ public LargeAsbMessageProducerTests() _contentType = new ContentType(MediaTypeNames.Application.Json); var clientProvider = ASBCreds.ASBClientProvider; - _administrationClient = new AdministrationClientWrapper(clientProvider); + _administrationClient = new AdministrationClientWrapper(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _administrationClient.CreateQueueAsync(_queueName, TimeSpan.FromMinutes(5), 3000).GetAwaiter().GetResult(); _administrationClient.CreateTopicAsync(_topicName, TimeSpan.FromMinutes(5), 3000).GetAwaiter().GetResult(); _administrationClient.CreateSubscriptionAsync(_topicName, channelName, new AzureServiceBusSubscriptionConfiguration()) @@ -70,7 +70,7 @@ public LargeAsbMessageProducerTests() .GetResult(); var channelFactory = - new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider)); + new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); _topicChannel = channelFactory.CreateSyncChannel(subscription); _queueChannel = channelFactory.CreateSyncChannel(queueSubscription); @@ -79,8 +79,8 @@ public LargeAsbMessageProducerTests() [ new AzureServiceBusPublication { Topic = new RoutingKey(_topicName) }, new AzureServiceBusPublication { Topic = new RoutingKey(_queueName), UseServiceBusQueue = true} - ] - ) + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); } @@ -127,7 +127,7 @@ public async Task When_posting_a_large_message_via_the_bulk_producer(bool testQu } private Message GenerateMessage(string topicName) => new Message( - new MessageHeader(_command.Id, new RoutingKey( topicName), MessageType.MT_COMMAND, correlationId:_correlationId, + new MessageHeader(_command.Id, new RoutingKey(topicName), MessageType.MT_COMMAND, correlationId: _correlationId, contentType: _contentType ), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) diff --git a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_message_via_the_producer.cs b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_message_via_the_producer.cs index ccadd8ae3f..a1fd19fde4 100644 --- a/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_message_via_the_producer.cs +++ b/tests/Paramore.Brighter.AzureServiceBus.Tests/MessagingGateway/When_posting_a_message_via_the_producer.cs @@ -52,7 +52,7 @@ public ASBProducerTests() subscriptionName: new SubscriptionName(queueChannelName), channelName: new ChannelName(queueChannelName), routingKey: queueRoutingKey, - subscriptionConfiguration : new AzureServiceBusSubscriptionConfiguration() + subscriptionConfiguration: new AzureServiceBusSubscriptionConfiguration() { UseServiceBusQueue = true } @@ -61,13 +61,13 @@ public ASBProducerTests() _contentType = new ContentType(MediaTypeNames.Application.Json); var clientProvider = ASBCreds.ASBClientProvider; - _administrationClient = new AdministrationClientWrapper(clientProvider); + _administrationClient = new AdministrationClientWrapper(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _administrationClient.CreateSubscriptionAsync(_topicName, channelName, new AzureServiceBusSubscriptionConfiguration()) .GetAwaiter() .GetResult(); var channelFactory = - new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider)); + new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(clientProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); _topicChannel = channelFactory.CreateSyncChannel(subscription); _queueChannel = channelFactory.CreateSyncChannel(queueSubscription); @@ -76,8 +76,8 @@ public ASBProducerTests() [ new AzureServiceBusPublication { Topic = new RoutingKey(_topicName) }, new AzureServiceBusPublication { Topic = new RoutingKey(_queueName), UseServiceBusQueue = true} - ] - ) + ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Create(); } @@ -163,7 +163,7 @@ public async Task When_posting_a_message_via_the_bulk_producer(bool testQueues) } private Message GenerateMessage(string topicName) => new Message( - new MessageHeader(_command.Id, new RoutingKey( topicName), MessageType.MT_COMMAND, correlationId:_correlationId, + new MessageHeader(_command.Id, new RoutingKey(topicName), MessageType.MT_COMMAND, correlationId: _correlationId, contentType: _contentType ), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_base_migrate_runs_with_a_tracer_it_should_emit_a_migration_span.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_base_migrate_runs_with_a_tracer_it_should_emit_a_migration_span.cs index 1a30b0615a..78b4eaa2cb 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_base_migrate_runs_with_a_tracer_it_should_emit_a_migration_span.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_base_migrate_runs_with_a_tracer_it_should_emit_a_migration_span.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -88,7 +88,7 @@ await runner.MigrateAsync( tableName: "Orders", schemaName: "dbo", boxType: BoxType.Outbox, - tableState:new BoxTableState(false, false, 0)); + tableState: new BoxTableState(false, false, 0)); _tracerProvider.ForceFlush(); @@ -133,7 +133,7 @@ await runner.MigrateAsync( tableName: "Orders", schemaName: null, boxType: BoxType.Inbox, - tableState:new BoxTableState(true, false, 0)); + tableState: new BoxTableState(true, false, 0)); _tracerProvider.ForceFlush(); @@ -171,7 +171,7 @@ await runner.MigrateAsync( tableName: "Orders", schemaName: "dbo", boxType: BoxType.Outbox, - tableState:new BoxTableState(true, true, 7)); + tableState: new BoxTableState(true, true, 7)); _tracerProvider.ForceFlush(); @@ -210,7 +210,7 @@ await runner.MigrateAsync( tableName: "Orders", schemaName: null, boxType: BoxType.Outbox, - tableState:new BoxTableState(false, false, 0)); + tableState: new BoxTableState(false, false, 0)); _tracerProvider.ForceFlush(); @@ -237,7 +237,7 @@ await runner.MigrateAsync( tableName: "Orders", schemaName: null, boxType: BoxType.Outbox, - tableState:new BoxTableState(false, false, 0)); + tableState: new BoxTableState(false, false, 0)); _tracerProvider.ForceFlush(); @@ -258,7 +258,7 @@ public ObservabilityTestRunner(ObservabilityTestUnitOfWork unitOfWork, IAmABrigh new StubBoxMigrationCatalog(), new StubRelationalDatabaseConfiguration(), TimeSpan.FromSeconds(30), - logger: null, + logger: global::Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, tracer: tracer) { _unitOfWork = unitOfWork; diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_bootstrap_fails_it_should_record_exception_on_activity.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_bootstrap_fails_it_should_record_exception_on_activity.cs index 9c8e3de0d3..79262c46d3 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_bootstrap_fails_it_should_record_exception_on_activity.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_relational_box_migration_runner_bootstrap_fails_it_should_record_exception_on_activity.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -163,7 +163,7 @@ public ThrowingBootstrapRunner( new StubBoxMigrationCatalog(), new StubRelationalDatabaseConfiguration(), TimeSpan.FromSeconds(30), - logger: null, + logger: global::Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, tracer: tracer) { _openConnectionThrow = openConnectionThrow; @@ -177,14 +177,16 @@ public ThrowingBootstrapRunner( protected override Task OpenConnectionAsync(CancellationToken cancellationToken) { - if (_openConnectionThrow is not null) throw _openConnectionThrow; + if (_openConnectionThrow is not null) + throw _openConnectionThrow; return Task.FromResult(new FakeDbConnection()); } protected override Task> CreateUnitOfWorkAsync( FakeDbConnection connection, string? schemaName, string tableName, CancellationToken cancellationToken) { - if (_createUnitOfWorkThrow is not null) throw _createUnitOfWorkThrow; + if (_createUnitOfWorkThrow is not null) + throw _createUnitOfWorkThrow; return Task.FromResult>( new ThrowOnBeginUnitOfWork(_beginAsyncThrow)); } diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_detect_table_state_inlines_negative_version_clamp.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_detect_table_state_inlines_negative_version_clamp.cs index a661cf3776..9e7f6c9ae7 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_detect_table_state_inlines_negative_version_clamp.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_detect_table_state_inlines_negative_version_clamp.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -104,7 +104,8 @@ public TestSqlBoxProvisioner( IAmARelationalDatabaseConfiguration configuration, IAmABoxMigrationRunner migrationRunner, BoxType boxType) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_effective_schema_name_is_overridden_it_should_propagate_to_detection_and_payload_calls_only.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_effective_schema_name_is_overridden_it_should_propagate_to_detection_and_payload_calls_only.cs index b5cd63a796..0fb71e86f1 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_effective_schema_name_is_overridden_it_should_propagate_to_detection_and_payload_calls_only.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_effective_schema_name_is_overridden_it_should_propagate_to_detection_and_payload_calls_only.cs @@ -1,4 +1,4 @@ -#region Licence +#region Licence /* The MIT License (MIT) Copyright © 2026 Ian Cooper @@ -115,7 +115,8 @@ public TestSqlBoxProvisionerWithDefaultSchema( IAmARelationalDatabaseConfiguration configuration, IAmABoxMigrationRunner migrationRunner, BoxType boxType) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } @@ -138,7 +139,8 @@ public TestSqlBoxProvisionerWithNullSchema( IAmARelationalDatabaseConfiguration configuration, IAmABoxMigrationRunner migrationRunner, BoxType boxType) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_receives_unsafe_identifier_it_should_throw_before_opening_connection.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_receives_unsafe_identifier_it_should_throw_before_opening_connection.cs index f653bc78d4..3c19a3bad2 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_receives_unsafe_identifier_it_should_throw_before_opening_connection.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_receives_unsafe_identifier_it_should_throw_before_opening_connection.cs @@ -109,7 +109,8 @@ public IdentifierProbeProvisioner(IAmARelationalDatabaseConfiguration configurat new ThrowingPayloadValidator(), configuration, new ThrowingMigrationRunner(), - BoxType.Outbox) + BoxType.Outbox, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_runs_successfully_it_should_invoke_hooks_in_documented_order.cs b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_runs_successfully_it_should_invoke_hooks_in_documented_order.cs index a5be5dea90..555c06d773 100644 --- a/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_runs_successfully_it_should_invoke_hooks_in_documented_order.cs +++ b/tests/Paramore.Brighter.BoxProvisioning.Tests/When_sql_box_provisioner_provision_async_runs_successfully_it_should_invoke_hooks_in_documented_order.cs @@ -184,7 +184,8 @@ public TestSqlBoxProvisioner( IAmABoxMigrationRunner migrationRunner, BoxType boxType, List log) - : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType) + : base(detectionHelper, catalog, payloadValidator, configuration, migrationRunner, boxType, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { _log = log; } diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox.cs index 3ac0476d6c..d64060fdf5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox.cs @@ -25,8 +25,8 @@ public ServiceBusMessageStoreArchiverTests() _archiver = new OutboxArchiver( _outbox, - _archiveProvider - ); + _archiveProvider, + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox_Async.cs index 91c1e1b278..4856e2911b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_Archiving_Old_Messages_From_The_Outbox_Async.cs @@ -23,7 +23,7 @@ public ServiceBusMessageStoreArchiverTestsAsync() _outbox = new InMemoryOutbox(_timeProvider){Tracer = tracer}; _archiveProvider = new InMemoryArchiveProvider(); - _archiver = new OutboxArchiver(_outbox, _archiveProvider); + _archiver = new OutboxArchiver(_outbox, _archiveProvider, loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_async_only_outbox_should_call_async_archive.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_async_only_outbox_should_call_async_archive.cs index cde93ba74c..649aabfe93 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_async_only_outbox_should_call_async_archive.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_async_only_outbox_should_call_async_archive.cs @@ -21,14 +21,14 @@ public async Task When_archiving_with_async_only_outbox_should_call_async_archiv var innerOutbox = new InMemoryOutbox(timeProvider) { Tracer = new BrighterTracer() }; var asyncOnlyOutbox = new AsyncOnlyOutboxWrapper(innerOutbox); var archiveProvider = new InMemoryArchiveProvider(); - var archiver = new OutboxArchiver(asyncOnlyOutbox, archiveProvider); + var archiver = new OutboxArchiver(asyncOnlyOutbox, archiveProvider, loggerFactory: Initializer.TestLoggerFactory); var distributedLock = new InMemoryLock(); var options = new TimedOutboxArchiverOptions { TimerInterval = 5, MinimumAge = TimeSpan.FromMilliseconds(500) }; - var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options); + var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); var context = new RequestContext(); var routingKey = new RoutingKey("test-topic"); diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_both_sync_and_async_outbox_should_prefer_async.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_both_sync_and_async_outbox_should_prefer_async.cs index e5a8b2b475..069780d4cd 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_both_sync_and_async_outbox_should_prefer_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_both_sync_and_async_outbox_should_prefer_async.cs @@ -19,14 +19,14 @@ public async Task When_archiving_with_both_sync_and_async_outbox_should_prefer_a var timeProvider = new FakeTimeProvider(); var outbox = new InMemoryOutbox(timeProvider) { Tracer = new BrighterTracer() }; var archiveProvider = new InMemoryArchiveProvider(); - var archiver = new OutboxArchiver(outbox, archiveProvider); + var archiver = new OutboxArchiver(outbox, archiveProvider, loggerFactory: Initializer.TestLoggerFactory); var distributedLock = new InMemoryLock(); var options = new TimedOutboxArchiverOptions { TimerInterval = 5, MinimumAge = TimeSpan.FromMilliseconds(500) }; - var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options); + var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); var context = new RequestContext(); var routingKey = new RoutingKey("test-topic"); diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_no_outbox_configured_should_log_warning.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_no_outbox_configured_should_log_warning.cs index 7afb1eac0f..4bc234bf53 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_no_outbox_configured_should_log_warning.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_no_outbox_configured_should_log_warning.cs @@ -16,14 +16,14 @@ public async Task When_archiving_with_no_outbox_configured_should_not_throw() //Arrange — NullOutbox implements only IAmAnOutbox (neither sync nor async) var nullOutbox = new NullOutbox(); var archiveProvider = new InMemoryArchiveProvider(); - var archiver = new OutboxArchiver(nullOutbox, archiveProvider); + var archiver = new OutboxArchiver(nullOutbox, archiveProvider, loggerFactory: Initializer.TestLoggerFactory); var distributedLock = new InMemoryLock(); var options = new TimedOutboxArchiverOptions { TimerInterval = 5, MinimumAge = TimeSpan.FromMilliseconds(500) }; - var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options); + var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); //Act — should complete without throwing (FR3) using var cts = new CancellationTokenSource(); diff --git a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_sync_only_outbox_should_call_sync_archive.cs b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_sync_only_outbox_should_call_sync_archive.cs index c1ee06ceb4..1e50dcc5d4 100644 --- a/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_sync_only_outbox_should_call_sync_archive.cs +++ b/tests/Paramore.Brighter.Core.Tests/Archiving/When_archiving_with_sync_only_outbox_should_call_sync_archive.cs @@ -21,14 +21,14 @@ public async Task When_archiving_with_sync_only_outbox_should_call_sync_archive( var innerOutbox = new InMemoryOutbox(timeProvider) { Tracer = new BrighterTracer() }; var syncOnlyOutbox = new SyncOnlyOutboxWrapper(innerOutbox); var archiveProvider = new InMemoryArchiveProvider(); - var archiver = new OutboxArchiver(syncOnlyOutbox, archiveProvider); + var archiver = new OutboxArchiver(syncOnlyOutbox, archiveProvider, loggerFactory: Initializer.TestLoggerFactory); var distributedLock = new InMemoryLock(); var options = new TimedOutboxArchiverOptions { TimerInterval = 5, MinimumAge = TimeSpan.FromMilliseconds(500) }; - var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options); + var timedArchiver = new TimedOutboxArchiver(archiver, distributedLock, options, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); var context = new RequestContext(); var routingKey = new RoutingKey("test-topic"); diff --git a/tests/Paramore.Brighter.Core.Tests/BoxProvisioning/When_using_box_provisioning_extension_it_should_register_hosted_service_and_provisioners.cs b/tests/Paramore.Brighter.Core.Tests/BoxProvisioning/When_using_box_provisioning_extension_it_should_register_hosted_service_and_provisioners.cs index 8ab110c40f..864dbb6491 100644 --- a/tests/Paramore.Brighter.Core.Tests/BoxProvisioning/When_using_box_provisioning_extension_it_should_register_hosted_service_and_provisioners.cs +++ b/tests/Paramore.Brighter.Core.Tests/BoxProvisioning/When_using_box_provisioning_extension_it_should_register_hosted_service_and_provisioners.cs @@ -13,7 +13,7 @@ public class When_using_box_provisioning_extension_it_should_register_hosted_ser public void Should_register_hosted_service_and_provisioners() { //Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddLogging(); var builder = new StubBrighterBuilder(services); diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message.cs index d4aeeb5ade..694edee26a 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message.cs @@ -35,7 +35,7 @@ public LargeMessagePayloadUnwrapTests() var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message_async.cs index 92fe7fcdf5..6e4b73c8e5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_unwrapping_a_large_message_async.cs @@ -37,7 +37,7 @@ public LargeMessagePayloadAsyncUnwrapTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message.cs index 0edbc3164b..9e77073b50 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message.cs @@ -41,7 +41,7 @@ public LargeMessagePayloadWrapTests() _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactoryAsync); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactoryAsync, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message_async.cs index f17ee96eae..3d1fef15cb 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/FileSystem/When_wrapping_a_large_message_async.cs @@ -42,7 +42,7 @@ public LargeMessagePayloadAsyncWrapTests() _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message.cs index 953699d2e3..95cdb108d5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message.cs @@ -27,7 +27,7 @@ public LargeMessagePaylodUnwrapTests() _inMemoryStorageProvider = new InMemoryStorageProvider(); var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => new ClaimCheckTransformer(_inMemoryStorageProvider, _inMemoryStorageProvider)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message_async.cs index 50eac06b41..736c7d91b3 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_unwrapping_a_large_message_async.cs @@ -30,7 +30,7 @@ public AsyncLargeMessagePaylodUnwrapTests() _inMemoryStorageProviderAsync = new InMemoryStorageProvider(); var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_inMemoryStorageProviderAsync, _inMemoryStorageProviderAsync)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message.cs index 1ef2c07778..9e6b72641e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message.cs @@ -31,7 +31,7 @@ public LargeMessagePayloadWrapTests() var messageTransformerFactory = new SimpleMessageTransformerFactory( _ => new ClaimCheckTransformer(_inMemoryStorageProvider, _inMemoryStorageProvider)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message_async.cs b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message_async.cs index cdd0bd95c3..b85c075063 100644 --- a/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Claims/InMemory/When_wrapping_a_large_message_async.cs @@ -33,7 +33,7 @@ public AsyncLargeMessagePayloadWrapTests() _publication = new Publication { Topic = new RoutingKey("MyLargeCommand") }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_a_message_uses_cloud_events.cs b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_a_message_uses_cloud_events.cs index 4bafc642ea..3663aa6401 100644 --- a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_a_message_uses_cloud_events.cs +++ b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_a_message_uses_cloud_events.cs @@ -12,7 +12,7 @@ namespace Paramore.Brighter.Core.Tests.CloudEvents; public class CloudEventsTransformerTests { - private readonly CloudEventsTransformer _transformer = new(); + private readonly CloudEventsTransformer _transformer = new(loggerFactory: Initializer.TestLoggerFactory); private readonly Uri _source = new("http://goparamore.io/CloudEventsTransformerTests"); private readonly CloudEventsType _type = new(typeof(MyCommand).FullName ?? "MyCommand"); private readonly Uri _dataSchema = new Uri("http://goparamore.io/CloudEventsTransformerTests/schema"); diff --git a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_migrating_subject_from_bag_to_header.cs b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_migrating_subject_from_bag_to_header.cs index cbf526aac8..146eeba83b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_migrating_subject_from_bag_to_header.cs +++ b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_migrating_subject_from_bag_to_header.cs @@ -69,7 +69,7 @@ public void When_subject_is_set_on_header_cloud_events_transformer_preserves_it( subject: expectedSubject), new MessageBody("{\"orderId\": 123}")); - var transformer = new CloudEventsTransformer(); + var transformer = new CloudEventsTransformer(loggerFactory: Initializer.TestLoggerFactory); var publication = new Publication(); // empty, no subject //Act - CloudEventsTransformer wraps the message diff --git a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_wrapping_a_message_that_already_has_cloud_event_headers_should_preserve_them.cs b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_wrapping_a_message_that_already_has_cloud_event_headers_should_preserve_them.cs index 324e407928..16cfaff73f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_wrapping_a_message_that_already_has_cloud_event_headers_should_preserve_them.cs +++ b/tests/Paramore.Brighter.Core.Tests/CloudEvents/When_wrapping_a_message_that_already_has_cloud_event_headers_should_preserve_them.cs @@ -10,7 +10,7 @@ namespace Paramore.Brighter.Core.Tests.CloudEvents; public class When_wrapping_a_message_that_already_has_cloud_event_headers_should_preserve_them { - private readonly CloudEventsTransformer _transformer = new(); + private readonly CloudEventsTransformer _transformer = new(loggerFactory: Initializer.TestLoggerFactory); private readonly Uri _mapperSource = new("http://goparamore.io/MyMapper"); private readonly CloudEventsType _mapperType = new("MyApp.OrderAccepted"); private readonly Uri _mapperDataSchema = new("http://goparamore.io/MyMapper/schema"); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs index 44a4d8d651..8891aab192 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs @@ -26,27 +26,27 @@ public CommandProcessorCallTests() var timeProvider = new FakeTimeProvider(); _routingKey = new RoutingKey("MyRequest"); - var messageProducer = new InMemoryMessageProducer(_bus, new Publication{Topic = _routingKey, RequestType = typeof(MyRequest)}); - + var messageProducer = new InMemoryMessageProducer(_bus, Initializer.TestLoggerFactory, new Publication{Topic = _routingKey, RequestType = typeof(MyRequest)}); + _messageMapperRegistry = new MessageMapperRegistry(new SimpleMessageMapperFactory((type) => { if (type == typeof(MyRequestMessageMapper)) return new MyRequestMessageMapper(); if (type == typeof(MyResponseMessageMapper)) return new MyResponseMessageMapper(); - + throw new ConfigurationException($"No mapper found for {type.Name}"); }), null); _messageMapperRegistry.Register(); _messageMapperRegistry.Register(); - + var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyResponseHandler()); var internalBus = new InternalBus(); - InMemoryChannelFactory inMemoryChannelFactory = new(internalBus, TimeProvider.System); - + InMemoryChannelFactory inMemoryChannelFactory = new(internalBus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory); + var replySubs = new List { new Subscription() @@ -54,7 +54,7 @@ public CommandProcessorCallTests() var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); - + var producerRegistry = new ProducerRegistry(new Dictionary { @@ -63,29 +63,29 @@ public CommandProcessorCallTests() var tracer = new BrighterTracer(); IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, + producerRegistry, resiliencePipelineRegistry, _messageMapperRegistry, new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider){Tracer = tracer}); - + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider){Tracer = tracer}); + _commandProcessor = new CommandProcessor( subscriberRegistry, handlerFactory, - new InMemoryRequestContextFactory(), + new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, replySubscriptions:replySubs, responseChannelFactory: inMemoryChannelFactory, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); - + _myRequest.RequestValue = "Hello World"; } @@ -94,21 +94,21 @@ public void When_Calling_A_Server_Via_The_Command_Processor() { //start a message pump on a new thread, to recieve the Call message Channel channel = new( - new("MyChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new("MyChannel"), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); - - var messagePump = new Reactor(_commandProcessor, (message) => typeof(MyRequest),_messageMapperRegistry, - new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + + var messagePump = new Reactor(_commandProcessor, (message) => typeof(MyRequest),_messageMapperRegistry, + new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; //RunAsync the pump on a new thread Task.Factory.StartNew(() => messagePump.Run()); - + _commandProcessor.Call(_myRequest, timeOut: TimeSpan.FromMilliseconds(500)); - + MyResponseHandler.ShouldReceive(new MyResponse(_myRequest.ReplyAddress) {Id = _myRequest.Id}); - + channel.Stop(_routingKey); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_In_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_In_Mapper.cs index bcc88d3a45..0cc12c507d 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_In_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_In_Mapper.cs @@ -34,7 +34,7 @@ public CommandProcessorNoInMapperTests() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{Topic = routingKey, RequestType = typeof(MyRequest)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{Topic = routingKey, RequestType = typeof(MyRequest)}) }, }); @@ -51,7 +51,7 @@ public CommandProcessorNoInMapperTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox( timeProvider) {Tracer = tracer} + Initializer.TestLoggerFactory, new InMemoryOutbox( timeProvider) {Tracer = tracer} ); _commandProcessor = new CommandProcessor( @@ -62,9 +62,9 @@ public CommandProcessorNoInMapperTests() resiliencePipelineRegistry, bus, replySubscriptions:new List(), - responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Out_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Out_Mapper.cs index 8b1308d5de..5088922b37 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Out_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Out_Mapper.cs @@ -41,7 +41,7 @@ public CommandProcessorMissingOutMapperTests() var routingKey = new RoutingKey("MyRequest"); var producerRegistry = new ProducerRegistry(new Dictionary { - { routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{Topic =routingKey } ) }, + { routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{Topic =routingKey } ) }, }); var tracer = new BrighterTracer(timeProvider); @@ -53,7 +53,7 @@ public CommandProcessorMissingOutMapperTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider){Tracer = tracer} + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider){Tracer = tracer} ); _commandProcessor = new CommandProcessor( @@ -64,9 +64,9 @@ public CommandProcessorMissingOutMapperTests() resiliencePipelineRegistry, bus, replySubscriptions:replySubs, - responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Timeout.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Timeout.cs index af3ac787d7..61fd27ac88 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Timeout.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor_With_No_Timeout.cs @@ -52,7 +52,7 @@ public CommandProcessorCallTestsNoTimeout() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication {Topic = routingKey, RequestType = typeof(MyRequest)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication {Topic = routingKey, RequestType = typeof(MyRequest)}) } }); @@ -65,7 +65,7 @@ public CommandProcessorCallTestsNoTimeout() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox( fakeTimeProvider) {Tracer = tracer} + Initializer.TestLoggerFactory, new InMemoryOutbox( fakeTimeProvider) {Tracer = tracer} ); _commandProcessor = new CommandProcessor( @@ -76,9 +76,9 @@ public CommandProcessorCallTestsNoTimeout() resiliencePipelineRegistry, bus, replySubscriptions:replySubs, - responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + responseChannelFactory: new InMemoryChannelFactory(new InternalBus(), TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Bulk_Clearing_The_PostBox_On_The_Command_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Bulk_Clearing_The_PostBox_On_The_Command_Processor_Async.cs index 470d0b9eec..23d5837daa 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Bulk_Clearing_The_PostBox_On_The_Command_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Bulk_Clearing_The_PostBox_On_The_Command_Processor_Async.cs @@ -32,10 +32,10 @@ public CommandProcessorPostBoxBulkClearAsyncTests() var routingKey = new RoutingKey("MyCommand"); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication{Topic = routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication{Topic = routingKey, RequestType = typeof(MyCommand)}); var routingKeyTwo = new RoutingKey("MyCommand2"); - InMemoryMessageProducer messageProducerTwo = new(_internalBus, new Publication {Topic = routingKeyTwo, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducerTwo = new(_internalBus, Initializer.TestLoggerFactory, new Publication {Topic = routingKeyTwo, RequestType = typeof(MyCommand)}); _messageOne = new Message( new MessageHeader(myCommand.Id, routingKey, MessageType.MT_COMMAND), @@ -72,7 +72,7 @@ public CommandProcessorPostBoxBulkClearAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -80,8 +80,8 @@ public CommandProcessorPostBoxBulkClearAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, _mediator, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor _Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor _Async.cs index 6494358ee6..15aa7059ed 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor _Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor _Async.cs @@ -27,7 +27,7 @@ public CommandProcessorPostBoxClearAsyncTests() var myCommand = new MyCommand{ Value = "Hello World"}; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -60,7 +60,7 @@ public CommandProcessorPostBoxClearAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -68,8 +68,8 @@ public CommandProcessorPostBoxClearAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor.cs index e47257b400..8fc23a28a0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Clearing_The_PostBox_On_The_Command_Processor.cs @@ -34,7 +34,7 @@ public CommandProcessorPostBoxClearTests() var myCommand = new MyCommand{ Value = "Hello World"}; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -80,7 +80,7 @@ public CommandProcessorPostBoxClearTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -88,8 +88,8 @@ public CommandProcessorPostBoxClearTests() policyRegistry, resiliencePipelineRegistry, bus, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor.cs index 4ee4fd64ac..e8f280fc2f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor.cs @@ -30,7 +30,7 @@ public CommandProcessorPostBoxImplicitClearTests() var myCommand = new MyCommand{ Value = "Hello World"}; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_bus, new Publication { Topic = new RoutingKey(Topic), RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication { Topic = new RoutingKey(Topic), RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(myCommand.Id, Topic, MessageType.MT_COMMAND), @@ -66,7 +66,7 @@ public CommandProcessorPostBoxImplicitClearTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -74,8 +74,8 @@ public CommandProcessorPostBoxImplicitClearTests() new DefaultPolicy(), resiliencePipelineRegistry, _mediator, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact(Skip = "Erratic due to timing")] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor_Async.cs index 9f0765b8a7..388fe1e3b8 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_Implicit_Clearing_The_PostBox_On_The_Command_Processor_Async.cs @@ -37,7 +37,7 @@ public CommandProcessorPostBoxImplicitClearAsyncTests() var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_bus, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -72,7 +72,7 @@ public CommandProcessorPostBoxImplicitClearAsyncTests() new EmptyMessageTransformerFactoryAsync(), new BrighterTracer(timeProvider), new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -80,8 +80,8 @@ public CommandProcessorPostBoxImplicitClearAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, _mediator, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_independent_mediators_sweep_concurrently_should_clear_both_outboxes.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_independent_mediators_sweep_concurrently_should_clear_both_outboxes.cs index e4d7594583..11985474df 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_independent_mediators_sweep_concurrently_should_clear_both_outboxes.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Clear/When_independent_mediators_sweep_concurrently_should_clear_both_outboxes.cs @@ -95,7 +95,7 @@ private static OutboxProducerMediator(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Concurrently_Depositing_Bulk_Posts.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Concurrently_Depositing_Bulk_Posts.cs index a0c59206a1..833554d881 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Concurrently_Depositing_Bulk_Posts.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Concurrently_Depositing_Bulk_Posts.cs @@ -28,7 +28,7 @@ public async Task When_concurrently_depositing_bulk_posts_async_no_messages_are_ var producerRegistry = new ProducerRegistry(new Dictionary { - { topic, new InMemoryMessageProducer(bus, new Publication { Topic = topic, RequestType = typeof(MyCommand) }) } + { topic, new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = topic, RequestType = typeof(MyCommand) }) } }); var mapperRegistry = new MessageMapperRegistry( @@ -50,14 +50,14 @@ public async Task When_concurrently_depositing_bulk_posts_async_no_messages_are_ new EmptyMessageTransformerFactoryAsync(), new BrighterTracer(), new FindPublicationByPublicationTopicOrRequestType(), - outbox); + Initializer.TestLoggerFactory, outbox); var commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, mediator, - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); var errors = new ConcurrentQueue(); var depositedIds = new ConcurrentBag(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store.cs index 265acf2370..fd0b4c7096 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store.cs @@ -28,7 +28,7 @@ public CommandProcessorDepositPostTests() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication {Topic = _routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication {Topic = _routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -60,7 +60,7 @@ public CommandProcessorDepositPostTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _fakeOutbox + Initializer.TestLoggerFactory, _fakeOutbox ); _commandProcessor = new CommandProcessor( @@ -68,8 +68,8 @@ public CommandProcessorDepositPostTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync.cs index d52acd365e..bd96a14882 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync.cs @@ -29,7 +29,7 @@ public CommandProcessorDepositPostTestsAsync() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication{ Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -61,7 +61,7 @@ public CommandProcessorDepositPostTestsAsync() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -69,8 +69,8 @@ public CommandProcessorDepositPostTestsAsync() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk.cs index ed33901936..aa5d70d76e 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk.cs @@ -37,13 +37,13 @@ public CommandProcessorBulkDepositPostTestsAsync() var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer commandMessageProducer = new(_internalBus, new Publication + InMemoryMessageProducer commandMessageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = new RoutingKey(_commandTopic), RequestType = typeof(MyCommand) } ); - InMemoryMessageProducer eventMessageProducer = new(_internalBus, new Publication + InMemoryMessageProducer eventMessageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = new RoutingKey(_eventTopic), RequestType = typeof(MyEvent) @@ -70,7 +70,7 @@ public CommandProcessorBulkDepositPostTestsAsync() { if (type == typeof(MyCommandMessageMapperAsync)) return new MyCommandMessageMapperAsync(); - else + else return new MyEventMessageMapperAsync(); })); messageMapperRegistry.RegisterAsync(); @@ -81,11 +81,11 @@ public CommandProcessorBulkDepositPostTestsAsync() { { _commandTopic, commandMessageProducer }, { _eventTopic, eventMessageProducer } - }); - + }); + var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); - + var tracer = new BrighterTracer(new FakeTimeProvider()); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; @@ -97,7 +97,7 @@ public CommandProcessorBulkDepositPostTestsAsync() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -105,8 +105,8 @@ public CommandProcessorBulkDepositPostTestsAsync() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk_With_Transaction.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk_With_Transaction.cs index 1ad723c14e..2c31c648e0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk_With_Transaction.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_Bulk_With_Transaction.cs @@ -32,16 +32,16 @@ public CommandProcessorBulkDepositPostWithTransactionTestsAsync() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer commandMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_commandTopic), - RequestType = typeof(MyCommand) + InMemoryMessageProducer commandMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_commandTopic), + RequestType = typeof(MyCommand) }); - InMemoryMessageProducer eventMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_eventTopic), - RequestType = typeof(MyEvent) + InMemoryMessageProducer eventMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_eventTopic), + RequestType = typeof(MyEvent) }); _messages.Add(new Message( @@ -75,32 +75,32 @@ public CommandProcessorBulkDepositPostWithTransactionTestsAsync() { _commandTopic, commandMessageProducer }, { _eventTopic, eventMessageProducer} }); - + var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); var tracer = new BrighterTracer(); _spyOutbox = new SpyOutbox {Tracer = tracer}; - + IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, + producerRegistry, resiliencePipelineRegistry, messageMapperRegistry, new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_With_Transaction.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_With_Transaction.cs index 1560f7ca17..0d70765f92 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_With_Transaction.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_StoreAsync_With_Transaction.cs @@ -29,7 +29,7 @@ public CommandProcessorDepositPostWithTransactionTestsAsync() { _myCommand.Value = "Hello World"; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -62,17 +62,17 @@ public CommandProcessorDepositPostWithTransactionTestsAsync() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk.cs index 6fbce95a69..310b35008d 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk.cs @@ -35,28 +35,28 @@ public CommandProcessorBulkDepositPostTests() _myEvent.Data = 3; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer commandMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_commandTopic), - RequestType = typeof(MyCommand) + InMemoryMessageProducer commandMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_commandTopic), + RequestType = typeof(MyCommand) }); - InMemoryMessageProducer eventMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_eventTopic), - RequestType = typeof(MyEvent) + InMemoryMessageProducer eventMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_eventTopic), + RequestType = typeof(MyEvent) }); - + _message = new Message( new MessageHeader(_myCommand.Id, _commandTopic, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_myCommand, JsonSerialisationOptions.Options)) ); - + _messageTwo = new Message( new MessageHeader(_myCommandTwo.Id, _commandTopic, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_myCommandTwo, JsonSerialisationOptions.Options)) ); - + _messageThree = new Message( new MessageHeader(_myEvent.Id, _eventTopic, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(_myEvent, JsonSerialisationOptions.Options)) @@ -68,10 +68,10 @@ public CommandProcessorBulkDepositPostTests() return new MyCommandMessageMapper(); else if (type == typeof(MyEventMessageMapper)) return new MyEventMessageMapper(); - + throw new ConfigurationException($"No command or event mappers registered for {type.Name}"); }), null); - + messageMapperRegistry.Register(); messageMapperRegistry.Register(); @@ -80,22 +80,22 @@ public CommandProcessorBulkDepositPostTests() { _commandTopic, commandMessageProducer }, { _eventTopic, eventMessageProducer} }); - + var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); var tracer = new BrighterTracer(); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; - + IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, + producerRegistry, resiliencePipelineRegistry, messageMapperRegistry, new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -103,8 +103,8 @@ public CommandProcessorBulkDepositPostTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } @@ -115,9 +115,9 @@ public void When_depositing_messages_in_the_outbox() var requests = new List {_myCommand, _myCommandTwo, _myEvent } ; _commandProcessor.DepositPost(requests); var context = new RequestContext(); - + //assert - + //message should not be posted Assert.False(_bus.Stream(_commandTopic).Any()); Assert.False(_bus.Stream(_eventTopic).Any()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk_With_Transaction.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk_With_Transaction.cs index 9c5dc9bbb4..b0eef7f0ad 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk_With_Transaction.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_Bulk_With_Transaction.cs @@ -31,16 +31,16 @@ public CommandProcessorBulkDepositPostWithTransactionTests() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer commandMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_commandTopic), - RequestType = typeof(MyCommand) + InMemoryMessageProducer commandMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_commandTopic), + RequestType = typeof(MyCommand) }); - InMemoryMessageProducer eventMessageProducer = new(_bus, new Publication - { - Topic = new RoutingKey(_eventTopic), - RequestType = typeof(MyEvent) + InMemoryMessageProducer eventMessageProducer = new(_bus, Initializer.TestLoggerFactory, new Publication + { + Topic = new RoutingKey(_eventTopic), + RequestType = typeof(MyEvent) }); _messages.Add(new Message( @@ -62,10 +62,10 @@ public CommandProcessorBulkDepositPostWithTransactionTests() return new MyCommandMessageMapper(); else if (type == typeof(MyEventMessageMapper)) return new MyEventMessageMapper(); - + throw new ConfigurationException($"No command or event mappers registered for {type.Name}"); }), null); - + messageMapperRegistry.Register(); messageMapperRegistry.Register(); @@ -74,32 +74,32 @@ public CommandProcessorBulkDepositPostWithTransactionTests() { _commandTopic, commandMessageProducer }, { _eventTopic, eventMessageProducer} }); - + var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); var tracer = new BrighterTracer(); _spyOutbox = new SpyOutbox() {Tracer = tracer}; - + IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, + producerRegistry, resiliencePipelineRegistry, messageMapperRegistry, new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_With_Transaction.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_With_Transaction.cs index a39820daf2..3b5a2914e1 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_With_Transaction.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Deposit/When_Depositing_A_Message_In_The_Message_Store_With_Transaction.cs @@ -29,7 +29,7 @@ public CommandProcessorDepositPostWithTransactionTests() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -61,17 +61,17 @@ public CommandProcessorDepositPostWithTransactionTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs index f7e2d816fb..4303333233 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs @@ -17,14 +17,14 @@ public PipelineBuilderAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs index 9cd8edee0b..f23095a9ea 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs @@ -17,14 +17,14 @@ public PipelineBuilderTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline.cs index ff6c1e2a9d..49a254d11f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline.cs @@ -26,14 +26,14 @@ public PipelineBuilderAgreementAsyncTests() [typeof(MyImplicitHandler), typeof(MyCommandHandler)] ); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline_Async.cs index b343742fd4..3aa1732cb4 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_An_Agreement_Pipeline_Async.cs @@ -26,14 +26,14 @@ public PipelineBuilderAgreementTests() [typeof(MyImplicitHandlerAsync), typeof(MyCommandHandlerAsync)] ); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_An_Exception_Is_Thrown_Terminate_The_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_An_Exception_Is_Thrown_Terminate_The_Pipeline.cs index cd7a25d69e..57be0dc1e3 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_An_Exception_Is_Thrown_Terminate_The_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_An_Exception_Is_Thrown_Terminate_The_Pipeline.cs @@ -19,13 +19,13 @@ public PipelineTerminationTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(),new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(),new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs index 205fc534c5..7296ef0e3c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs @@ -17,7 +17,7 @@ public PipelineForeignAttributesTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public PipelineForeignAttributesTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs index be5476e0cb..085a3997b9 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -17,7 +17,7 @@ public PipelinePreAndPostFiltersTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public PipelinePreAndPostFiltersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Disambiguates_Handlers_By_Type.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Disambiguates_Handlers_By_Type.cs index ee4d173661..59921c596e 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Disambiguates_Handlers_By_Type.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Disambiguates_Handlers_By_Type.cs @@ -98,14 +98,14 @@ public void When_a_single_handler_is_built_twice_should_leave_one_cache_entry_ke var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); container.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var factory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - var builder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)factory); + var builder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)factory, loggerFactory: Initializer.TestLoggerFactory); // Act — build the same handler twice (single-threaded) string firstTrace = @@ -131,7 +131,7 @@ private static (PipelineBuilder, PipelineBuilder) CreateSy var registryB = new SubscriberRegistry(); registryB.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -141,8 +141,8 @@ private static (PipelineBuilder, PipelineBuilder) CreateSy var factory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); return ( - new PipelineBuilder(registryA, (IAmAHandlerFactorySync)factory), - new PipelineBuilder(registryB, (IAmAHandlerFactorySync)factory)); + new PipelineBuilder(registryA, (IAmAHandlerFactorySync)factory, loggerFactory: Initializer.TestLoggerFactory), + new PipelineBuilder(registryB, (IAmAHandlerFactorySync)factory, loggerFactory: Initializer.TestLoggerFactory)); } private static (PipelineBuilder, PipelineBuilder) CreateAsyncBuilders() @@ -153,7 +153,7 @@ private static (PipelineBuilder, PipelineBuilder) CreateAs var registryB = new SubscriberRegistry(); registryB.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -163,8 +163,8 @@ private static (PipelineBuilder, PipelineBuilder) CreateAs var factory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); return ( - new PipelineBuilder(registryA, (IAmAHandlerFactoryAsync)factory), - new PipelineBuilder(registryB, (IAmAHandlerFactoryAsync)factory)); + new PipelineBuilder(registryA, (IAmAHandlerFactoryAsync)factory, loggerFactory: Initializer.TestLoggerFactory), + new PipelineBuilder(registryB, (IAmAHandlerFactoryAsync)factory, loggerFactory: Initializer.TestLoggerFactory)); } private static PipelineTracer TracePipeline(IHandleRequests firstInPipeline) diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index 0db83c8569..830e9a44bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -19,7 +19,7 @@ public BuildPipelineFaults() var handlerFactory = new SimpleHandlerFactorySync(_ => throw new InvalidOperationException("Could not create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Inbox_Cache_Does_Not_Leak_Across_Configurations.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Inbox_Cache_Does_Not_Leak_Across_Configurations.cs index db5a51189b..d6b66871dc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Inbox_Cache_Does_Not_Leak_Across_Configurations.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Inbox_Cache_Does_Not_Leak_Across_Configurations.cs @@ -20,7 +20,7 @@ public void When_Building_A_Pipeline_With_Inbox_Then_Without_Inbox_No_Leakage() var inboxRegistry = new SubscriberRegistry(); inboxRegistry.Register(); - var inboxContainer = new ServiceCollection(); + var inboxContainer = new ServiceCollection().AddLogging(); inboxContainer.AddTransient(_ => new MyCommandHandler(new Dictionary())); inboxContainer.AddSingleton(new InMemoryInbox(new FakeTimeProvider())); inboxContainer.AddTransient>(); @@ -28,7 +28,7 @@ public void When_Building_A_Pipeline_With_Inbox_Then_Without_Inbox_No_Leakage() var inboxHandlerFactory = new ServiceProviderHandlerFactory(inboxContainer.BuildServiceProvider()); var inboxBuilder = new PipelineBuilder( - inboxRegistry, (IAmAHandlerFactorySync)inboxHandlerFactory, new InboxConfiguration()); + inboxRegistry, (IAmAHandlerFactorySync)inboxHandlerFactory, Initializer.TestLoggerFactory, new InboxConfiguration()); var withInbox = inboxBuilder.Build(new MyCommand(), new RequestContext()); var withInboxTrace = TracePipeline(withInbox.First()); @@ -38,13 +38,13 @@ public void When_Building_A_Pipeline_With_Inbox_Then_Without_Inbox_No_Leakage() var noInboxRegistry = new SubscriberRegistry(); noInboxRegistry.Register(); - var noInboxContainer = new ServiceCollection(); + var noInboxContainer = new ServiceCollection().AddLogging(); noInboxContainer.AddTransient(_ => new MyCommandHandler(new Dictionary())); noInboxContainer.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var noInboxHandlerFactory = new ServiceProviderHandlerFactory(noInboxContainer.BuildServiceProvider()); var noInboxBuilder = new PipelineBuilder( - noInboxRegistry, (IAmAHandlerFactorySync)noInboxHandlerFactory); + noInboxRegistry, (IAmAHandlerFactorySync)noInboxHandlerFactory, loggerFactory: Initializer.TestLoggerFactory); var withoutInbox = noInboxBuilder.Build(new MyCommand(), new RequestContext()); var withoutInboxTrace = TracePipeline(withoutInbox.First()); @@ -60,13 +60,13 @@ public void When_Building_A_Pipeline_Without_Inbox_Then_With_Inbox_Still_Gets_In var noInboxRegistry = new SubscriberRegistry(); noInboxRegistry.Register(); - var noInboxContainer = new ServiceCollection(); + var noInboxContainer = new ServiceCollection().AddLogging(); noInboxContainer.AddTransient(_ => new MyCommandHandler(new Dictionary())); noInboxContainer.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var noInboxHandlerFactory = new ServiceProviderHandlerFactory(noInboxContainer.BuildServiceProvider()); var noInboxBuilder = new PipelineBuilder( - noInboxRegistry, (IAmAHandlerFactorySync)noInboxHandlerFactory); + noInboxRegistry, (IAmAHandlerFactorySync)noInboxHandlerFactory, loggerFactory: Initializer.TestLoggerFactory); var withoutInbox = noInboxBuilder.Build(new MyCommand(), new RequestContext()); var withoutInboxTrace = TracePipeline(withoutInbox.First()); @@ -76,7 +76,7 @@ public void When_Building_A_Pipeline_Without_Inbox_Then_With_Inbox_Still_Gets_In var inboxRegistry = new SubscriberRegistry(); inboxRegistry.Register(); - var inboxContainer = new ServiceCollection(); + var inboxContainer = new ServiceCollection().AddLogging(); inboxContainer.AddTransient(_ => new MyCommandHandler(new Dictionary())); inboxContainer.AddSingleton(new InMemoryInbox(new FakeTimeProvider())); inboxContainer.AddTransient>(); @@ -84,7 +84,7 @@ public void When_Building_A_Pipeline_Without_Inbox_Then_With_Inbox_Still_Gets_In var inboxHandlerFactory = new ServiceProviderHandlerFactory(inboxContainer.BuildServiceProvider()); var inboxBuilder = new PipelineBuilder( - inboxRegistry, (IAmAHandlerFactorySync)inboxHandlerFactory, new InboxConfiguration()); + inboxRegistry, (IAmAHandlerFactorySync)inboxHandlerFactory, Initializer.TestLoggerFactory, new InboxConfiguration()); var withInbox = inboxBuilder.Build(new MyCommand(), new RequestContext()); var withInboxTrace = TracePipeline(withInbox.First()); @@ -100,7 +100,7 @@ public void When_Building_An_Async_Pipeline_With_Inbox_Then_Without_Inbox_No_Lea var inboxRegistry = new SubscriberRegistry(); inboxRegistry.RegisterAsync(); - var inboxContainer = new ServiceCollection(); + var inboxContainer = new ServiceCollection().AddLogging(); inboxContainer.AddSingleton(new MyCommandHandlerAsync(new Dictionary())); inboxContainer.AddSingleton(new InMemoryInbox(new FakeTimeProvider())); inboxContainer.AddTransient>(); @@ -108,7 +108,7 @@ public void When_Building_An_Async_Pipeline_With_Inbox_Then_Without_Inbox_No_Lea var inboxHandlerFactory = new ServiceProviderHandlerFactory(inboxContainer.BuildServiceProvider()); var inboxBuilder = new PipelineBuilder( - inboxRegistry, (IAmAHandlerFactoryAsync)inboxHandlerFactory, new InboxConfiguration()); + inboxRegistry, (IAmAHandlerFactoryAsync)inboxHandlerFactory, Initializer.TestLoggerFactory, new InboxConfiguration()); var withInbox = inboxBuilder.BuildAsync(new MyCommand(), new RequestContext(), false); var withInboxTrace = TraceAsyncPipeline(withInbox.First()); @@ -118,13 +118,13 @@ public void When_Building_An_Async_Pipeline_With_Inbox_Then_Without_Inbox_No_Lea var noInboxRegistry = new SubscriberRegistry(); noInboxRegistry.RegisterAsync(); - var noInboxContainer = new ServiceCollection(); + var noInboxContainer = new ServiceCollection().AddLogging(); noInboxContainer.AddSingleton(new MyCommandHandlerAsync(new Dictionary())); noInboxContainer.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var noInboxHandlerFactory = new ServiceProviderHandlerFactory(noInboxContainer.BuildServiceProvider()); var noInboxBuilder = new PipelineBuilder( - noInboxRegistry, (IAmAHandlerFactoryAsync)noInboxHandlerFactory); + noInboxRegistry, (IAmAHandlerFactoryAsync)noInboxHandlerFactory, loggerFactory: Initializer.TestLoggerFactory); var withoutInbox = noInboxBuilder.BuildAsync(new MyCommand(), new RequestContext(), false); var withoutInboxTrace = TraceAsyncPipeline(withoutInbox.First()); @@ -140,13 +140,13 @@ public void When_Building_An_Async_Pipeline_Without_Inbox_Then_With_Inbox_Still_ var noInboxRegistry = new SubscriberRegistry(); noInboxRegistry.RegisterAsync(); - var noInboxContainer = new ServiceCollection(); + var noInboxContainer = new ServiceCollection().AddLogging(); noInboxContainer.AddSingleton(new MyCommandHandlerAsync(new Dictionary())); noInboxContainer.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var noInboxHandlerFactory = new ServiceProviderHandlerFactory(noInboxContainer.BuildServiceProvider()); var noInboxBuilder = new PipelineBuilder( - noInboxRegistry, (IAmAHandlerFactoryAsync)noInboxHandlerFactory); + noInboxRegistry, (IAmAHandlerFactoryAsync)noInboxHandlerFactory, loggerFactory: Initializer.TestLoggerFactory); var withoutInbox = noInboxBuilder.BuildAsync(new MyCommand(), new RequestContext(), false); var withoutInboxTrace = TraceAsyncPipeline(withoutInbox.First()); @@ -156,7 +156,7 @@ public void When_Building_An_Async_Pipeline_Without_Inbox_Then_With_Inbox_Still_ var inboxRegistry = new SubscriberRegistry(); inboxRegistry.RegisterAsync(); - var inboxContainer = new ServiceCollection(); + var inboxContainer = new ServiceCollection().AddLogging(); inboxContainer.AddSingleton(new MyCommandHandlerAsync(new Dictionary())); inboxContainer.AddSingleton(new InMemoryInbox(new FakeTimeProvider())); inboxContainer.AddTransient>(); @@ -164,7 +164,7 @@ public void When_Building_An_Async_Pipeline_Without_Inbox_Then_With_Inbox_Still_ var inboxHandlerFactory = new ServiceProviderHandlerFactory(inboxContainer.BuildServiceProvider()); var inboxBuilder = new PipelineBuilder( - inboxRegistry, (IAmAHandlerFactoryAsync)inboxHandlerFactory, new InboxConfiguration()); + inboxRegistry, (IAmAHandlerFactoryAsync)inboxHandlerFactory, Initializer.TestLoggerFactory, new InboxConfiguration()); var withInbox = inboxBuilder.BuildAsync(new MyCommand(), new RequestContext(), false); var withInboxTrace = TraceAsyncPipeline(withInbox.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Post_Attributes_Are_Cached.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Post_Attributes_Are_Cached.cs index e4fb663248..c15654b737 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Post_Attributes_Are_Cached.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Post_Attributes_Are_Cached.cs @@ -20,14 +20,14 @@ public void When_Building_A_Sync_Pipeline_Post_Attributes_Are_Cached_For_The_Han var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); container.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - var pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + var pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); pipelineBuilder.Build(new MyCommand(), new RequestContext()).First(); @@ -42,14 +42,14 @@ public void When_Building_An_Async_Pipeline_Post_Attributes_Are_Cached_For_The_H var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); container.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - var pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + var pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); pipelineBuilder.BuildAsync(new MyCommand(), new RequestContext(), false).First(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs index 3c96d16ad5..c2788bd7b5 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs @@ -17,7 +17,7 @@ public PipelineOrderingTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public PipelineOrderingTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs index 7835225060..2a1f6ace95 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs @@ -24,7 +24,7 @@ public PipelineGlobalInboxTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(_ => new MyCommandHandler(_receivedMessages)); container.AddSingleton(inbox); container.AddTransient>(); @@ -36,7 +36,7 @@ public PipelineGlobalInboxTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs index e581f3b20c..85df892c9f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs @@ -22,7 +22,7 @@ public PipelineGlobalInboxNoInboxAttributeTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -33,7 +33,7 @@ public PipelineGlobalInboxNoInboxAttributeTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs index 140f5b9386..d726f42001 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs @@ -22,7 +22,7 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -33,7 +33,7 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs index c56ac475bc..c41c7bf455 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs @@ -25,7 +25,7 @@ public PipelineGlobalInboxWhenUseInboxTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddTransient>(); @@ -41,7 +41,7 @@ public PipelineGlobalInboxWhenUseInboxTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs index df02bea496..5155dcbce5 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs @@ -26,7 +26,7 @@ public PipelineGlobalInboxWhenUseInboxAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton((IAmAnInboxAsync)inbox); container.AddTransient>(); @@ -43,7 +43,7 @@ public PipelineGlobalInboxWhenUseInboxAsyncTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs index f992828a55..292bdb4027 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs @@ -29,7 +29,7 @@ public PipelineGlobalInboxTestsAsync() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(inbox); container.AddTransient>(); @@ -42,7 +42,7 @@ public PipelineGlobalInboxTestsAsync() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Each_Handler_Gets_Its_Own_UseInbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Each_Handler_Gets_Its_Own_UseInbox.cs index ed546f2d9e..898f301494 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Each_Handler_Gets_Its_Own_UseInbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Each_Handler_Gets_Its_Own_UseInbox.cs @@ -111,7 +111,7 @@ private static (PipelineBuilder, PipelineBuilder) CreateSy var registryB = new SubscriberRegistry(); registryB.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -123,8 +123,8 @@ private static (PipelineBuilder, PipelineBuilder) CreateSy var inboxConfiguration = new InboxConfiguration(); return ( - new PipelineBuilder(registryA, (IAmAHandlerFactorySync)factory, inboxConfiguration), - new PipelineBuilder(registryB, (IAmAHandlerFactorySync)factory, inboxConfiguration)); + new PipelineBuilder(registryA, (IAmAHandlerFactorySync)factory, Initializer.TestLoggerFactory, inboxConfiguration), + new PipelineBuilder(registryB, (IAmAHandlerFactorySync)factory, Initializer.TestLoggerFactory, inboxConfiguration)); } private static (PipelineBuilder, PipelineBuilder) CreateAsyncInboxBuilders() @@ -137,7 +137,7 @@ private static (PipelineBuilder, PipelineBuilder) CreateAs var registryB = new SubscriberRegistry(); registryB.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -149,8 +149,8 @@ private static (PipelineBuilder, PipelineBuilder) CreateAs var inboxConfiguration = new InboxConfiguration(); return ( - new PipelineBuilder(registryA, (IAmAHandlerFactoryAsync)factory, inboxConfiguration), - new PipelineBuilder(registryB, (IAmAHandlerFactoryAsync)factory, inboxConfiguration)); + new PipelineBuilder(registryA, (IAmAHandlerFactoryAsync)factory, Initializer.TestLoggerFactory, inboxConfiguration), + new PipelineBuilder(registryB, (IAmAHandlerFactoryAsync)factory, Initializer.TestLoggerFactory, inboxConfiguration)); } private static void AssertCacheExcludesUseInbox(Type handlerType) diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs index 44d92a2fa7..c77bedd0da 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs @@ -25,7 +25,7 @@ public PipelineGlobalInboxContextTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -39,7 +39,7 @@ public PipelineGlobalInboxContextTests() scope: InboxScope.All, context: (handlerType) => CONTEXT_KEY); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, Initializer.TestLoggerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs index d331ba3eb4..cc9742e2ea 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs @@ -43,16 +43,16 @@ public PipelineMixedHandlersTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); - + var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs index a49003b6f7..722a81e16d 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs @@ -18,7 +18,7 @@ public PipelineForiegnAttributesAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); @@ -27,7 +27,7 @@ public PipelineForiegnAttributesAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs index b99d181b10..d9245b43e3 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -17,7 +17,7 @@ public PipelinePreAndPostFiltersAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public PipelinePreAndPostFiltersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry,(IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry,(IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index 250376e4e0..9a04b9820b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -19,7 +19,7 @@ public BuildPipelineFaultsAsync() IAmAHandlerFactoryAsync handlerFactory = new SimpleHandlerFactoryAsync(_ => throw new InvalidOperationException("Could not create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs index d01506262d..180c9864b0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs @@ -17,7 +17,7 @@ public PipelineOrderingAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public PipelineOrderingAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs index 2e6129ee26..01a611c977 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs @@ -19,14 +19,14 @@ public PipelineMixedHandlersAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler.cs index 28619a3fc5..87a81e023c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler.cs @@ -19,7 +19,7 @@ public PipelineForCommandTests() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler(new Dictionary())); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler_Async.cs index 7758f4be60..a2b50cfa1c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Creating_Context_For_A_Handler_Async.cs @@ -20,7 +20,7 @@ public PipelineForCommandAsyncTests() var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(_receivedMessages)); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, asyncHandlerFactory: handlerFactory); + _chainBuilder = new PipelineBuilder(registry, asyncHandlerFactory: handlerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs index 1ba322e81c..f6e1b84415 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs @@ -18,7 +18,7 @@ public PipelineWithHandlerDependenciesTests() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyDependentCommandHandler(new FakeRepository(new FakeSession()))); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs index b635b67843..a617ee0d13 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs @@ -17,7 +17,7 @@ public PipelineBuildForCommandTests() registry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler(new Dictionary())); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_Async.cs index 97dff3a43d..7b2f46cbde 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_Async.cs @@ -17,7 +17,7 @@ public PipelineBuildForCommandAsyncTests () registry.RegisterAsync(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(new Dictionary())); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement.cs index 1ad59910b4..e1d99cadb0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement.cs @@ -26,7 +26,7 @@ public PipelineBuildForAgreementTests () ); var handlerFactory = new SimpleHandlerFactorySync(factoryMethod: _ => new MyCommandHandler(new Dictionary())); - _pipelineBuilder = new PipelineBuilder(subscriberRegistry: registry, syncHandlerFactory: handlerFactory); + _pipelineBuilder = new PipelineBuilder(subscriberRegistry: registry, syncHandlerFactory: handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement_Async.cs index 724a5b26bf..0007327856 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command_By_Agreement_Async.cs @@ -26,7 +26,7 @@ public PipelineBuildForAgreementAsyncTests () ); var handlerFactory = new SimpleHandlerFactoryAsync(factoryMethod: _ => new MyCommandHandlerAsync(new Dictionary())); - _pipelineBuilder = new PipelineBuilder(subscriberRegistry: registry, asyncHandlerFactory: handlerFactory); + _pipelineBuilder = new PipelineBuilder(subscriberRegistry: registry, asyncHandlerFactory: handlerFactory, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs index bf1c9eb530..826f3a3bdd 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs @@ -25,7 +25,7 @@ public CommandProcessorBuildDefaultInboxPublishTests() //This handler has no Inbox attribute subscriberRegistry.Add(typeof(MyEvent), typeof(MyGlobalInboxEventHandler)); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(_inbox); container.AddSingleton>(); @@ -55,9 +55,9 @@ public CommandProcessorBuildDefaultInboxPublishTests() new InMemoryRequestContextFactory(), new PolicyRegistry {{CommandProcessor.RETRYPOLICY, retryPolicy}, {CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy}}, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs index 8e330aa9db..fc68ee917c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs @@ -25,7 +25,7 @@ public CommandProcessorBuildDefaultInboxPublishAsyncTests() //This handler has no Inbox attribute subscriberRegistry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(_inbox); container.AddTransient>(); @@ -56,9 +56,9 @@ public CommandProcessorBuildDefaultInboxPublishAsyncTests() { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy } }, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline.cs index 336a1b74dc..771d25dc77 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline.cs @@ -24,7 +24,7 @@ public CommandProcessorBuildDefaultInboxSendTests() //This handler has no Inbox attribute subscriberRegistry.Add(typeof(MyCommand), typeof(MyCommandHandler)); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(_ => new MyCommandHandler(_receivedMessages)); container.AddSingleton(new InMemoryInbox(new FakeTimeProvider())); container.AddTransient>(); @@ -54,9 +54,9 @@ public CommandProcessorBuildDefaultInboxSendTests() new InMemoryRequestContextFactory(), new PolicyRegistry {{CommandProcessor.RETRYPOLICY, retryPolicy}, {CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy}}, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline_Async.cs index e27fc61d61..9bd8862f63 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Inserting_A_Default_Inbox_Into_The_Send_Pipeline_Async.cs @@ -25,7 +25,7 @@ public CommandProcessorBuildDefaultInboxSendAsyncTests() //This handler has no Inbox attribute subscriberRegistry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(_inbox); container.AddTransient>(); @@ -55,9 +55,9 @@ public CommandProcessorBuildDefaultInboxSendAsyncTests() { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy } }, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_There_Is_No_Sync_Or_Async_Handler_Factories.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_There_Is_No_Sync_Or_Async_Handler_Factories.cs index 6be19d6d8f..d73da55b38 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_There_Is_No_Sync_Or_Async_Handler_Factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_There_Is_No_Sync_Or_Async_Handler_Factories.cs @@ -14,7 +14,7 @@ public class CommandProcessorNoHandlerFactoriesTests [Fact] public void When_There_Are_No_Command_Handlers_Async() { - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); _exception = Catch.Exception(() => new CommandProcessor( @@ -23,7 +23,7 @@ public void When_There_Are_No_Command_Handlers_Async() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory())); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory)); Assert.IsType(_exception); @@ -35,7 +35,7 @@ public void When_There_Are_No_Command_Handlers_Async() [Fact] public void When_using_IAmAHandlerFactory() { - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); _exception = Catch.Exception(() => new CommandProcessor( @@ -44,7 +44,7 @@ public void When_using_IAmAHandlerFactory() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory())); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory)); //_should_fail_because_no_handler_factories_have_been_set Assert.IsType(_exception); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs index 7296f95fc8..28307a1dd6 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs @@ -20,7 +20,7 @@ public PipelineCleanupTests() var handlerFactory = new CheapHandlerFactorySync(); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory, loggerFactory: Initializer.TestLoggerFactory); _pipelineBuilder.Build(new MyCommand(), new RequestContext()).Any(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Bulk_Dispatching_Reply_Messages_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Bulk_Dispatching_Reply_Messages_Async.cs index eb34b42ca8..13bed05223 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Bulk_Dispatching_Reply_Messages_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Bulk_Dispatching_Reply_Messages_Async.cs @@ -37,7 +37,7 @@ public CommandProcessorBulkDispatchReplyAsyncTests() _replyTwo = new MyResponse(replyAddress) { ReplyValue = "World" }; InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + Initializer.TestLoggerFactory, new Publication { Topic = producerRoutingKey, RequestType = typeof(MyResponse) @@ -68,7 +68,7 @@ public CommandProcessorBulkDispatchReplyAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -77,8 +77,8 @@ public CommandProcessorBulkDispatchReplyAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, _mediator, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry.cs index 92419862d2..b7a088aa5b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry.cs @@ -23,7 +23,7 @@ public CommandProcessorNoMessageMapperTests() var timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = - new(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + new(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory((_) => new MyCommandMessageMapper()), @@ -41,30 +41,30 @@ public CommandProcessorNoMessageMapperTests() var outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, + producerRegistry, resiliencePipelineRegistry, messageMapperRegistry, new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + Initializer.TestLoggerFactory, outbox ); - + _commandProcessor = new CommandProcessor( - new InMemoryRequestContextFactory(), + new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] public void When_Posting_A_Message_And_There_Is_No_Message_Mapper_Factory() { var exception = Catch.Exception(() => _commandProcessor.Post(_myCommand)); - Assert.IsType(exception); + Assert.IsType(exception); } } } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry_Async.cs index 116c414006..316445af2a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Mapper_Registry_Async.cs @@ -24,7 +24,7 @@ public CommandProcessorNoMessageMapperAsyncTests() var timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = - new(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + new(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory((_) => new MyCommandMessageMapper()), @@ -46,7 +46,7 @@ public CommandProcessorNoMessageMapperAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + Initializer.TestLoggerFactory, outbox ); _commandProcessor = new CommandProcessor( @@ -54,8 +54,8 @@ public CommandProcessorNoMessageMapperAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Producer.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Producer.cs index fe2ee4b416..1170d375a5 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Producer.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Producer.cs @@ -44,7 +44,7 @@ public void When_Creating_A_Command_Processor_Without_Producer_Registry() new EmptyMessageTransformerFactoryAsync(), _tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox) + Initializer.TestLoggerFactory, _outbox) ); Assert.IsType(exception); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer.cs index e344c525a7..1ad6cd0509 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer.cs @@ -38,7 +38,7 @@ public CommandProcessorPostMissingMessageTransformerTests() _producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication {Topic = routingKey, RequestType = typeof(MyCommand) }) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication {Topic = routingKey, RequestType = typeof(MyCommand) }) }, }); } @@ -57,7 +57,7 @@ public void When_Creating_A_Command_Processor_Without_Message_Transformer() new EmptyMessageTransformerFactoryAsync(), _tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox) + Initializer.TestLoggerFactory, _outbox) ); Assert.IsType(exception); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer_Async.cs index aaf7090250..71821d8051 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_And_There_Is_No_Message_Transformer_Async.cs @@ -32,33 +32,33 @@ public CommandProcessorPostMissingMessageTransformerTestsAsync() _messageMapperRegistry.Register(); var routingKey = new RoutingKey("MyTopic"); - + _producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }) } }); } [Fact] public void When_Creating_A_Command_Processor_Without_Message_Transformer_Async() - { + { var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); - + var exception = Catch.Exception(() => new OutboxProducerMediator( - _producerRegistry, + _producerRegistry, resiliencePipelineRegistry, _messageMapperRegistry, new EmptyMessageTransformerFactory(), null!, _tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox) - ); + Initializer.TestLoggerFactory, _outbox) + ); - Assert.IsType(exception); + Assert.IsType(exception); } } } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor.cs index 1347addfe1..fa3fd23259 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor.cs @@ -37,8 +37,8 @@ public CommandProcessorPostCommandTests() var cloudEventsType = new CloudEventsType("go.paramore.brighter.test"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication() + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication() { DataSchema = new Uri("https://goparamore.io/schemas/MyCommand.json"), Source = new Uri("https://goparamore.io"), @@ -89,7 +89,7 @@ public CommandProcessorPostCommandTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -97,8 +97,8 @@ public CommandProcessorPostCommandTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_Async.cs index b6ba031e9b..78bfc19479 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_Async.cs @@ -36,8 +36,8 @@ public CommandProcessorPostCommandAsyncTests() var timeProvider = new FakeTimeProvider(); var cloudEventsType = new CloudEventsType("go.paramore.brighter.test"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication() + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication() { DataSchema = new Uri("https://goparamore.io/schemas/MyCommand.json"), Source = new Uri("https://goparamore.io"), @@ -89,7 +89,7 @@ public CommandProcessorPostCommandAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -97,8 +97,8 @@ public CommandProcessorPostCommandAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider.cs index 34b5d4ae84..c00ab6e483 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider.cs @@ -54,7 +54,7 @@ public CommandProcessorPostCommandWithTransactionProviderTests() var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey(Topic); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication {Topic = routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication {Topic = routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND, contentType: new ContentType(MediaTypeNames.Application.Json) {CharSet = CharacterEncoding.UTF8.FromCharacterEncoding()}), @@ -83,17 +83,17 @@ public CommandProcessorPostCommandWithTransactionProviderTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), new ResiliencePipelineRegistry(), bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider_Async.cs index 1ee27d6c80..893b38623a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Message_To_The_Command_Processor_With_A_Transaction_Provider_Async.cs @@ -55,7 +55,7 @@ public CommandProcessorPostCommandWithTransactionProviderTestsAsync() var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey(Topic); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication {Topic = routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication {Topic = routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND), @@ -84,17 +84,17 @@ public CommandProcessorPostCommandWithTransactionProviderTestsAsync() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _spyOutbox + Initializer.TestLoggerFactory, _spyOutbox ); - var scheduler = new InMemorySchedulerFactory(); + var scheduler = new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = new CommandProcessor( new InMemoryRequestContextFactory(), new DefaultPolicy(), resiliencePipelineRegistry, bus, scheduler, - typeof(SpyTransaction) + Initializer.TestLoggerFactory, typeof(SpyTransaction) ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor.cs index 6cc7ee7c70..1ea7ee2687 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor.cs @@ -29,7 +29,7 @@ public CommandProcessorPostReplyTests() _myResponse = new MyResponse(replyAddress) { ReplyValue = "Hello World" }; InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + Initializer.TestLoggerFactory, new Publication { Topic = producerRoutingKey, RequestType = typeof(MyResponse) @@ -60,7 +60,7 @@ public CommandProcessorPostReplyTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -68,8 +68,8 @@ public CommandProcessorPostReplyTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor_Async.cs index 14ca40c60d..b79ca61f3b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_A_Reply_Message_To_The_Command_Processor_Async.cs @@ -30,7 +30,7 @@ public CommandProcessorPostReplyAsyncTests() _myResponse = new MyResponse(replyAddress) { ReplyValue = "Hello World" }; InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + Initializer.TestLoggerFactory, new Publication { Topic = producerRoutingKey, RequestType = typeof(MyResponse) @@ -61,7 +61,7 @@ public CommandProcessorPostReplyAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -69,8 +69,8 @@ public CommandProcessorPostReplyAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs index bb4e067561..54adaec855 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs @@ -21,7 +21,7 @@ public class PostFailureLimitCommandTests public PostFailureLimitCommandTests() { var routingKey = new RoutingKey("MyCommand"); - + IAmAMessageProducer producer = new FakeErroringMessageProducerSync{Publication = { Topic = routingKey, RequestType = typeof(MyCommand)}}; var messageMapperRegistry = @@ -35,35 +35,36 @@ public PostFailureLimitCommandTests() _outbox = new InMemoryOutbox(_timeProvider) {Tracer = tracer}; var producerRegistry = - new ProducerRegistry(new Dictionary { { routingKey, producer }, }); - + new ProducerRegistry(new Dictionary { { routingKey, producer }, }); + var externalBus = new OutboxProducerMediator( producerRegistry: producerRegistry, resiliencePipelineRegistry: new ResiliencePipelineRegistry().AddBrighterDefault(), mapperRegistry: messageMapperRegistry, messageTransformerFactory: new EmptyMessageTransformerFactory(), - messageTransformerFactoryAsync: new EmptyMessageTransformerFactoryAsync(), + messageTransformerFactoryAsync: new EmptyMessageTransformerFactoryAsync(), tracer, outbox: _outbox, maxOutStandingMessages:3, maxOutStandingCheckInterval: TimeSpan.FromMilliseconds(250), - publicationFinder: new FindPublicationByPublicationTopicOrRequestType() - ); - + publicationFinder: new FindPublicationByPublicationTopicOrRequestType(), + loggerFactory: Initializer.TestLoggerFactory); + _commandProcessor = CommandProcessorBuilder.StartNew() .Handlers(new HandlerConfiguration(new SubscriberRegistry(), new EmptyHandlerFactorySync())) .DefaultResilience() .ExternalBus(ExternalBusType.FireAndForget, externalBus) .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } [Fact] public async Task When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window() { - var sentList = new List(); + var sentList = new List(); bool shouldThrowException = false; try { @@ -72,7 +73,7 @@ public async Task When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window() var command = new MyCommand{Value = $"Hello World: {sentList.Count + 1}"}; _commandProcessor.Post(command); sentList.Add(command.Id); - + _timeProvider.Advance(TimeSpan.FromMilliseconds(500)); //We need to wait for the sweeper thread to check the outstanding in the outbox @@ -84,10 +85,10 @@ public async Task When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window() { shouldThrowException = true; } - + //We should error before the end Assert.True(shouldThrowException); - + //should store the message in the sent outbox foreach (var id in sentList) { diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic.cs index d633a1f831..29da74818b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic.cs @@ -38,8 +38,8 @@ public CommandProcessorPostCommandMultiChannelTopicTests () var otherEventsType = new CloudEventsType("io.goparamore.brighter.myothercommand"); var messageProducer = new InMemoryMessageProducer( - _internalBus, - new Publication + _internalBus, + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, Type = cloudEventsType, @@ -49,8 +49,8 @@ public CommandProcessorPostCommandMultiChannelTopicTests () //This producer is for a different command type, but the same topic var otherMessageProducer = new InMemoryMessageProducer( - _internalBus, - new Publication + _internalBus, + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, Type = otherEventsType, @@ -97,7 +97,7 @@ public CommandProcessorPostCommandMultiChannelTopicTests () new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -105,8 +105,8 @@ public CommandProcessorPostCommandMultiChannelTopicTests () new DefaultPolicy(), resiliencePipeline, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic_Async.cs index fefdc49876..095dc5a0ee 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Multiple_Message_Types_To_A_Single_Topic_Async.cs @@ -39,8 +39,8 @@ public CommandProcessorPostCommandMultiChannelTopicAsyncTests () var otherEventsType = new CloudEventsType("io.goparamore.brighter.myothercommand"); var messageProducer = new InMemoryMessageProducer( - _internalBus, - new Publication + _internalBus, + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, Type = cloudEventsType, @@ -50,8 +50,8 @@ public CommandProcessorPostCommandMultiChannelTopicAsyncTests () //This producer is for a different command type, but the same topic var otherMessageProducer = new InMemoryMessageProducer( - _internalBus, - new Publication + _internalBus, + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, Type = otherEventsType, @@ -98,7 +98,7 @@ public CommandProcessorPostCommandMultiChannelTopicAsyncTests () new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -106,8 +106,8 @@ public CommandProcessorPostCommandMultiChannelTopicAsyncTests () new DefaultPolicy(), resiliencePipeline, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender.cs index 23c17719c4..83224c649d 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender.cs @@ -29,7 +29,7 @@ public ControlBusSenderPostMessageTests() _timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = - new(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + new(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, routingKey, MessageType.MT_COMMAND), @@ -56,7 +56,7 @@ public ControlBusSenderPostMessageTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + Initializer.TestLoggerFactory, _outbox, timeProvider: _timeProvider ); @@ -65,8 +65,8 @@ public ControlBusSenderPostMessageTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); _controlBusSender = new ControlBusSender(commandProcessor); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender_Async.cs index 282aeff2be..58f2a7172c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Via_A_Control_Bus_Sender_Async.cs @@ -30,7 +30,7 @@ public ControlBusSenderPostMessageAsyncTests() var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -55,7 +55,7 @@ public ControlBusSenderPostMessageAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); var commandProcessor = new CommandProcessor( @@ -63,8 +63,8 @@ public ControlBusSenderPostMessageAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); _controlBusSender = new ControlBusSender(commandProcessor); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Custom_Policy.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Custom_Policy.cs index c2bec3b2fb..9946186e7f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Custom_Policy.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Custom_Policy.cs @@ -33,7 +33,7 @@ public PostCommandWithCustomPolicyTests() var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -66,8 +66,8 @@ public PostCommandWithCustomPolicyTests() tracer: tracer, publicationFinder: new FindPublicationByPublicationTopicOrRequestType(), outboxCircuitBreaker: new InMemoryOutboxCircuitBreaker(), - outbox: _outbox - ); + outbox: _outbox, + loggerFactory: Initializer.TestLoggerFactory); _commandProcessor = CommandProcessorBuilder.StartNew() .Handlers(new HandlerConfiguration(new SubscriberRegistry(), new EmptyHandlerFactorySync())) @@ -75,7 +75,8 @@ public PostCommandWithCustomPolicyTests() .ExternalBus(ExternalBusType.FireAndForget, externalBus) .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs index 378a5d88ad..4a4eecc118 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs @@ -30,7 +30,7 @@ public PostCommandTests() var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -55,16 +55,17 @@ public PostCommandTests() tracer: tracer, publicationFinder: new FindPublicationByPublicationTopicOrRequestType(), outboxCircuitBreaker: new InMemoryOutboxCircuitBreaker(), - outbox: _outbox - ); - + outbox: _outbox, + loggerFactory: Initializer.TestLoggerFactory); + _commandProcessor = CommandProcessorBuilder.StartNew() .Handlers(new HandlerConfiguration(new SubscriberRegistry(), new EmptyHandlerFactorySync())) .DefaultResilience() .ExternalBus(ExternalBusType.FireAndForget, externalBus) .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } @@ -74,7 +75,7 @@ public void When_Posting_With_A_Default_Policy() _commandProcessor.Post(_myCommand); Assert.True(_internalBus.Stream(new RoutingKey(_routingKey)).Any()); - + var message = _outbox.Get(_myCommand.Id, new RequestContext()); Assert.NotNull(message); Assert.Equal(_message, message); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store.cs index 3eb157fd40..61fc9db5f6 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store.cs @@ -27,7 +27,7 @@ public CommandProcessorWithInMemoryOutboxTests() _myCommand.Value = "Hello World"; var timeProvider = new FakeTimeProvider(); - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = new RoutingKey(_routingKey), RequestType = typeof(MyCommand) }); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = new RoutingKey(_routingKey), RequestType = typeof(MyCommand) }); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -54,7 +54,7 @@ public CommandProcessorWithInMemoryOutboxTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -62,8 +62,8 @@ public CommandProcessorWithInMemoryOutboxTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store_Async.cs index 8fb1c129e3..f560012da2 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_An_In_Memory_Message_Store_Async.cs @@ -31,7 +31,7 @@ public CommandProcessorWithInMemoryOutboxAscyncTests() var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); _outbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); + InMemoryMessageProducer messageProducer = new(_internalBus, Initializer.TestLoggerFactory, new Publication{Topic = _routingKey, RequestType = typeof(MyCommand)}); _message = new Message( new MessageHeader(_myCommand.Id, _routingKey, MessageType.MT_COMMAND), @@ -56,7 +56,7 @@ public CommandProcessorWithInMemoryOutboxAscyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor( @@ -64,8 +64,8 @@ public CommandProcessorWithInMemoryOutboxAscyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_a_mapper_release_throws_the_message_is_still_posted.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_a_mapper_release_throws_the_message_is_still_posted.cs index 65b8153bb1..ae9e471e78 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_a_mapper_release_throws_the_message_is_still_posted.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_a_mapper_release_throws_the_message_is_still_posted.cs @@ -31,7 +31,7 @@ public CommandProcessorPostMapperReleaseThrowsTests() var timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); var messageMapperRegistry = new MessageMapperRegistry(new ThrowingOnReleaseMessageMapperFactory(), null); messageMapperRegistry.Register(); @@ -51,7 +51,7 @@ public CommandProcessorPostMapperReleaseThrowsTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer } + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer } ); _commandProcessor = new CommandProcessor( @@ -59,8 +59,8 @@ public CommandProcessorPostMapperReleaseThrowsTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_disposing_the_mediator_it_disposes_its_factories.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_disposing_the_mediator_it_disposes_its_factories.cs index 794fd3676c..17f2048d24 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_disposing_the_mediator_it_disposes_its_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_disposing_the_mediator_it_disposes_its_factories.cs @@ -39,7 +39,7 @@ public void When_disposing_the_mediator_it_disposes_the_registry_and_transform_f asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }, + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }, ownsRegistry: true, ownsTransformerFactories: true); @@ -80,7 +80,7 @@ public void When_closing_the_producers_throws_the_factories_are_still_disposed_a asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }, + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }, ownsRegistry: true, ownsTransformerFactories: true); @@ -125,7 +125,7 @@ public void When_disposing_the_registry_throws_the_transform_factories_are_still asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }, + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }, ownsRegistry: true, ownsTransformerFactories: true); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_posting_a_message_should_release_every_mapper_it_creates.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_posting_a_message_should_release_every_mapper_it_creates.cs index 300e844c77..50f4894fe0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_posting_a_message_should_release_every_mapper_it_creates.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_posting_a_message_should_release_every_mapper_it_creates.cs @@ -25,7 +25,7 @@ public CommandProcessorPostMapperReleaseTests() var routingKey = new RoutingKey(Topic); InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var messageMapperRegistry = new MessageMapperRegistry(_mapperFactory, null); messageMapperRegistry.Register(); @@ -45,7 +45,7 @@ public CommandProcessorPostMapperReleaseTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer } + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer } ); _commandProcessor = new CommandProcessor( @@ -53,8 +53,8 @@ public CommandProcessorPostMapperReleaseTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_the_mediator_does_not_own_its_factories.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_the_mediator_does_not_own_its_factories.cs index 2b6ab84f4f..8bcb86f727 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_the_mediator_does_not_own_its_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_the_mediator_does_not_own_its_factories.cs @@ -42,7 +42,7 @@ public void When_the_mediator_does_not_own_its_factories_it_does_not_dispose_the asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }); + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }); //act mediator.Dispose(); @@ -76,7 +76,7 @@ public void When_the_mediator_owns_only_the_registry_it_disposes_only_the_regist asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }, + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }, ownsRegistry: true, ownsTransformerFactories: false); @@ -112,7 +112,7 @@ public void When_the_mediator_owns_only_the_transform_factories_it_disposes_only asyncTransformerFactory, tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer }, + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer }, ownsRegistry: false, ownsTransformerFactories: true); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs index 4a173bcb58..3baab8c323 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline.cs @@ -25,7 +25,7 @@ public CommandProcessorBuildDefaultInboxPublishTests() //This handler has no Inbox attribute subscriberRegistry.Add(typeof(MyEvent), typeof(MyGlobalInboxEventHandler)); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(_inbox); container.AddSingleton>(); @@ -55,9 +55,9 @@ public CommandProcessorBuildDefaultInboxPublishTests() new InMemoryRequestContextFactory(), new PolicyRegistry {{Brighter.CommandProcessor.RETRYPOLICY, retryPolicy}, {Brighter.CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy}}, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs index 978deb0009..f94f0208ba 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Inserting_A_Default_Inbox_Into_The_Publish_Pipeline_Async.cs @@ -26,7 +26,7 @@ public CommandProcessorBuildDefaultInboxPublishAsyncTests() //This handler has no Inbox attribute subscriberRegistry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(handler); container.AddSingleton(_inbox); container.AddTransient>(); @@ -60,9 +60,9 @@ public CommandProcessorBuildDefaultInboxPublishAsyncTests() { Brighter.CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy } }, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), - inboxConfiguration: inboxConfiguration - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + inboxConfiguration: inboxConfiguration, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor.cs index a2b6e60cac..5935656fb9 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor.cs @@ -19,7 +19,7 @@ public CommandProcessorPublishEventTests() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyEventHandler(_receivedMessages)); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_Async.cs index 326e4bbc50..6181a55ddc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_Async.cs @@ -20,7 +20,7 @@ public CommandProcessorPublishEventAsyncTests() var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyEventHandlerAsync(_receivedMessages)); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement.cs index bf0da183f5..c589ac87ff 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement.cs @@ -27,7 +27,7 @@ public CommandProcessorPublishEventAgreementTests() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyEventHandler(_receivedMessages)); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement_Async.cs index 8213707651..b9fa287254 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_An_Event_To_The_Processor_With_Agreement_Async.cs @@ -28,7 +28,7 @@ public CommandProcessorPublishEventAgreementAsyncTests() var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyEventHandlerAsync(_receivedMessages)); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions.cs index cabc6246b3..31e267a746 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions.cs @@ -24,7 +24,7 @@ public PublishingToMultipleSubscribersTests() registry.Register(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient(); @@ -34,7 +34,7 @@ public PublishingToMultipleSubscribersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions_Async.cs index e0e7d385f1..0aae9e7969 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_Publishing_To_Multiple_Subscribers_Should_Aggregate_Exceptions_Async.cs @@ -49,7 +49,7 @@ public PublishingToMultipleSubscribersAsyncTests() registry.RegisterAsync(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient(); @@ -59,7 +59,7 @@ public PublishingToMultipleSubscribersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers.cs index 663b2be133..005d37cbb9 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers.cs @@ -47,7 +47,7 @@ public CommandProcessorPublishMultipleMatchesTests() registry.Register(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_receivedMessages); @@ -56,7 +56,7 @@ public CommandProcessorPublishMultipleMatchesTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_Async.cs index b51f7b5cfd..2c2af0a64f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_Async.cs @@ -24,7 +24,7 @@ public CommandProcessorPublishMultipleMatchesAsyncTests() registry.RegisterAsync(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_receivedMessages); @@ -33,7 +33,7 @@ public CommandProcessorPublishMultipleMatchesAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement.cs index c0349dcfa5..b8300f1f3a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement.cs @@ -58,7 +58,7 @@ public CommandProcessorPublishMultipleMatchesAgreementTests() }, [typeof(MyEventHandler), typeof(MyOtherEventHandler)]); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_receivedMessages); @@ -68,7 +68,7 @@ public CommandProcessorPublishMultipleMatchesAgreementTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement_Async.cs index f382b0d317..a7cfa58a60 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_Multiple_Subscribers_With_Agreement_Async.cs @@ -58,7 +58,7 @@ public CommandProcessorPublishMultipleMatchesAgreementAsyncTests() }, [typeof(MyEventHandlerAsync), typeof(MyOtherEventHandlerAsync)]); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_receivedMessages); @@ -68,7 +68,7 @@ public CommandProcessorPublishMultipleMatchesAgreementAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers.cs index 03c25b2be0..4b63f55970 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers.cs @@ -40,7 +40,7 @@ public class CommandProcessorNoHandlersMatchTests public CommandProcessorNoHandlersMatchTests() { - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); _commandProcessor = new CommandProcessor( @@ -49,8 +49,8 @@ public CommandProcessorNoHandlersMatchTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers_Async.cs index cb6bd51a1e..88b36e082e 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Command_Handlers_Async.cs @@ -41,7 +41,7 @@ public class CommandProcessorNoHandlersMatchAsyncTests public CommandProcessorNoHandlersMatchAsyncTests() { - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); _commandProcessor = new CommandProcessor( @@ -50,8 +50,8 @@ public CommandProcessorNoHandlersMatchAsyncTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers.cs index f9a05184af..bfa028c103 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers.cs @@ -43,7 +43,7 @@ public CommandProcessorNoMatchingSubcribersTests() var registry = new SubscriberRegistry(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyEventHandler(_receivedMessages)); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers_Async.cs index 2758bb134f..4f0b37a729 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Publish/When_There_Are_No_Subscribers_Async.cs @@ -44,7 +44,7 @@ public CommandProcessorNoMatchingSubcribersAsyncTests() var registry = new SubscriberRegistry(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyEventHandlerAsync(_receivedMessages)); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor.cs index b0cd9909c0..0912b6d8ab 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor.cs @@ -70,7 +70,7 @@ public CommandProcessorSchedulerCommandTests() messageMapperRegistry.Register(); - var producer = new InMemoryMessageProducer(_internalBus, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + var producer = new InMemoryMessageProducer(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); @@ -89,7 +89,7 @@ public CommandProcessorSchedulerCommandTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor(registry, @@ -98,7 +98,7 @@ public CommandProcessorSchedulerCommandTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory { TimeProvider = _timeProvider }); + new InMemorySchedulerFactory (loggerFactory: Initializer.TestLoggerFactory) { TimeProvider = _timeProvider }, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor_Async.cs index 002201b447..55b74869b7 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_A_Message_To_The_Command_Processor_Async.cs @@ -53,7 +53,7 @@ public CommandProcessorSchedulerCommandAsyncTests() messageMapperRegistry.RegisterAsync(); - var producer = new InMemoryMessageProducer (_internalBus) { Publication = { Topic = routingKey, RequestType = typeof(MyCommand) } }; + var producer = new InMemoryMessageProducer (_internalBus, loggerFactory: Initializer.TestLoggerFactory) { Publication = { Topic = routingKey, RequestType = typeof(MyCommand) } }; var producerRegistry = new ProducerRegistry(new Dictionary { { routingKey, producer }, }); var resiliencePipelineRegistry = new ResiliencePipelineRegistry() .AddBrighterDefault(); @@ -69,7 +69,7 @@ public CommandProcessorSchedulerCommandAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor(registry, @@ -78,7 +78,7 @@ public CommandProcessorSchedulerCommandAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory { TimeProvider = _timeProvider }); + new InMemorySchedulerFactory (loggerFactory: Initializer.TestLoggerFactory) { TimeProvider = _timeProvider }, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter.cs index 5d725613c8..d223b5237e 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter.cs @@ -44,7 +44,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsTests() messageMapperRegistry.Register(); - var producer = new InMemoryMessageProducer(_internalBus, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + var producer = new InMemoryMessageProducer(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var producerRegistry = new ProducerRegistry(new Dictionary { { routingKey, producer }, }); var resiliencePipelineRegistry = new ResiliencePipelineRegistry() @@ -61,7 +61,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor(registry, @@ -70,7 +70,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory { TimeProvider = _timeProvider }); + new InMemorySchedulerFactory (loggerFactory: Initializer.TestLoggerFactory) { TimeProvider = _timeProvider }, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter_Async.cs index 622891be2c..c4c1eac801 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Scheduler/When_Scheduling_With_Invalid_Parameter_Async.cs @@ -45,7 +45,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsAsyncTests() messageMapperRegistry.Register(); - var producer = new InMemoryMessageProducer(_internalBus, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); + var producer = new InMemoryMessageProducer(_internalBus, Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyCommand) }); var producerRegistry = new ProducerRegistry(new Dictionary { { routingKey, producer }, }); var resiliencePipelineRegistry = new ResiliencePipelineRegistry() @@ -62,7 +62,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsAsyncTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + Initializer.TestLoggerFactory, _outbox ); _commandProcessor = new CommandProcessor(registry, @@ -71,7 +71,7 @@ public CommandProcessorSchedulerCommandWithInvalidParamsAsyncTests() new DefaultPolicy(), resiliencePipelineRegistry, bus, - new InMemorySchedulerFactory { TimeProvider = _timeProvider }); + new InMemorySchedulerFactory (loggerFactory: Initializer.TestLoggerFactory) { TimeProvider = _timeProvider }, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Cancelling_An_Async_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Cancelling_An_Async_Command.cs index 9ae411ba4b..dbe44f5aa8 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Cancelling_An_Async_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Cancelling_An_Async_Command.cs @@ -19,7 +19,7 @@ public CancellingAsyncPipelineTests() registry.RegisterAsync(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(_receivedMessages)); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_Command_To_The_Processor_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_Command_To_The_Processor_Async.cs index bd2ff92caa..a46649b8c2 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_Command_To_The_Processor_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_Command_To_The_Processor_Async.cs @@ -43,7 +43,7 @@ public CommandProcessorSendAsyncTests() registry.RegisterAsync(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(_receivedMessages)); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor.cs index a2daf05cc5..29235e2d28 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor.cs @@ -19,7 +19,7 @@ public CommandProcessorSendTests() _myCommandHandler = new MyCommandHandler(new Dictionary()); var handlerFactory = new SimpleHandlerFactorySync(_ => _myCommandHandler); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement.cs index 362d4136a2..976ade905d 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement.cs @@ -29,7 +29,7 @@ public CommandProcessorSendViaAgreementTests() var handlerFactory = new SimpleHandlerFactorySync(_ => _myCommandHandler); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); _myCommand = new MyCommand {Value = "new"}; diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement_Async.cs index 8cfc964075..7c1234126b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_Sending_A_command_To_The_Processor_Via_Agreement_Async.cs @@ -30,7 +30,7 @@ public CommandProcessorSendViaAgreementAsyncTests () var handlerFactory = new SimpleHandlerFactoryAsync(_ => _myCommandHandler); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); _myCommand = new MyCommand {Value = "new"}; diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers.cs index 2b529efdf0..af922bd327 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers.cs @@ -22,7 +22,7 @@ public CommandProcessorSendWithMultipleMatchesTests() registry.Register(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(_ => new MyCommandHandler(_receivedMessages)); container.AddTransient(); container.AddTransient>(); @@ -30,7 +30,7 @@ public CommandProcessorSendWithMultipleMatchesTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers_Async.cs index 90c1d45b41..294605e8bd 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_There_Are_Multiple_Possible_Command_Handlers_Async.cs @@ -23,7 +23,7 @@ public CommandProcessorSendWithMultipleMatchesAsyncTests() registry.RegisterAsync(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -32,7 +32,7 @@ public CommandProcessorSendWithMultipleMatchesAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_there_are_no_failures_execute_all_the_steps_in_the_pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_there_are_no_failures_execute_all_the_steps_in_the_pipeline.cs index 235518f0b5..52df821265 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_there_are_no_failures_execute_all_the_steps_in_the_pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Send/When_there_are_no_failures_execute_all_the_steps_in_the_pipeline.cs @@ -17,7 +17,7 @@ public CommandProcessorPipelineStepsTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddTransient>(); @@ -25,7 +25,7 @@ public CommandProcessorPipelineStepsTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_async_mapper_is_unresolvable_the_reply_does_not_fall_through_to_sync.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_async_mapper_is_unresolvable_the_reply_does_not_fall_through_to_sync.cs index 79c37dddc1..3c6eba6c17 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_async_mapper_is_unresolvable_the_reply_does_not_fall_through_to_sync.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_async_mapper_is_unresolvable_the_reply_does_not_fall_through_to_sync.cs @@ -33,7 +33,7 @@ public MediatorUnresolvableMapperReplyTests() var timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = new(new InternalBus(), - new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); //sync mapper works; the async mapper type is registered but its factory cannot instantiate it var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +55,7 @@ public MediatorUnresolvableMapperReplyTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer } + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer } ); //a genuinely round-trippable reply, so that on master the sync fall-through would have succeeded diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_registered_mapper_type_is_unresolvable_the_send_throws_a_configuration_error.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_registered_mapper_type_is_unresolvable_the_send_throws_a_configuration_error.cs index 9c2396c08b..56be3381fe 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_registered_mapper_type_is_unresolvable_the_send_throws_a_configuration_error.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/UnresolvableMapper/When_the_registered_mapper_type_is_unresolvable_the_send_throws_a_configuration_error.cs @@ -30,7 +30,7 @@ public MediatorUnresolvableMapperSendTests() var timeProvider = new FakeTimeProvider(); InMemoryMessageProducer messageProducer = new(new InternalBus(), - new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = _routingKey, RequestType = typeof(MyCommand) }); //the type is registered, but the factory cannot instantiate it (Create returns null) var messageMapperRegistry = new MessageMapperRegistry(new NullReturningMapperFactory(), null); @@ -49,7 +49,7 @@ public MediatorUnresolvableMapperSendTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - new InMemoryOutbox(timeProvider) { Tracer = tracer } + Initializer.TestLoggerFactory, new InMemoryOutbox(timeProvider) { Tracer = tracer } ); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_A_Request_Context_Is_Provided.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_A_Request_Context_Is_Provided.cs index f8e279ff61..f5a841db05 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_A_Request_Context_Is_Provided.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_A_Request_Context_Is_Provided.cs @@ -15,14 +15,14 @@ public class RequestContextPresentTests : IDisposable { private readonly SpyContextFactory _requestContextFactory; private readonly IPolicyRegistry _policyRegistry; - private readonly ResiliencePipelineRegistry _resiliencePipelineRegistry; + private readonly ResiliencePipelineRegistry _resiliencePipelineRegistry; public RequestContextPresentTests() { - MyContextAwareCommandHandler.TestString = null; - MyContextAwareCommandHandlerAsync.TestString = null; - MyContextAwareEventHandler.TestString = null; - MyContextAwareEventHandlerAsync.TestString = null; + MyContextAwareCommandHandler.TestString = null; + MyContextAwareCommandHandlerAsync.TestString = null; + MyContextAwareEventHandler.TestString = null; + MyContextAwareEventHandlerAsync.TestString = null; _policyRegistry = new DefaultPolicy(); _resiliencePipelineRegistry = new ResiliencePipelineRegistry().AddBrighterDefault(); @@ -45,13 +45,13 @@ public void When_A_Request_Context_Is_Provided_On_A_Send() spyRequestContextFactory, policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); var testBagValue = Guid.NewGuid().ToString(); - context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue) ; + context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue); commandProcessor.Send(new MyCommand(), context); //assert @@ -77,8 +77,8 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Send_Async() spyRequestContextFactory, policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); @@ -107,8 +107,8 @@ public void When_A_Request_Context_Is_Provided_On_A_Publish() _requestContextFactory, _policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); @@ -137,8 +137,8 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Publish_Async() _requestContextFactory, _policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); @@ -168,14 +168,14 @@ public void When_A_Request_Context_Is_Provided_On_A_Deposit() var producerRegistry = new ProducerRegistry(new Dictionary { - { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) + { + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) }, }); var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); - var fakeOutbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; + var fakeOutbox = new InMemoryOutbox(timeProvider) { Tracer = tracer }; var bus = new OutboxProducerMediator( producerRegistry, @@ -185,7 +185,7 @@ public void When_A_Request_Context_Is_Provided_On_A_Deposit() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -193,13 +193,13 @@ public void When_A_Request_Context_Is_Provided_On_A_Deposit() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); var testBagValue = Guid.NewGuid().ToString(); - context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue) ; + context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue); commandProcessor.DepositPost(new MyCommand(), context); //assert @@ -221,13 +221,13 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Deposit_Async() var producerRegistry = new ProducerRegistry(new Dictionary { - { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) + { + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) }, }); var tracer = new BrighterTracer(timeProvider); - var fakeOutbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; + var fakeOutbox = new InMemoryOutbox(timeProvider) { Tracer = tracer }; var bus = new OutboxProducerMediator( producerRegistry, @@ -237,7 +237,7 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Deposit_Async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -245,8 +245,8 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Deposit_Async() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act var context = new RequestContext(); @@ -273,11 +273,11 @@ public void When_A_Request_Context_Is_Provided_On_A_Clear() var producerRegistry = new ProducerRegistry(new Dictionary { - { routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey})} + { routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey})} }); var tracer = new BrighterTracer(timeProvider); - var fakeOutbox = new InMemoryOutbox(timeProvider) {Tracer = tracer}; + var fakeOutbox = new InMemoryOutbox(timeProvider) { Tracer = tracer }; var bus = new OutboxProducerMediator( producerRegistry, @@ -287,7 +287,7 @@ public void When_A_Request_Context_Is_Provided_On_A_Clear() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -295,18 +295,18 @@ public void When_A_Request_Context_Is_Provided_On_A_Clear() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); - var myCommand = new MyCommand() {Id = Guid.NewGuid().ToString()}; + var myCommand = new MyCommand() { Id = Guid.NewGuid().ToString() }; var message = new Message(new MessageHeader(myCommand.Id, new("MyCommand"), MessageType.MT_COMMAND), new MessageBody("test content")); bus.AddToOutbox(message, new RequestContext()); //act var context = new RequestContext(); var testBagValue = Guid.NewGuid().ToString(); - context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue) ; - commandProcessor.ClearOutbox(new []{myCommand.Id}, context); + context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue); + commandProcessor.ClearOutbox(new[] { myCommand.Id }, context); //assert Assert.False(_requestContextFactory.CreateWasCalled); @@ -327,8 +327,8 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() var producerRegistry = new ProducerRegistry(new Dictionary { - { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey} ) + { + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey} ) }, }); @@ -343,7 +343,7 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -351,17 +351,17 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); - var myCommand = new MyCommand() {Id = Guid.NewGuid().ToString()}; + var myCommand = new MyCommand() { Id = Guid.NewGuid().ToString() }; var message = new Message(new MessageHeader(myCommand.Id, new("MyCommand"), MessageType.MT_COMMAND), new MessageBody("test content")); bus.AddToOutbox(message, new RequestContext()); //act var context = new RequestContext(); var testBagValue = Guid.NewGuid().ToString(); - context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue) ; + context.Bag.AddOrUpdate("TestString", testBagValue, (_, _) => testBagValue); await commandProcessor.ClearOutboxAsync([myCommand.Id], context); //assert diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs index 4ea8805d77..0e659af044 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs @@ -38,7 +38,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Send() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyContextAwareCommandHandler()); var myCommand = new MyCommand(); - var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); //act commandProcessor.Send(myCommand); @@ -58,7 +58,7 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Send_Async() var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyContextAwareCommandHandlerAsync()); var myCommand = new MyCommand(); - var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); //act await commandProcessor.SendAsync(myCommand); @@ -78,7 +78,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Publish() var handlerFactory = new SimpleHandlerFactorySync(_ => new MyContextAwareEventHandler()); var myEvent = new MyEvent(); - var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); //act commandProcessor.Publish(myEvent); @@ -98,7 +98,7 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Publish_Async() var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyContextAwareEventHandlerAsync()); var myEvent = new MyEvent(); - var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); //act await commandProcessor.PublishAsync(myEvent); @@ -124,7 +124,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Deposit() new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) } }); @@ -139,7 +139,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Deposit() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -147,8 +147,8 @@ public void When_No_Request_Context_Is_Provided_On_A_Deposit() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act commandProcessor.DepositPost(new MyCommand()); @@ -172,7 +172,7 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Deposit_Async() new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication{RequestType = typeof(MyCommand), Topic = routingKey}) }, }); @@ -187,7 +187,7 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Deposit_Async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -195,8 +195,8 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Deposit_Async() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); //act await commandProcessor.DepositPostAsync(new MyCommand()); @@ -220,7 +220,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Clear() var producerRegistry = new ProducerRegistry(new Dictionary { - { routingKey, new InMemoryMessageProducer(new InternalBus(), instrumentationOptions:InstrumentationOptions.All) + { routingKey, new InMemoryMessageProducer(new InternalBus(), instrumentationOptions:InstrumentationOptions.All, loggerFactory: Initializer.TestLoggerFactory) { Publication = new Publication{RequestType = typeof(MyCommand), Topic = routingKey} } }, @@ -237,7 +237,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Clear() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -245,8 +245,8 @@ public void When_No_Request_Context_Is_Provided_On_A_Clear() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var myCommand = new MyCommand() {Id = Guid.NewGuid().ToString()}; var message = new Message(new MessageHeader(myCommand.Id, routingKey, MessageType.MT_COMMAND), new MessageBody("test content")); @@ -274,7 +274,7 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() var producerRegistry = new ProducerRegistry(new Dictionary { - { routingKey, new InMemoryMessageProducer(new InternalBus(), instrumentationOptions:InstrumentationOptions.All) + { routingKey, new InMemoryMessageProducer(new InternalBus(), instrumentationOptions:InstrumentationOptions.All, loggerFactory: Initializer.TestLoggerFactory) { Publication = new Publication{RequestType = typeof(MyCommand), Topic = routingKey} } }, @@ -291,7 +291,7 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - fakeOutbox + Initializer.TestLoggerFactory, fakeOutbox ); var commandProcessor = new CommandProcessor( @@ -299,8 +299,8 @@ public async Task When_A_Request_Context_Is_Provided_On_A_Clear_Async() _policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var myCommand = new MyCommand() {Id = Guid.NewGuid().ToString()}; var message = new Message(new MessageHeader(myCommand.Id, routingKey, MessageType.MT_COMMAND), new MessageBody("test content")); diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_log_warning_with_id_and_topic.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_log_warning_with_id_and_topic.cs index f23367e08d..5026155dea 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_log_warning_with_id_and_topic.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_log_warning_with_id_and_topic.cs @@ -45,7 +45,7 @@ public ConfirmationFailureWarningLogTests() { // Arrange: an InMemory producer whose publish confirmation always fails var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -66,7 +66,7 @@ public ConfirmationFailureWarningLogTests() new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer: null, - new FindPublicationByPublicationTopicOrRequestType()); + new FindPublicationByPublicationTopicOrRequestType(), loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_not_dispatch_or_bubble.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_not_dispatch_or_bubble.cs index 1558b655b6..2c8c03f97c 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_not_dispatch_or_bubble.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_not_dispatch_or_bubble.cs @@ -50,7 +50,7 @@ public ConfirmationFailureNoDispatchTests() // deterministic. var bus = new InternalBus(); _outbox = new InMemoryOutbox(_timeProvider); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -73,7 +73,7 @@ public ConfirmationFailureNoDispatchTests() tracer: null, new FindPublicationByPublicationTopicOrRequestType(), outbox: _outbox, - timeProvider: _timeProvider); + timeProvider: _timeProvider, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_trip_topic_on_wire_topic.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_trip_topic_on_wire_topic.cs index 71243296ca..bd88aaaf92 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_trip_topic_on_wire_topic.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_should_trip_topic_on_wire_topic.cs @@ -49,7 +49,7 @@ public ConfirmationFailureBreakerTripTests() { // Arrange: an InMemory producer whose publish confirmation always fails, wired to a // mediator that owns a real circuit breaker. - _producer = new InMemoryMessageProducer(_bus, new Publication { Topic = _publicationTopic }) + _producer = new InMemoryMessageProducer(_bus, Initializer.TestLoggerFactory, new Publication { Topic = _publicationTopic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -72,7 +72,7 @@ public ConfirmationFailureBreakerTripTests() new EmptyMessageTransformerFactoryAsync(), tracer: null, new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: _circuitBreaker); + outboxCircuitBreaker: _circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); } private static Message MessageWithWireTopic(RoutingKey wireTopic) => diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_with_empty_id_should_still_observe.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_with_empty_id_should_still_observe.cs index f7d944d0f5..fda076b01f 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_with_empty_id_should_still_observe.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_fails_with_empty_id_should_still_observe.cs @@ -65,7 +65,7 @@ public ConfirmationFailureEmptyIdTests() _tracer = new BrighterTracer(); var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -85,7 +85,7 @@ public ConfirmationFailureEmptyIdTests() new EmptyMessageTransformerFactoryAsync(), tracer: _tracer, new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: _circuitBreaker); + outboxCircuitBreaker: _circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); } public void Dispose() diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_is_received_should_emit_linked_span.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_is_received_should_emit_linked_span.cs index 642d8a819b..72c28e5892 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_is_received_should_emit_linked_span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_is_received_should_emit_linked_span.cs @@ -71,7 +71,7 @@ public void Dispose() private InMemoryMessageProducer BuildConfirmingProducer(bool fail) { var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + var producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = fail ? _ => true : null @@ -90,7 +90,7 @@ private InMemoryMessageProducer BuildConfirmingProducer(bool fail) new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer: _tracer, - new FindPublicationByPublicationTopicOrRequestType()); + new FindPublicationByPublicationTopicOrRequestType(), loggerFactory: Initializer.TestLoggerFactory); return producer; } diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_span_ends_should_use_tracer_clock_and_status.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_span_ends_should_use_tracer_clock_and_status.cs index 475a1196da..930b4409f8 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_span_ends_should_use_tracer_clock_and_status.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_span_ends_should_use_tracer_clock_and_status.cs @@ -69,7 +69,7 @@ public ConfirmationSpanEndTests() var bus = new InternalBus(); _outbox = new InMemoryOutbox(_timeProvider); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true // PublishFailurePredicate not set => every confirmation succeeds (ack) @@ -89,7 +89,7 @@ public ConfirmationSpanEndTests() tracer: _tracer, new FindPublicationByPublicationTopicOrRequestType(), outbox: _outbox, - timeProvider: _timeProvider); + timeProvider: _timeProvider, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_succeeds_should_nest_dispatch_under_span.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_succeeds_should_nest_dispatch_under_span.cs index 8ad2a05e8a..c6d54d90e1 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_succeeds_should_nest_dispatch_under_span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirmation_succeeds_should_nest_dispatch_under_span.cs @@ -73,7 +73,7 @@ public ConfirmationSuccessNestedSpanTests() var bus = new InternalBus(); _outbox = new InMemoryOutbox(_timeProvider); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true // PublishFailurePredicate not set => every confirmation succeeds (ack) @@ -96,7 +96,7 @@ public ConfirmationSuccessNestedSpanTests() new FindPublicationByPublicationTopicOrRequestType(), outbox: _outbox, outboxCircuitBreaker: _circuitBreaker, - timeProvider: _timeProvider); + timeProvider: _timeProvider, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirming_bulk_producer_confirmation_fails.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirming_bulk_producer_confirmation_fails.cs index 0f4942eb30..cc725db9f2 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirming_bulk_producer_confirmation_fails.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_a_confirming_bulk_producer_confirmation_fails.cs @@ -56,7 +56,7 @@ public BulkDispatchConfirmingProducerConfirmationFailsTests() // clock keeps the outbox outstanding/dispatched windows deterministic. var bus = new InternalBus(); _outbox = new InMemoryOutbox(_timeProvider); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -78,7 +78,7 @@ public BulkDispatchConfirmingProducerConfirmationFailsTests() new FindPublicationByPublicationTopicOrRequestType(), outbox: _outbox, outboxCircuitBreaker: _circuitBreaker, - timeProvider: _timeProvider); + timeProvider: _timeProvider, loggerFactory: Initializer.TestLoggerFactory); } private Message MessageOn(RoutingKey topic) => new( diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_broker_style_producer_confirms_should_await_dispatch.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_broker_style_producer_confirms_should_await_dispatch.cs index b151e7f4a6..ff5cb8e4f2 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_broker_style_producer_confirms_should_await_dispatch.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_broker_style_producer_confirms_should_await_dispatch.cs @@ -103,7 +103,7 @@ private static void ConfigureMediator(StubConfirmingProducerAsync producer, IAmA new EmptyMessageTransformerFactoryAsync(), tracer: null, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, new InMemoryOutboxCircuitBreaker()); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_bulk_dispatching_a_confirming_producer.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_bulk_dispatching_a_confirming_producer.cs index 8c13c62938..430522c939 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_bulk_dispatching_a_confirming_producer.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_bulk_dispatching_a_confirming_producer.cs @@ -62,7 +62,7 @@ public BulkDispatchConfirmingProducerTests() // outstanding/dispatched windows deterministic. var bus = new InternalBus(); _outbox = new InMemoryOutbox(_timeProvider); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true }; @@ -83,7 +83,7 @@ public BulkDispatchConfirmingProducerTests() new FindPublicationByPublicationTopicOrRequestType(), outbox: _outbox, outboxCircuitBreaker: _circuitBreaker, - timeProvider: _timeProvider); + timeProvider: _timeProvider, loggerFactory: Initializer.TestLoggerFactory); } private Message MessageOn(RoutingKey topic) => new( diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_concurrent_same_topic_confirmations_fail_should_not_lose_trips.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_concurrent_same_topic_confirmations_fail_should_not_lose_trips.cs index 987240247d..2cbc7f738e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_concurrent_same_topic_confirmations_fail_should_not_lose_trips.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_concurrent_same_topic_confirmations_fail_should_not_lose_trips.cs @@ -54,7 +54,7 @@ public ConcurrentConfirmationFailureTripTests() // Arrange: a producer whose confirmations always fail, wired to a mediator whose tracer // gates every callback on a barrier so concurrent sends trip the breaker concurrently. var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { PublishFailurePredicate = _ => true }; @@ -72,7 +72,7 @@ public ConcurrentConfirmationFailureTripTests() new EmptyMessageTransformerFactoryAsync(), tracer: new GatingConfirmationTracer(_barrier), new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: _circuitBreaker); + outboxCircuitBreaker: _circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); } private Message NewMessage() => new( diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_confirmation_dispatch_throws_should_isolate_and_log.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_confirmation_dispatch_throws_should_isolate_and_log.cs index 683f5d9994..03426365f2 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_confirmation_dispatch_throws_should_isolate_and_log.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_confirmation_dispatch_throws_should_isolate_and_log.cs @@ -50,7 +50,7 @@ public ConfirmationDispatchIsolationTests() // span). The tracer is null so the observability block is a no-op and the only thing that can // throw inside the callback is the breaker trip. var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -69,7 +69,7 @@ public ConfirmationDispatchIsolationTests() new EmptyMessageTransformerFactoryAsync(), tracer: null, new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: _circuitBreaker); + outboxCircuitBreaker: _circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_disposing_async_confirmation_producer_should_await_callback.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_disposing_async_confirmation_producer_should_await_callback.cs index 0a1893f598..511326317e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_disposing_async_confirmation_producer_should_await_callback.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_disposing_async_confirmation_producer_should_await_callback.cs @@ -48,7 +48,7 @@ public async Task When_disposing_async_confirmation_producer_should_await_callba var message = CreateMessage(); var outbox = new GatedAsyncOutbox(); await outbox.AddAsync(message, requestContext); - var producer = new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = s_topic }) + var producer = new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = s_topic }) { UseAsyncPublishConfirmation = true }; @@ -82,7 +82,7 @@ public async Task When_async_confirmation_is_off_should_not_wait_for_async_dispa var message = CreateMessage(); var outbox = new GatedAsyncOutbox(); await outbox.AddAsync(message, requestContext); - var producer = new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = s_topic }); + var producer = new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = s_topic }); ConfigureMediator(producer, outbox); // Act @@ -106,7 +106,7 @@ public async Task When_async_confirmation_is_off_should_not_wait_for_async_dispa public async Task When_disposing_with_concurrent_sends_should_drain_every_confirmation() { // Arrange - var producer = new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = s_topic }) + var producer = new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = s_topic }) { UseAsyncPublishConfirmation = true }; @@ -132,7 +132,7 @@ public async Task When_disposing_with_concurrent_sends_should_drain_every_confir public async Task When_an_async_confirmation_subscriber_throws_dispose_still_drains() { // Arrange - var producer = new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = s_topic }) + var producer = new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = s_topic }) { UseAsyncPublishConfirmation = true }; @@ -174,7 +174,7 @@ private static void ConfigureMediator(InMemoryMessageProducer producer, IAmAnOut new EmptyMessageTransformerFactoryAsync(), tracer: null, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, new InMemoryOutboxCircuitBreaker()); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_ending_confirmation_span_throws_should_continue_draining.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_ending_confirmation_span_throws_should_continue_draining.cs index 91aaf4bf58..d172bd3995 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_ending_confirmation_span_throws_should_continue_draining.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_ending_confirmation_span_throws_should_continue_draining.cs @@ -45,7 +45,7 @@ public async Task When_ending_confirmation_span_throws_should_continue_draining( const int messageCount = 2; var topic = new RoutingKey("Confirmation.EndSpan.Throws.Topic"); var circuitBreaker = new InMemoryOutboxCircuitBreaker(); - var producer = new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = topic }) + var producer = new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -63,7 +63,7 @@ public async Task When_ending_confirmation_span_throws_should_continue_draining( new EmptyMessageTransformerFactoryAsync(), tracer: new ThrowingConfirmationTracer(throwOnEndSpan: true), new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: circuitBreaker); + outboxCircuitBreaker: circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); using var context = TestCorrelator.CreateContext(); diff --git a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_observability_throws_should_isolate_and_still_trip.cs b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_observability_throws_should_isolate_and_still_trip.cs index 3f5c3b628d..86c83b9e3d 100644 --- a/tests/Paramore.Brighter.Core.Tests/Confirmation/When_observability_throws_should_isolate_and_still_trip.cs +++ b/tests/Paramore.Brighter.Core.Tests/Confirmation/When_observability_throws_should_isolate_and_still_trip.cs @@ -49,7 +49,7 @@ public ConfirmationObservabilityIsolationTests() // Arrange: a confirmation that always fails, wired to a mediator whose tracer throws from // CreateConfirmationSpan — modelling an observability fault inside the callback. var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus, new Publication { Topic = _topic }) + _producer = new InMemoryMessageProducer(bus, Initializer.TestLoggerFactory, new Publication { Topic = _topic }) { UseAsyncPublishConfirmation = true, PublishFailurePredicate = _ => true @@ -68,7 +68,7 @@ public ConfirmationObservabilityIsolationTests() new EmptyMessageTransformerFactoryAsync(), tracer: new ThrowingConfirmationTracer(), new FindPublicationByPublicationTopicOrRequestType(), - outboxCircuitBreaker: _circuitBreaker); + outboxCircuitBreaker: _circuitBreaker, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(new Id(Guid.NewGuid().ToString()), _topic, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_configuring_a_control_bus.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_configuring_a_control_bus.cs index 6ac41e7f5a..f5142f751d 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_configuring_a_control_bus.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_configuring_a_control_bus.cs @@ -20,13 +20,13 @@ public ControlBusBuilderTests() var bus = new InternalBus(); _busReceiverBuilder = (ControlBusReceiverBuilder - .With() + .With(Initializer.TestLoggerFactory) .Dispatcher(dispatcher) .ProducerRegistryFactory(new InMemoryProducerRegistryFactory(bus, [ new Publication{Topic = new RoutingKey("MyTopic"), RequestType = typeof(ConfigurationCommand)} - ], InstrumentationOptions.All)) - .ChannelFactory(new InMemoryChannelFactory(bus, TimeProvider.System)) as ControlBusReceiverBuilder)!; + ], Initializer.TestLoggerFactory, InstrumentationOptions.All)) + .ChannelFactory(new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory)) as ControlBusReceiverBuilder)!; } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_creating_a_control_bus_sender.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_creating_a_control_bus_sender.cs index bbc8fd63ed..25cdf1d6b7 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_creating_a_control_bus_sender.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_creating_a_control_bus_sender.cs @@ -16,9 +16,9 @@ public class ControlBusSenderFactoryTests public ControlBusSenderFactoryTests() { _outbox = new InMemoryOutbox(TimeProvider.System); - _gateway = new InMemoryMessageProducer(new InternalBus()); + _gateway = new InMemoryMessageProducer(new InternalBus(), loggerFactory: Initializer.TestLoggerFactory); - _senderFactory = new ControlBusSenderFactory(); + _senderFactory = new ControlBusSenderFactory(loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_start_message_for_a_connection.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_start_message_for_a_connection.cs index d3fd10319d..3ac8632258 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_start_message_for_a_connection.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_start_message_for_a_connection.cs @@ -40,7 +40,7 @@ public class ConfigurationCommandStartTests public ConfigurationCommandStartTests() { _dispatcher = A.Fake(); - _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher); + _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)); _configurationCommand = new ConfigurationCommand(ConfigurationCommandType.CM_STARTCHANNEL, new SubscriptionName(SubscriptionName)); } diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_stop_message_for_a_connection.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_stop_message_for_a_connection.cs index 6a0d358d3b..417f2206a7 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_stop_message_for_a_connection.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_a_stop_message_for_a_connection.cs @@ -16,7 +16,7 @@ public class ConfigurationCommandStopTests public ConfigurationCommandStopTests() { _dispatcher = A.Fake(); - _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher); + _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)); _configurationCommand = new ConfigurationCommand(ConfigurationCommandType.CM_STOPCHANNEL, new SubscriptionName(SUBSCRIPTION_NAME)); } diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_start_message.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_start_message.cs index 4595ada73c..bd0ac809b0 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_start_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_start_message.cs @@ -39,7 +39,7 @@ public class ConfigurationCommandAllStartTests public ConfigurationCommandAllStartTests() { _dispatcher = A.Fake(); - _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher); + _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)); _configurationCommand = new ConfigurationCommand(ConfigurationCommandType.CM_STARTALL, ""); } diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_stop_message.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_stop_message.cs index d58607b705..c413df6876 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_stop_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_receiving_an_all_stop_message.cs @@ -39,7 +39,7 @@ public class ConfigurationCommandAllStopTests public ConfigurationCommandAllStopTests() { _dispatcher = A.Fake(); - _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher); + _configurationCommandHandler = new ConfigurationCommandHandler(_dispatcher, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)); _configurationCommand = new ConfigurationCommand(ConfigurationCommandType.CM_STOPALL, ""); } diff --git a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_we_build_a_control_bus_we_can_send_configuration_messages_to_it.cs b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_we_build_a_control_bus_we_can_send_configuration_messages_to_it.cs index 92960241d3..5db2997c21 100644 --- a/tests/Paramore.Brighter.Core.Tests/ControlBus/When_we_build_a_control_bus_we_can_send_configuration_messages_to_it.cs +++ b/tests/Paramore.Brighter.Core.Tests/ControlBus/When_we_build_a_control_bus_we_can_send_configuration_messages_to_it.cs @@ -24,14 +24,14 @@ public ControlBusTests() var bus = new InternalBus(); ControlBusReceiverBuilder busReceiverBuilder = (ControlBusReceiverBuilder) ControlBusReceiverBuilder - .With() + .With(Initializer.TestLoggerFactory) .Dispatcher(_dispatcher) .ProducerRegistryFactory(new InMemoryProducerRegistryFactory( bus, [ new Publication{Topic = topic, RequestType = typeof(ConfigurationCommand)} - ], InstrumentationOptions.All)) - .ChannelFactory(new InMemoryChannelFactory(bus, TimeProvider.System)); + ], Initializer.TestLoggerFactory, InstrumentationOptions.All)) + .ChannelFactory(new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory)); _controlBus = busReceiverBuilder.Build("tests"); diff --git a/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_succeeds_should_not_defer_message.cs b/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_succeeds_should_not_defer_message.cs index 0d0a360fe2..be4ef0f034 100644 --- a/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_succeeds_should_not_defer_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_succeeds_should_not_defer_message.cs @@ -48,7 +48,7 @@ public When_async_handler_succeeds_should_not_defer_message() if (type == typeof(MySucceedingDeferHandlerAsync)) return new MySucceedingDeferHandlerAsync(); if (type == typeof(DeferMessageOnErrorHandlerAsync)) - return new DeferMessageOnErrorHandlerAsync(); + return new DeferMessageOnErrorHandlerAsync(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -60,8 +60,8 @@ public When_async_handler_succeeds_should_not_defer_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_throws_exception_should_defer_message.cs b/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_throws_exception_should_defer_message.cs index ae5dee1798..1038b25b18 100644 --- a/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_throws_exception_should_defer_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Defer/When_async_handler_throws_exception_should_defer_message.cs @@ -49,7 +49,7 @@ public When_async_handler_throws_exception_should_defer_message() if (type == typeof(MyFailingDeferHandlerAsync)) return new MyFailingDeferHandlerAsync(); if (type == typeof(DeferMessageOnErrorHandlerAsync)) - return new DeferMessageOnErrorHandlerAsync(); + return new DeferMessageOnErrorHandlerAsync(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -61,8 +61,8 @@ public When_async_handler_throws_exception_should_defer_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_succeeds_should_not_defer_message.cs b/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_succeeds_should_not_defer_message.cs index 492ac1a7f4..10c015e8fd 100644 --- a/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_succeeds_should_not_defer_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_succeeds_should_not_defer_message.cs @@ -47,7 +47,7 @@ public When_handler_succeeds_should_not_defer_message() if (type == typeof(MySucceedingDeferHandler)) return new MySucceedingDeferHandler(); if (type == typeof(DeferMessageOnErrorHandler)) - return new DeferMessageOnErrorHandler(); + return new DeferMessageOnErrorHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -59,8 +59,8 @@ public When_handler_succeeds_should_not_defer_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_throws_exception_should_defer_message.cs b/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_throws_exception_should_defer_message.cs index 9bc017b8f8..3a9e79abad 100644 --- a/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_throws_exception_should_defer_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Defer/When_handler_throws_exception_should_defer_message.cs @@ -48,7 +48,7 @@ public When_handler_throws_exception_should_defer_message() if (type == typeof(MyFailingDeferHandler)) return new MyFailingDeferHandler(); if (type == typeof(DeferMessageOnErrorHandler)) - return new DeferMessageOnErrorHandler(); + return new DeferMessageOnErrorHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -60,8 +60,8 @@ public When_handler_throws_exception_should_defer_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/DontAck/When_async_handler_throws_exception_should_dont_ack_message.cs b/tests/Paramore.Brighter.Core.Tests/DontAck/When_async_handler_throws_exception_should_dont_ack_message.cs index 83e0d533e9..edca9392a1 100644 --- a/tests/Paramore.Brighter.Core.Tests/DontAck/When_async_handler_throws_exception_should_dont_ack_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/DontAck/When_async_handler_throws_exception_should_dont_ack_message.cs @@ -61,8 +61,8 @@ public When_async_handler_throws_exception_should_dont_ack_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/DontAck/When_handler_throws_exception_should_dont_ack_message.cs b/tests/Paramore.Brighter.Core.Tests/DontAck/When_handler_throws_exception_should_dont_ack_message.cs index 1264ed575f..d002f4ad97 100644 --- a/tests/Paramore.Brighter.Core.Tests/DontAck/When_handler_throws_exception_should_dont_ack_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/DontAck/When_handler_throws_exception_should_dont_ack_message.cs @@ -60,8 +60,8 @@ public When_handler_throws_exception_should_dont_ack_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_A_Fallback_Is_Broken_Ciruit_Only.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_A_Fallback_Is_Broken_Ciruit_Only.cs index 9319a8ce4d..74e8884e6b 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_A_Fallback_Is_Broken_Ciruit_Only.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_A_Fallback_Is_Broken_Ciruit_Only.cs @@ -22,7 +22,7 @@ public FallbackHandlerBrokenCircuitTests() registry.Register(); var policyRegistry = new PolicyRegistry(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -33,7 +33,7 @@ public FallbackHandlerBrokenCircuitTests() MyFailsWithFallbackDivideByZeroHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_A_Broken_Circuit_Exception_Can_Fallback.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_A_Broken_Circuit_Exception_Can_Fallback.cs index 7d8a3deaf2..55966f2681 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_A_Broken_Circuit_Exception_Can_Fallback.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_A_Broken_Circuit_Exception_Can_Fallback.cs @@ -44,7 +44,7 @@ public FallbackHandlerBrokenCircuitOnErrorTests() registry.Register(); var policyRegistry = new PolicyRegistry(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -54,7 +54,7 @@ public FallbackHandlerBrokenCircuitOnErrorTests() MyFailsWithFallbackDivideByZeroHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Can_Fallback.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Can_Fallback.cs index 0cc140eb7a..42cd4b3c05 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Can_Fallback.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Can_Fallback.cs @@ -44,7 +44,7 @@ public FallbackHandlerOnExceptionTests() registry.Register(); var policyRegistry = new PolicyRegistry(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -53,7 +53,7 @@ public FallbackHandlerOnExceptionTests() MyFailsWithFallbackDivideByZeroHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Run_Fallback_Chain.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Run_Fallback_Chain.cs index 2fae1bf89b..ec98bb0de4 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Run_Fallback_Chain.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Raising_An_Exception_Run_Fallback_Chain.cs @@ -45,7 +45,7 @@ public FallbackHandlerPipelineRunOnExceptionTests() registry.Register(); var policyRegistry = new PolicyRegistry(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton>(); @@ -56,7 +56,7 @@ public FallbackHandlerPipelineRunOnExceptionTests() MyFailsWithFallbackMultipleHandlers.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry.cs index d82d9a248f..4327252eba 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry.cs @@ -22,7 +22,7 @@ public CommandProcessorMissingPolicyFromRegistryTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingPolicyFromRegistryTests() MyDoesNotFailPolicyHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry_Async.cs index ceb87bc8b2..6859f20b72 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_Policy_Is_Not_In_The_Registry_Async.cs @@ -23,7 +23,7 @@ public CommandProcessorMissingPolicyFromRegistryAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingPolicyFromRegistryAsyncTests() MyDoesNotFailPolicyHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry.cs index c36044c016..a72237d525 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry.cs @@ -22,7 +22,7 @@ public CommandProcessorMissingResiliencePipelineFromRegistryTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingResiliencePipelineFromRegistryTests() MyDoesNotFailResiliencePipelineHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry_Async.cs index 64faf1fabb..8cd1c89925 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_ResiliencePipeline_Is_Not_In_The_Registry_Async.cs @@ -23,7 +23,7 @@ public CommandProcessorMissingResiliencePipelineFromRegistryAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingResiliencePipelineFromRegistryAsyncTests() MyDoesNotFailResiliencePipelineHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry.cs index 8ea15766e4..f6167aafda 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry.cs @@ -22,7 +22,7 @@ public CommandProcessorMissingTypeResiliencePipelineFromRegistryTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingTypeResiliencePipelineFromRegistryTests() MyDoesNotFailTypeResiliencePipelineHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry_Async.cs index 50049fbcfd..4004a22262 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_And_The_TypeResiliencePipeline_Is_Not_In_The_Registry_Async.cs @@ -23,7 +23,7 @@ public CommandProcessorMissingTypeResiliencePipelineFromRegistryAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -32,7 +32,7 @@ public CommandProcessorMissingTypeResiliencePipelineFromRegistryAsyncTests() MyDoesNotFailTypeResiliencePipelineHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Multiple_Policy_Checks.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Multiple_Policy_Checks.cs index d0c19cb0ff..2e1e8fa2bb 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Multiple_Policy_Checks.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Multiple_Policy_Checks.cs @@ -21,7 +21,7 @@ public CommandProcessorWithMultipleExceptionPoliciesNothingThrowTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions() @@ -50,7 +50,7 @@ public CommandProcessorWithMultipleExceptionPoliciesNothingThrowTests() MyDoesNotFailMultiplePoliciesHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Policy_Check.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Policy_Check.cs index 090f1259e2..235d54edac 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Policy_Check.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_Policy_Check.cs @@ -21,7 +21,7 @@ public CommandProcessorWithExceptionPolicyNothingThrowTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithExceptionPolicyNothingThrowTests() MyDoesNotFailPolicyHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_ResiliencePipeline_Check.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_ResiliencePipeline_Check.cs index bb8650f749..dccab2691a 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_ResiliencePipeline_Check.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_ResiliencePipeline_Check.cs @@ -23,7 +23,7 @@ public CommandProcessorWithExceptionResiliencePipelineNothingThrowTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithExceptionResiliencePipelineNothingThrowTests() MyDoesNotFailResiliencePipelineHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_TypeResiliencePipeline_Check.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_TypeResiliencePipeline_Check.cs index 30675bff30..9cb73e755d 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_TypeResiliencePipeline_Check.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Passes_TypeResiliencePipeline_Check.cs @@ -23,7 +23,7 @@ public CommandProcessorWithExceptionTypeResiliencePipelineNothingThrowTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithExceptionTypeResiliencePipelineNothingThrowTests() MyDoesNotFailTypeResiliencePipelineHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit.cs index 3d572c65ee..6e73c31130 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit.cs @@ -25,7 +25,7 @@ public CommandProcessorWithCircuitBreakerTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -44,7 +44,7 @@ public CommandProcessorWithCircuitBreakerTests() MyFailsWithDivideByZeroHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + policyRegistry, new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_Async.cs index 9324f7c871..7d4f10ba99 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_Async.cs @@ -26,7 +26,7 @@ public CommandProcessorWithCircuitBreakerAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithCircuitBreakerAsyncTests() MyFailsWithDivideByZeroHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs index a229d04c1a..a49cd7f5c7 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs @@ -25,7 +25,7 @@ public CommandProcessorWithCircuitBreakerAndResiliencePipelineTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithCircuitBreakerAndResiliencePipelineTests() MyFailsWithDivideByZeroWithResiliencePipelineHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), resiliencePipeline, new InMemorySchedulerFactory()); + new PolicyRegistry(), resiliencePipeline, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit.cs index 7ba336c61c..faec0b1fa6 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit.cs @@ -26,7 +26,7 @@ public CommandProcessorWithBothRetryAndCircuitBreaker() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions() @@ -67,7 +67,7 @@ public CommandProcessorWithBothRetryAndCircuitBreaker() MyMultiplePoliciesFailsWithDivideByZeroHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit_Async.cs index deed518a67..654e681c54 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Retries_Then_Repeatedly_Fails_Breaks_The_Circuit_Async.cs @@ -26,7 +26,7 @@ public CommandProcessorWithBothRetryAndCircuitBreakerAsync() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions() @@ -67,7 +67,7 @@ public CommandProcessorWithBothRetryAndCircuitBreakerAsync() MyMultiplePoliciesFailsWithDivideByZeroHandlerAsync.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure.cs index 3bf49075be..a840a41c46 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure.cs @@ -22,7 +22,7 @@ public CommandProcessorWithRetryPolicyTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -48,7 +48,7 @@ public CommandProcessorWithRetryPolicyTests() MyFailsWithDivideByZeroHandler.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure_Async.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure_Async.cs index 17ea873045..ddf510188d 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Should_Retry_Failure_Async.cs @@ -24,7 +24,7 @@ public CommandProcessorWithRetryPolicyAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton>(); @@ -50,7 +50,7 @@ public CommandProcessorWithRetryPolicyAsyncTests() _provider.GetService().ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_ResiliencePipeline_Check.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_ResiliencePipeline_Check.cs index e9720d2b6c..61ff13a1e5 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_ResiliencePipeline_Check.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_ResiliencePipeline_Check.cs @@ -24,7 +24,7 @@ public CommandProcessorWithExceptionResiliencePipelineNothingThrowAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -46,7 +46,7 @@ public CommandProcessorWithExceptionResiliencePipelineNothingThrowAsyncTests() MyDoesNotFailResiliencePipelineHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_TypeResiliencePipeline_Check.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_TypeResiliencePipeline_Check.cs index 88c120ab80..099739b9bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_TypeResiliencePipeline_Check.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Passes_TypeResiliencePipeline_Check.cs @@ -24,7 +24,7 @@ public CommandProcessorWithExceptionTypeResiliencePipelineNothingThrowAsyncTests var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -46,7 +46,7 @@ public CommandProcessorWithExceptionTypeResiliencePipelineNothingThrowAsyncTests MyDoesNotFailTypeResiliencePipelineHandlerAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs index 1d0198941c..6209a7fbd2 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_An_Async_Command_That_Repeatedely_Fails_Break_The_Circuit_With_ResiliencePipeline.cs @@ -26,7 +26,7 @@ public CommandProcessorWithCircuitBreakerAndResiliencePipelineAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton>(); container.AddSingleton(new BrighterOptions {HandlerLifetime = ServiceLifetime.Transient}); @@ -45,7 +45,7 @@ public CommandProcessorWithCircuitBreakerAndResiliencePipelineAsyncTests() MyFailsWithDivideByZeroWithResiliencePipelineHandlerAsync.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), resiliencePipeline, new InMemorySchedulerFactory()); + new PolicyRegistry(), resiliencePipeline, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_Different_Async_Commands_That_Share_A_ResiliencePipeline.cs b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_Different_Async_Commands_That_Share_A_ResiliencePipeline.cs index 0700ec3481..9d3fc17df4 100644 --- a/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_Different_Async_Commands_That_Share_A_ResiliencePipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_Different_Async_Commands_That_Share_A_ResiliencePipeline.cs @@ -25,7 +25,7 @@ public CommandProcessorWithSharedResiliencePipelineAsyncTests() registry.RegisterAsync(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddTransient>(); @@ -46,7 +46,7 @@ public CommandProcessorWithSharedResiliencePipelineAsyncTests() MyCommandHandlerWithSharedPipelineAsync.ReceivedCommand = false; MyOtherCommandHandlerWithSharedPipelineAsync.ReceivedCommand = false; - _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory()); + _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_Off.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_Off.cs index 83ea55d509..5e84ab494e 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_Off.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_Off.cs @@ -32,7 +32,7 @@ public CommandProcessorWithFeatureSwitchOffByConfigInPipelineTests() .StatusOf().Is(FeatureSwitchStatus.Off) .Build(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -50,7 +50,8 @@ public CommandProcessorWithFeatureSwitchOffByConfigInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_On.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_On.cs index 9b2a16f76f..3cfeb7a025 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_On.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Config_On.cs @@ -26,7 +26,7 @@ public CommandProcessorWithFeatureSwitchOnByConfigInPipelineTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -50,7 +50,8 @@ public CommandProcessorWithFeatureSwitchOnByConfigInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_Exception.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_Exception.cs index 38a9e90efd..fd1a07e505 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_Exception.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_Exception.cs @@ -27,7 +27,7 @@ public FeatureSwitchByConfigMissingConfigStrategyExceptionTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -49,7 +49,8 @@ public FeatureSwitchByConfigMissingConfigStrategyExceptionTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOff.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOff.cs index 0ca7c41946..dd06065a7b 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOff.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOff.cs @@ -25,7 +25,7 @@ public FeatureSwitchByConfigMissingConfigStrategySilentOffTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -48,7 +48,8 @@ public FeatureSwitchByConfigMissingConfigStrategySilentOffTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOn.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOn.cs index 2e8b13820a..3e00b206a0 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOn.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Missing_Config_SilentOn.cs @@ -25,7 +25,7 @@ public FeatureSwitchByConfigMissingConfigStrategySilentOnTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -48,7 +48,8 @@ public FeatureSwitchByConfigMissingConfigStrategySilentOnTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off.cs index f08e9025f0..322dc2ee84 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off.cs @@ -23,7 +23,7 @@ public CommandProcessorWithFeatureSwitchOffInPipelineTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -39,7 +39,8 @@ public CommandProcessorWithFeatureSwitchOffInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck.cs index ec08cf2d8d..aa7d9c2252 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck.cs @@ -46,7 +46,7 @@ public CommandProcessorWithFeatureSwitchOffDontAckInPipelineTests() SubscriberRegistry registry = new(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddTransient>(); container.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); @@ -62,7 +62,8 @@ public CommandProcessorWithFeatureSwitchOffDontAckInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck_Async.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck_Async.cs index aa4a5b6701..4b870f5789 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_Off_With_DontAck_Async.cs @@ -46,7 +46,7 @@ public CommandProcessorWithFeatureSwitchOffDontAckAsyncInPipelineTests() SubscriberRegistry registry = new(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddTransient>(); container.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); @@ -62,7 +62,8 @@ public CommandProcessorWithFeatureSwitchOffDontAckAsyncInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_On.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_On.cs index 89dc62970f..3b68c7f54b 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_On.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_A_Handler_Is_Feature_Switch_On.cs @@ -23,7 +23,7 @@ public CommandProcessorWithFeatureSwitchOnInPipelineTests() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -39,7 +39,8 @@ public CommandProcessorWithFeatureSwitchOnInPipelineTests() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(TimeProvider.System), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_No_Feature_Switch_Config.cs b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_No_Feature_Switch_Config.cs index b58abf714a..825957ce75 100644 --- a/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_No_Feature_Switch_Config.cs +++ b/tests/Paramore.Brighter.Core.Tests/FeatureSwitch/When_No_Feature_Switch_Config.cs @@ -24,7 +24,7 @@ public CommandProcessorWithNullFeatureSwitchConfig() registry.Register(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddSingleton(); container.AddSingleton(); container.AddTransient>(); @@ -41,7 +41,8 @@ public CommandProcessorWithNullFeatureSwitchConfig() .NoExternalBus() .ConfigureInstrumentation(new BrighterTracer(), InstrumentationOptions.All) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory)) + .ConfigureLogging(Initializer.TestLoggerFactory) .Build(); } diff --git a/tests/Paramore.Brighter.Core.Tests/Initializer.cs b/tests/Paramore.Brighter.Core.Tests/Initializer.cs index ec51a7dc81..d03b1c171b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Initializer.cs +++ b/tests/Paramore.Brighter.Core.Tests/Initializer.cs @@ -1,17 +1,25 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Serilog; namespace Paramore.Brighter.Core.Tests { - sealed class Initializer + static class Initializer { + /// + /// A Serilog-backed wired to Serilog's TestCorrelator sink. Brighter logging + /// is now instance-scoped, so tests that assert on log output must pass this factory into the Brighter + /// objects they construct (e.g. as the loggerFactory constructor argument), rather than relying on a + /// process-wide static. + /// + public static ILoggerFactory TestLoggerFactory { get; private set; } = NullLoggerFactory.Instance; + [ModuleInitializer] public static void InitializeTestLogger() { var logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger(); - ApplicationLogging.LoggerFactory = new LoggerFactory().AddSerilog(logger); + TestLoggerFactory = new LoggerFactory().AddSerilog(logger); } } } diff --git a/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline.cs index 4230a6fbc7..a04b2901e5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline.cs @@ -33,9 +33,9 @@ public void When_A_Request_Logger_Is_In_The_Pipeline() var registry = new SubscriberRegistry(); registry.Register>(); - var requestLogger = new RequestLoggingHandler(); + var requestLogger = new RequestLoggingHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(typeof(RequestLoggingHandler), provider => requestLogger); @@ -43,7 +43,7 @@ public void When_A_Request_Logger_Is_In_The_Pipeline() var commandProcessor = new CommandProcessor(registry, handlerFactory: handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); commandProcessor.Send(myCommand); diff --git a/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline_Async.cs b/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline_Async.cs index c0847c061a..14f6addcbc 100644 --- a/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Logging/When_A_Request_Logger_Is_In_The_Pipeline_Async.cs @@ -35,7 +35,7 @@ public async Task When_A_Request_Logger_Is_In_The_Pipeline_Async() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(typeof(RequestLoggingHandlerAsync<>), typeof(RequestLoggingHandlerAsync<>)); @@ -43,7 +43,7 @@ public async Task When_A_Request_Logger_Is_In_The_Pipeline_Async() var commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); await commandProcessor.SendAsync(myCommand); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs index 9cd554bada..a2c2508dae 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs @@ -24,8 +24,8 @@ public MessagePumpRetryCommandOnConnectionFailureTestsAsync() { _commandProcessor = new SpyCommandProcessor(); var channel = new FailingChannelAsync( - new ChannelName(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new ChannelName(ChannelName), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2) { NumberOfRetries = 1 @@ -34,8 +34,8 @@ public MessagePumpRetryCommandOnConnectionFailureTestsAsync() null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; @@ -44,20 +44,20 @@ public MessagePumpRetryCommandOnConnectionFailureTestsAsync() //two command, will be received when subscription restored var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(command, JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(command, JsonSerialisationOptions.Options)) ); channel.Enqueue(message1); channel.Enqueue(message2); - + //end the pump var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs index 5908fc22e7..156b53e760 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs @@ -23,20 +23,20 @@ public MessagePumpRetryEventConnectionFailureTestsAsync() { _commandProcessor = new SpyCommandProcessor(); var channel = new FailingChannelAsync( - new ChannelName("myChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new ChannelName("myChannel"), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2) { NumberOfRetries = 1 }; - + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; @@ -45,20 +45,20 @@ public MessagePumpRetryEventConnectionFailureTestsAsync() //Two events will be received when channel fixed var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); channel.Enqueue(message1); channel.Enqueue(message2); - + //Quit the message pump var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs index fce27512a1..fedec585b6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs @@ -49,19 +49,19 @@ public MessagePumpCommandProcessingDeferMessageActionTestsAsync() { SpyRequeueCommandProcessor commandProcessor = new(); - _channel = new ChannelAsync(new(ChannelName),_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new ChannelAsync(new(ChannelName),_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyCommand), messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyCommand), messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyCommand(), new RequestContext(), new Publication{Topic = _routingKey}) .Result; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_with_delay_Then_message_is_requeued_with_delay.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_with_delay_Then_message_is_requeued_with_delay.cs index fb493fc9d5..d3f244d9f4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_with_delay_Then_message_is_requeued_with_delay.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_with_delay_Then_message_is_requeued_with_delay.cs @@ -48,7 +48,7 @@ public async Task When_a_command_handler_throws_a_defer_message_with_delay_Then_ //Arrange var bus = new InternalBus(); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(_routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(_routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); var spyChannel = new SpyChannelAsync(new ChannelName(ChannelName), _routingKey, consumer); var commandProcessor = new SpyRequeueWithDelayCommandProcessor(delayMilliseconds: 5000); @@ -64,7 +64,7 @@ public async Task When_a_command_handler_throws_a_defer_message_with_delay_Then_ messageMapperRegistry, null, new InMemoryRequestContextFactory(), - spyChannel) + spyChannel, loggerFactory: Initializer.TestLoggerFactory) { Channel = spyChannel, TimeOut = TimeSpan.FromMilliseconds(5000), @@ -72,7 +72,7 @@ public async Task When_a_command_handler_throws_a_defer_message_with_delay_Then_ RequeueDelay = TimeSpan.FromMilliseconds(100) // Subscription default — should NOT be used when DeferMessageAction has a delay }; - var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyCommand(), new RequestContext(), new Publication { Topic = _routingKey }) .Result; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs index fd42cf3c2b..46566ef314 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs @@ -27,21 +27,22 @@ public MessagePumpCommandProcessingExceptionTestsAsync() InternalBus bus = new(); - _channel = new ChannelAsync(new("myChannel"),_routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new ChannelAsync(new("myChannel"),_routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, + loggerFactory: Initializer.TestLoggerFactory ) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyCommand(), new RequestContext(), new Publication{Topic = _routingKey}) .Result; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges_async.cs index b2721facdd..8cbefd84eb 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges_async.cs @@ -40,7 +40,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesAsyncTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -56,7 +56,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesAsyncTests() null, new InMemoryRequestContextFactory(), _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, @@ -65,7 +65,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesAsyncTests() }; // Build a properly-mapped command message so that mapping succeeds and the exception comes from dispatch - var mappableMessage = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var mappableMessage = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyCommand(), new RequestContext(), new Publication { Topic = _routingKey }) .Result; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_nack_the_message_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_nack_the_message_async.cs index e3a987b36a..180aa55a85 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_nack_the_message_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_nack_the_message_async.cs @@ -27,7 +27,7 @@ public MessagePumpCommandDontAckActionNackTestsAsync() _channel = new ChannelAsync( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -41,7 +41,7 @@ public MessagePumpCommandDontAckActionNackTestsAsync() messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge_async.cs index 99acaffc0f..7166138e09 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge_async.cs @@ -27,7 +27,7 @@ public MessagePumpCommandDontAckActionTestsAsync() _channel = new ChannelAsync( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -41,7 +41,7 @@ public MessagePumpCommandDontAckActionTestsAsync() messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched_async.cs index 646482f48b..2ac6ee39cf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched_async.cs @@ -47,12 +47,12 @@ public AsyncMessagePumpMapperReleaseThrowsTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new ChannelAsync(new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); //a mapper factory whose release throws, standing in for a user DisposeAsync/Release that faults or //MS DI's sync scope Dispose of an IAsyncDisposable-only mapper @@ -62,7 +62,7 @@ public AsyncMessagePumpMapperReleaseThrowsTests() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, _ => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_Is_asked_to_connect_a_channel_and_handler_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_Is_asked_to_connect_a_channel_and_handler_async.cs index bbca8eec56..bcdd2a8e44 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_Is_asked_to_connect_a_channel_and_handler_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_Is_asked_to_connect_a_channel_and_handler_async.cs @@ -10,7 +10,7 @@ namespace Paramore.Brighter.Core.Tests.MessageDispatch.Proactor { - + public class MessageDispatcherRoutingAsyncTests : IDisposable { private const string ChannelName = "myChannel"; @@ -33,48 +33,48 @@ public MessageDispatcherRoutingAsyncTests() var subscription = new Subscription( new SubscriptionName("test"), - noOfPerformers: 1, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: new ChannelName(ChannelName), + noOfPerformers: 1, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName(ChannelName), routingKey: _routingKey, messagePumpType: MessagePumpType.Proactor ); _dispatcher = new Dispatcher( - _commandProcessor, - new List { subscription }, - null, - messageMapperRegistry, - requestContextFactory: new InMemoryRequestContextFactory() + _commandProcessor, + new List { subscription }, + loggerFactory: Initializer.TestLoggerFactory, + messageMapperRegistryAsync: messageMapperRegistry, + requestContextFactory: new InMemoryRequestContextFactory() ); var @event = new MyEvent {Data = 4}; var message = new MyEventMessageMapperAsync().MapToMessageAsync(@event, new() { Topic = _routingKey }).Result; - + _bus.Enqueue(message); Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); - + } #pragma warning disable xUnit1031 - + [Fact] public async Task When_a_message_dispatcher_is_asked_to_connect_a_channel_and_handler_async() { await Task.Delay(5000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages - + await _dispatcher.End(); - + Assert.Equal(DispatcherState.DS_STOPPED, _dispatcher.State); Assert.NotNull(_commandProcessor.Observe()); Assert.Contains(CommandType.PublishAsync, _commandProcessor.Commands); Assert.Empty(_bus.Stream(_routingKey)); } - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_has_a_new_connection_added_while_running_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_has_a_new_connection_added_while_running_async.cs index cc50026ec2..04f93e4fa4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_has_a_new_connection_added_while_running_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_has_a_new_connection_added_while_running_async.cs @@ -21,7 +21,7 @@ public class DispatcherAddNewConnectionTestsAsync : IDisposable public DispatcherAddNewConnectionTestsAsync() { _bus = new InternalBus(); - + IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); var messageMapperRegistry = new MessageMapperRegistry( @@ -30,16 +30,16 @@ public DispatcherAddNewConnectionTestsAsync() messageMapperRegistry.RegisterAsync(); Subscription subscription = new Subscription( - new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), channelName: new ChannelName("fakeChannel"), + new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey ); - + _newSubscription = new Subscription( - new SubscriptionName("newTest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), + new SubscriptionName("newTest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeChannelTwo"), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKeyTwo); - _dispatcher = new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistryAsync: messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var message = new MyEventMessageMapperAsync() @@ -50,7 +50,7 @@ public DispatcherAddNewConnectionTestsAsync() Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection.cs index d8d7e958e2..328b2af13e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection.cs @@ -29,34 +29,34 @@ public MessageDispatcherResetConnectionAsync() messageMapperRegistry.RegisterAsync(); _subscription = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 1, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: new ChannelName("myChannel"), + new SubscriptionName("test"), + noOfPerformers: 1, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey ); - + _publication = new Publication{Topic = _subscription.RoutingKey, RequestType = typeof(MyEvent)}; - - _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistryAsync:messageMapperRegistry); + + _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistryAsync:messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var message = new MyEventMessageMapperAsync() .MapToMessageAsync(@event, _publication) .GetAwaiter() .GetResult(); - + _bus.Enqueue(message); Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); Task.Delay(1000).Wait(); _dispatcher.Shut(_subscription); - + } - + #pragma warning disable xUnit1031 [Fact] public async Task When_A_Message_Dispatcher_Restarts_A_Connection() @@ -68,7 +68,7 @@ public async Task When_A_Message_Dispatcher_Restarts_A_Connection() _bus.Enqueue(message); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages await _dispatcher.End(); @@ -77,7 +77,7 @@ public async Task When_A_Message_Dispatcher_Restarts_A_Connection() Assert.Equal(DispatcherState.DS_STOPPED, _dispatcher.State); } #pragma warning restore xUnit1031 - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped_async.cs index f4d05a3ee4..a946e567db 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped_async.cs @@ -34,27 +34,27 @@ public DispatcherRestartConnectionTestsAsync() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: _channelName, messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey ); - + Subscription newSubscription = new Subscription( - new SubscriptionName("newTest"), - noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: _channelName, + new SubscriptionName("newTest"), + noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: _channelName, messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey ); - + _publication = new Publication{Topic = subscription.RoutingKey}; - + _dispatcher = new Dispatcher( - commandProcessor, - new List { subscription, newSubscription }, - messageMapperRegistryAsync: messageMapperRegistry) + commandProcessor, + new List { subscription, newSubscription }, + messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory) ; var @event = new MyEvent(); @@ -62,7 +62,7 @@ public DispatcherRestartConnectionTestsAsync() .MapToMessageAsync(@event, _publication ) .GetAwaiter() .GetResult(); - + _bus.Enqueue(message); @@ -73,7 +73,7 @@ public DispatcherRestartConnectionTestsAsync() _dispatcher.Shut(newSubscription.Name); Task.Delay(1000).Wait(); Assert.Empty(_dispatcher.Consumers); - + } [Fact] @@ -83,10 +83,10 @@ public async Task When_A_Message_Dispatcher_Restarts_A_Connection_After_All_Conn var @event = new MyEvent(); var message = await new MyEventMessageMapperAsync().MapToMessageAsync(@event, _publication); _bus.Enqueue(message); - + await Task.Delay(1000); _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages - + Assert.Empty(_bus.Stream(_routingKey)); Assert.Equal(DispatcherState.DS_RUNNING, _dispatcher.State); Assert.Single(_dispatcher.Consumers); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_shuts_a_connection_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_shuts_a_connection_async.cs index 55c3ffae9e..199419a503 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_shuts_a_connection_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_shuts_a_connection_async.cs @@ -22,7 +22,7 @@ public class MessageDispatcherShutConnectionTests : IDisposable public MessageDispatcherShutConnectionTests() { InternalBus bus = new(); - + IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); var messageMapperRegistry = new MessageMapperRegistry( @@ -31,24 +31,24 @@ public MessageDispatcherShutConnectionTests() messageMapperRegistry.RegisterAsync(); _subscription = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 3, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(bus, _timeProvider), - channelName: new ChannelName(ChannelName), + new SubscriptionName("test"), + noOfPerformers: 3, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistryAsync: messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var message = new MyEventMessageMapperAsync().MapToMessageAsync(@event, new Publication{ Topic = _subscription.RoutingKey}) .GetAwaiter() .GetResult(); - + for (var i = 0; i < 6; i++) bus.Enqueue(message); - + Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); } @@ -64,7 +64,7 @@ public async Task When_A_Message_Dispatcher_Shuts_A_Connection() Assert.Equal(DispatcherState.DS_STOPPED, _dispatcher.State); Assert.Empty(_dispatcher.Consumers); } - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_different_types_of_performers.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_different_types_of_performers.cs index dc7fa0d90e..33d2bcebe5 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_different_types_of_performers.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_different_types_of_performers.cs @@ -26,7 +26,7 @@ public MessageDispatcherMultipleConnectionTestsAsync() { var commandProcessor = new SpyCommandProcessor(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); @@ -38,39 +38,39 @@ public MessageDispatcherMultipleConnectionTestsAsync() messageMapperRegistry.RegisterAsync(); var myEventConnection = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 1, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + new SubscriptionName("test"), + noOfPerformers: 1, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), messagePumpType: MessagePumpType.Proactor, - channelName: new ChannelName("fakeEventChannel"), + channelName: new ChannelName("fakeEventChannel"), routingKey: _eventRoutingKey ); var myCommandConnection = new Subscription( - new SubscriptionName("anothertest"), - noOfPerformers: 1, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: new ChannelName("fakeCommandChannel"), - messagePumpType: MessagePumpType.Proactor, + new SubscriptionName("anothertest"), + noOfPerformers: 1, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName("fakeCommandChannel"), + messagePumpType: MessagePumpType.Proactor, routingKey: _commandRoutingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { myEventConnection, myCommandConnection }, messageMapperRegistryAsync: messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { myEventConnection, myCommandConnection }, messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var eventMessage = new MyEventMessageMapperAsync().MapToMessageAsync(@event, new Publication{Topic = _eventRoutingKey}) .GetAwaiter() .GetResult(); - + _bus.Enqueue(eventMessage); var command = new MyCommand(); var commandMessage = new MyCommandMessageMapperAsync().MapToMessageAsync(command, new Publication{Topic = _commandRoutingKey}) .GetAwaiter() .GetResult(); - + _bus.Enqueue(commandMessage); - + Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); } @@ -80,11 +80,11 @@ public MessageDispatcherMultipleConnectionTestsAsync() public async Task When_A_Message_Dispatcher_Starts_Different_Types_Of_Performers() { await Task.Delay(1000); - + _numberOfConsumers = _dispatcher.Consumers.Count(); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages - + await _dispatcher.End(); Assert.Empty(_bus.Stream(_eventRoutingKey)); @@ -93,7 +93,7 @@ public async Task When_A_Message_Dispatcher_Starts_Different_Types_Of_Performers Assert.Empty(_dispatcher.Consumers); Assert.Equal(2, _numberOfConsumers); } - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_multiple_performers_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_multiple_performers_async.cs index e11a0e0cff..e1c6caaee6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_multiple_performers_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_dispatcher_starts_multiple_performers_async.cs @@ -22,8 +22,8 @@ public MessageDispatcherMultiplePerformerTestsAsync() { var routingKey = new RoutingKey(Topic); _bus = new InternalBus(); - var consumer = new InMemoryMessageConsumer(routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000)); - + var consumer = new InMemoryMessageConsumer(routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); + IAmAChannelSync channel = new Channel(new (ChannelName), new(Topic), consumer, 6); IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); @@ -33,24 +33,24 @@ public MessageDispatcherMultiplePerformerTestsAsync() messageMapperRegistry.RegisterAsync(); var connection = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 3, - timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), - channelName: new ChannelName("fakeChannel"), + new SubscriptionName("test"), + noOfPerformers: 3, + timeOut: TimeSpan.FromMilliseconds(100), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName("fakeChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: routingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { connection }, messageMapperRegistryAsync: messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { connection }, messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var message = new MyEventMessageMapperAsync().MapToMessageAsync(@event, new Publication{Topic = connection.RoutingKey}) .GetAwaiter() .GetResult(); - + for (var i = 0; i < 6; i++) channel.Enqueue(message); - + Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status_async.cs index ccf16b1672..9130fbaaf9 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status_async.cs @@ -40,7 +40,7 @@ public MessagePumpMappingRejectionDescriptionMatchesSpanStatusAsyncTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +55,7 @@ public MessagePumpMappingRejectionDescriptionMatchesSpanStatusAsyncTests() null, new InMemoryRequestContextFactory(), _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs index cb63e00718..b621490d61 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs @@ -48,7 +48,7 @@ public MessagePumpUnacceptableMessageLimitTestsAsync() new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)), + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2 ); var messageMapperRegistry = new MessageMapperRegistry( @@ -57,7 +57,7 @@ public MessagePumpUnacceptableMessageLimitTestsAsync() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyFailingMapperEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs index 960b63fbc0..d0ff7e8068 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs @@ -40,7 +40,7 @@ public MessagePumpFailingMessageTranslationTestsAsync() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +55,7 @@ public MessagePumpFailingMessageTranslationTestsAsync() null, new InMemoryRequestContextFactory(), _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs index e9a3779251..e2aa918d30 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs @@ -29,25 +29,25 @@ public MessagePumpDispatchAsyncTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); - var channel = new ChannelAsync(new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + var channel = new ChannelAsync(new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; var message = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(_myEvent))); channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] @@ -57,7 +57,7 @@ public void When_a_message_is_dispatched_it_should_reach_a_handler_async() Assert.True(MyEventHandlerAsyncWithContinuation.ShouldReceive(_myEvent)); Assert.Equal(2, MyEventHandlerAsyncWithContinuation.MonitorValue); - //NOTE: We may want to run the continuation on the captured context, so as not to create a new thread, which means this test would + //NOTE: We may want to run the continuation on the captured context, so as not to create a new thread, which means this test would //change once we fix the pump to exhibit that behavior\ Assert.NotEqual(MyEventHandlerAsyncWithContinuation.WorkThreadId, MyEventHandlerAsyncWithContinuation.ContinuationThreadId); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_mapper_throws_invalid_message_action_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_mapper_throws_invalid_message_action_async.cs index 054c5adeab..70460d6a51 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_mapper_throws_invalid_message_action_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_mapper_throws_invalid_message_action_async.cs @@ -45,14 +45,14 @@ public MessageDispatchInvalidMessageActionAsyncTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var subscription = new InMemorySubscription( new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey @@ -64,8 +64,8 @@ public MessageDispatchInvalidMessageActionAsyncTests() commandProcessor, new List { subscription }, messageMapperRegistryAsync: messageMapperRegistry, - requestContextFactory: new InMemoryRequestContextFactory() - ); + requestContextFactory: new InMemoryRequestContextFactory(), + loggerFactory: Initializer.TestLoggerFactory); // Act: Send a message that will fail deserialization var @event = new MyRejectedEvent(Id.Random()); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs index 357fe70418..0f05ec1651 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs @@ -24,26 +24,26 @@ public class MessagePumpCommandRequeueCountThresholdTestsAsync public MessagePumpCommandRequeueCountThresholdTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - _channel = new ChannelAsync(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); - + _channel = new ChannelAsync(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyCommand), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; - var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize((MyCommand)new(), JsonSerialisationOptions.Options)) ); - var message2 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + var message2 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize((MyCommand)new(), JsonSerialisationOptions.Options)) ); _bus.Enqueue(message1); _bus.Enqueue(message2); - + } [Fact] @@ -51,7 +51,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Commands_Has_Been_Reached() { var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages var quitMessage = MessageFactory.CreateQuitMessage(new RoutingKey("MyTopic")); @@ -63,7 +63,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Commands_Has_Been_Reached() Assert.Equal(6, _commandProcessor.SendCount); Assert.Empty(_bus.Stream(_routingKey)); - + //TODO: How can we observe that the channel has been closed? Observability? } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs index 3015f431c5..c6a1dd54f3 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs @@ -24,28 +24,28 @@ public class MessagePumpEventRequeueCountThresholdTestsAsync public MessagePumpEventRequeueCountThresholdTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - _channel = new ChannelAsync(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); - + _channel = new ChannelAsync(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); _bus.Enqueue(message1); _bus.Enqueue(message2); - + } [Fact] @@ -53,7 +53,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Events_Has_Been_Reached() { var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); @@ -65,7 +65,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Events_Has_Been_Reached() Assert.Equal(6, _commandProcessor.PublishCount); Assert.Empty(_bus.Stream(_routingKey)); - + //TODO: How do we assert that the channel was closed? Observability? } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs index 2ef20b3731..7f36ce6326 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs @@ -24,35 +24,35 @@ public class MessagePumpCommandRequeueTestsAsync public MessagePumpCommandRequeueTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - ChannelAsync channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), 2); - + ChannelAsync channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2); + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) ); - + var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) ); - + channel.Enqueue(message1); channel.Enqueue(message2); var quitMessage = new Message( - new MessageHeader(string.Empty, RoutingKey.Empty, MessageType.MT_QUIT), + new MessageHeader(string.Empty, RoutingKey.Empty, MessageType.MT_QUIT), new MessageBody("") ); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs index 738398df2a..45413c1fc8 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs @@ -24,41 +24,41 @@ public MessagePumpEventRequeueTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); ChannelAsync channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2 ); - + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); - + channel.Enqueue(message1); channel.Enqueue(message2); var quitMessage = MessageFactory.CreateQuitMessage(new RoutingKey("MyTopic")); channel.Enqueue(quitMessage); - + } [Fact] public void When_A_Requeue_Of_Event_Exception_Is_Thrown() { _messagePump.Run(); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages //_should_publish_the_message_via_the_command_processor @@ -67,7 +67,7 @@ public void When_A_Requeue_Of_Event_Exception_Is_Thrown() //_should_requeue_the_messages Assert.Equal(2, _bus.Stream(_routingKey).Count()); - + //TODO: How do we know that the channel has been disposed? Observability } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge_async.cs index b65ee3cff0..5ed72401b4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge_async.cs @@ -26,7 +26,7 @@ public MessagePumpEventDontAckAggregateExceptionTestsAsync() var channel = new ChannelAsync( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -40,7 +40,7 @@ public MessagePumpEventDontAckAggregateExceptionTestsAsync() messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), - channel) + channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throw_a_reject_message_exception_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throw_a_reject_message_exception_async.cs index a697077f10..d5700a44c1 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throw_a_reject_message_exception_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throw_a_reject_message_exception_async.cs @@ -43,14 +43,14 @@ public MessageDispatchRejectMessageExceptionTestsAsync() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var subscription = new InMemorySubscription( new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: _routingKey @@ -61,8 +61,8 @@ public MessageDispatchRejectMessageExceptionTestsAsync() _dispatcher = new Dispatcher( commandProcessor, new List { subscription }, - null, - messageMapperRegistryAsync, + loggerFactory: Initializer.TestLoggerFactory, + messageMapperRegistryAsync: messageMapperRegistryAsync, requestContextFactory: new InMemoryRequestContextFactory() ); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs index db6d3397f1..6832f081de 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs @@ -50,23 +50,23 @@ public MessagePumpEventProcessingDeferMessageActionTestsAsync() SpyRequeueCommandProcessor commandProcessor = new(); _bus = new InternalBus(); - _channel = new ChannelAsync(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); - + _channel = new ChannelAsync(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); + var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyEvent(), new RequestContext(), new Publication{Topic = _routingKey}) .Result; _channel.Enqueue(msg); - + } @@ -75,9 +75,9 @@ public async Task When_an_event_handler_throws_a_defer_message_the_message_is_re { var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages - + var quitMessage = MessageFactory.CreateQuitMessage(new RoutingKey(Topic)); _channel.Enqueue(quitMessage); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs index a5a59d9a9b..9a60f8af1b 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs @@ -29,20 +29,20 @@ public MessagePumpEventProcessingExceptionTestsAsync() var bus = new InternalBus(); - _channel = new ChannelAsync(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new ChannelAsync(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, InstrumentationOptions.All) + var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All) .BuildWrapPipeline() .WrapAsync(new MyEvent(), new RequestContext(), new Publication{Topic = _routingKey}) .Result; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs index 0822a4c486..89b376b094 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs @@ -51,7 +51,7 @@ public AsyncMessagePumpUnacceptableMessageTests() _channel = new ChannelAsync( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -60,7 +60,7 @@ public AsyncMessagePumpUnacceptableMessageTests() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_a_dlq.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_a_dlq.cs index b66e43c336..11c99ad260 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_a_dlq.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_a_dlq.cs @@ -52,7 +52,7 @@ public AsyncMessagePumpUnacceptableMessageDeadLetterChannelTests() _channel = new ChannelAsync( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -61,7 +61,7 @@ public AsyncMessagePumpUnacceptableMessageDeadLetterChannelTests() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_an_imc.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_an_imc.cs index 3d81a5c4f0..010c0d825a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_an_imc.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async_and_there_is_an_imc.cs @@ -52,7 +52,7 @@ public AsyncMessagePumpUnacceptableMessageInvalidMessageChannelTests() _channel = new ChannelAsync( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -61,7 +61,7 @@ public AsyncMessagePumpUnacceptableMessageInvalidMessageChannelTests() messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs index 10aed5578a..27f8f1554c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs @@ -44,7 +44,7 @@ public MessagePumpUnacceptableMessageLimitBreachedAsyncTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var channel = new ChannelAsync(new("MyChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), 3); + var channel = new ChannelAsync(new("MyChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 3); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -53,7 +53,7 @@ public MessagePumpUnacceptableMessageLimitBreachedAsyncTests() _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, - timeProvider:_timeProvider) + timeProvider:_timeProvider, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3, UnacceptableMessageLimitWindow = TimeSpan.FromMinutes(1) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reset_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reset_async.cs index c4263f7d2b..59c171bf8e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reset_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reset_async.cs @@ -27,14 +27,14 @@ public class MessagePumpUnacceptableMessageLimitResetTestsAsync public MessagePumpUnacceptableMessageLimitResetTestsAsync() { _bus = new InternalBus(); - + _channel = new ChannelAsync( new(Channel), - _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 10 ); - + var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.RegisterAsync(); @@ -44,8 +44,8 @@ public MessagePumpUnacceptableMessageLimitResetTestsAsync() ); var resiliencePipelineRegistry = new ResiliencePipelineRegistry(); - resiliencePipelineRegistry.AddBrighterDefault(); - + resiliencePipelineRegistry.AddBrighterDefault(); + var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => throw new NotImplementedException() ), new SimpleMessageMapperFactoryAsync(_ => new MyAdvanceTimerEventMessageMapperAsync())); @@ -57,39 +57,39 @@ public MessagePumpUnacceptableMessageLimitResetTestsAsync() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); - - _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyAdvanceTimerEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, - timeProvider:_timeProvider) + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); + + _messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyAdvanceTimerEvent), + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, + timeProvider:_timeProvider, loggerFactory: Initializer.TestLoggerFactory) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), - RequeueCount = 3, - UnacceptableMessageLimit = 3, + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3, + UnacceptableMessageLimit = 3, UnacceptableMessageLimitWindow = TimeSpan.FromMinutes(1) }; _unacceptableMessage1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage3 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage4 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _timeAdvanceMessage = new MyAdvanceTimerEventMessageMapper().MapToMessage( - new MyAdvanceTimerEvent(2), + new MyAdvanceTimerEvent(2), new Publication { Topic = _routingKey @@ -102,20 +102,20 @@ public async Task When_An_Unacceptable_Message_Limit_Is_Reached() { _channel.Enqueue(_unacceptableMessage1); _channel.Enqueue(_unacceptableMessage2); - + //force the time forward, whilst in the message loop _channel.Enqueue(_timeAdvanceMessage); - + //will trigger reset of unacceptable message count as window has passed _channel.Enqueue(_unacceptableMessage3); _channel.Enqueue(_unacceptableMessage4); var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); - + _channel.Stop(_routingKey); - + await Task.WhenAll(task); - + Assert.Empty(_bus.Stream(_routingKey)); Assert.Equal(MessagePumpStatus.MP_STOPPED, _messagePump.Status); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_consuming_a_message_the_proactor_releases_every_mapper_it_creates.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_consuming_a_message_the_proactor_releases_every_mapper_it_creates.cs index ad63d7e42d..457922c99d 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_consuming_a_message_the_proactor_releases_every_mapper_it_creates.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_consuming_a_message_the_proactor_releases_every_mapper_it_creates.cs @@ -38,18 +38,18 @@ public ProactorConsumeMapperReleaseTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new ChannelAsync(new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry(null, _mapperFactory); messageMapperRegistry.RegisterAsync(); _messagePump = new ServiceActivator.Proactor(commandProcessor, _ => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_dispatcher_started_on_limited_concurrency_scheduler_should_not_deadlock.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_dispatcher_started_on_limited_concurrency_scheduler_should_not_deadlock.cs index 7fe492c4b7..402691b12d 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_dispatcher_started_on_limited_concurrency_scheduler_should_not_deadlock.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_dispatcher_started_on_limited_concurrency_scheduler_should_not_deadlock.cs @@ -20,7 +20,7 @@ public void When_Dispatcher_Started_On_Limited_Concurrency_Scheduler_Should_Not_ { var routingKey = new RoutingKey(Topic); var bus = new InternalBus(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); IAmAChannelSync channel = new Channel(new(ChannelName), new(Topic), consumer, 6); IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); @@ -34,12 +34,12 @@ public void When_Dispatcher_Started_On_Limited_Concurrency_Scheduler_Should_Not_ new SubscriptionName("test"), noOfPerformers: 3, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(bus, TimeProvider.System), + channelFactory: new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeChannel"), messagePumpType: MessagePumpType.Proactor, routingKey: routingKey ); - var dispatcher = new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistryAsync: messageMapperRegistry); + var dispatcher = new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistryAsync: messageMapperRegistry, loggerFactory: Initializer.TestLoggerFactory); var @event = new MyEvent(); var message = new MyEventMessageMapperAsync() diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_no_imq_configured_reject_falls_back_to_dlq_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_no_imq_configured_reject_falls_back_to_dlq_async.cs index f9a9eb0ed2..b8c0ddc384 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_no_imq_configured_reject_falls_back_to_dlq_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_no_imq_configured_reject_falls_back_to_dlq_async.cs @@ -47,7 +47,7 @@ public MessagePumpMappingFailureNoImqFallsToDlqAsyncTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -61,7 +61,7 @@ public MessagePumpMappingFailureNoImqFallsToDlqAsyncTests() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_receives_quit_should_dispose_channel_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_receives_quit_should_dispose_channel_async.cs index e07cb43746..1b92568369 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_receives_quit_should_dispose_channel_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_receives_quit_should_dispose_channel_async.cs @@ -23,7 +23,7 @@ public ProactorQuitAsyncDisposalTests() { // Arrange var commandProcessor = new SpyCommandProcessor(); - var consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _trackingChannel = new TrackingChannelAsync( new ChannelName("test-channel"), _routingKey, @@ -41,8 +41,8 @@ public ProactorQuitAsyncDisposalTests() messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), - _trackingChannel - ); + _trackingChannel, + loggerFactory: Initializer.TestLoggerFactory); messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); // Enqueue a message followed by a quit diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_shutdown_inside_async_context_should_not_deadlock.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_shutdown_inside_async_context_should_not_deadlock.cs index f986d7e88f..3336beba49 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_shutdown_inside_async_context_should_not_deadlock.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_proactor_shutdown_inside_async_context_should_not_deadlock.cs @@ -30,7 +30,7 @@ public void When_Proactor_Shuts_Down_Inside_BrighterAsyncContext_Should_Not_Dead var timeProvider = new FakeTimeProvider(); var commandProcessor = new SpyCommandProcessor(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); // Use a channel whose DisposeAsync does real async work (Task.Yield) // to force continuations back onto the scheduler @@ -51,8 +51,8 @@ public void When_Proactor_Shuts_Down_Inside_BrighterAsyncContext_Should_Not_Dead messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), - channel - ); + channel, + loggerFactory: Initializer.TestLoggerFactory); messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); // Enqueue a message followed by a quit diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs index 8996501a9b..c7905d819e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs @@ -24,10 +24,10 @@ public MessagePumpToCommandProcessorDynamicMappingTestsAsync() { _commandProcessor = new SpyCommandProcessor(); _channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); - + var messagerMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(type => @@ -39,15 +39,15 @@ public MessagePumpToCommandProcessorDynamicMappingTestsAsync() })); messagerMapperRegistry.RegisterAsync(); messagerMapperRegistry.RegisterAsync(); - + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => message switch { var m when m.Header.Type == new CloudEventsType("io.brighter.paramore.myevent") => typeof(MyEvent), var m when m.Header.Type == new CloudEventsType("io.brighter.paramore.myotherevent") => typeof(MyOtherEvent), _ => throw new ArgumentException($"No type mapping found for message with type {message.Header.Type}", nameof(message)), - }, - messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + }, + messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; } @@ -55,20 +55,20 @@ public MessagePumpToCommandProcessorDynamicMappingTestsAsync() public void When_Reading_A_MyOtherEvent_Message_From_A_Channel_Pump_Out_To_Command_Processor() { //arrange - var @event = new MyEvent(); //although we send a MyEvent, we will map it dynamically to a MyOtherEvent + var @event = new MyEvent(); //although we send a MyEvent, we will map it dynamically to a MyOtherEvent var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myotherevent") ), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myotherevent") ), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); - + _channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); _channel.Enqueue(quitMessage); - + //act _messagePump.Run(); - + //assert Assert.Equal(CommandType.PublishAsync, _commandProcessor.Commands[0]); @@ -76,25 +76,25 @@ public void When_Reading_A_MyOtherEvent_Message_From_A_Channel_Pump_Out_To_Comma Assert.Equal(@event.Id, myOtherEvent.Id); Assert.Equal(@event.Data, myOtherEvent.Data); } - + [Fact] public void When_Reading_A_MyEvent_Message_From_A_Channel_Pump_Out_To_Command_Processor() { //arrange - var @event = new MyEvent(); //we send a MyEvent, we will map it dynamically to a MyEvent + var @event = new MyEvent(); //we send a MyEvent, we will map it dynamically to a MyEvent var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myevent") ), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myevent") ), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); - + _channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); _channel.Enqueue(quitMessage); - + //act _messagePump.Run(); - + //assert Assert.Equal(CommandType.PublishAsync, _commandProcessor.Commands[0]); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs index c0a604e8b8..ca9c2086ef 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs @@ -24,28 +24,28 @@ public MessagePumpToCommandProcessorTestsAsync() { _commandProcessor = new SpyCommandProcessor(); ChannelAsync channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messagerMapperRegistry = new MessageMapperRegistry( null, new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messagerMapperRegistry.RegisterAsync(); - + _messagePump = new ServiceActivator.Proactor(_commandProcessor, (message) => typeof(MyEvent), - messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; _event = new MyEvent(); var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(_event, JsonSerialisationOptions.Options)) ); channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs index 199a86010f..8727ba49e6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs @@ -24,7 +24,7 @@ public PerformerCanStopTestsAsync() SpyCommandProcessor commandProcessor = new(); ChannelAsync channel = new( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -33,7 +33,7 @@ public PerformerCanStopTestsAsync() messageMapperRegistry.RegisterAsync(); var messagePump = new ServiceActivator.Proactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, - new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel); + new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory); messagePump.Channel = channel; messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_mapping_reject_path_is_compared_across_pumps_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_mapping_reject_path_is_compared_across_pumps_async.cs index 2e69890c6c..31574b0457 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_mapping_reject_path_is_compared_across_pumps_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_mapping_reject_path_is_compared_across_pumps_async.cs @@ -48,7 +48,7 @@ public MessagePumpMappingRejectPathParityTestsAsync() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -62,7 +62,7 @@ public MessagePumpMappingRejectPathParityTestsAsync() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit_async.cs index 35f9345bba..3637f0a5d7 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit_async.cs @@ -24,7 +24,7 @@ public MessagePumpDefaultLimitZeroMappingFailuresNeverTripLimitAsyncTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -39,7 +39,7 @@ public MessagePumpDefaultLimitZeroMappingFailuresNeverTripLimitAsyncTests() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs index 76919e1971..36cbbe6203 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs @@ -24,8 +24,8 @@ public MessagePumpRetryCommandOnConnectionFailureTests() { _commandProcessor = new SpyCommandProcessor(); var channel = new FailingChannel( - new ChannelName(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new ChannelName(ChannelName), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2) { NumberOfRetries = 1 @@ -35,7 +35,7 @@ public MessagePumpRetryCommandOnConnectionFailureTests() null); messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; @@ -44,20 +44,20 @@ public MessagePumpRetryCommandOnConnectionFailureTests() //two command, will be received when subscription restored var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(command, JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(command, JsonSerialisationOptions.Options)) ); channel.Enqueue(message1); channel.Enqueue(message2); - + //end the pump var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs index a94dea1d0c..53d8d594cd 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs @@ -23,20 +23,20 @@ public MessagePumpRetryEventConnectionFailureTests() { _commandProcessor = new SpyCommandProcessor(); var channel = new FailingChannel( - new ChannelName("myChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new ChannelName("myChannel"), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2) { NumberOfRetries = 1 }; - + var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); - - _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; @@ -45,20 +45,20 @@ public MessagePumpRetryEventConnectionFailureTests() //Two events will be received when channel fixed var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); channel.Enqueue(message1); channel.Enqueue(message2); - + //Quit the message pump var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs index 604787ffb5..d8d2575daf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs @@ -46,7 +46,7 @@ public MessagePumpCommandProcessingDeferMessageActionTests() { SpyRequeueCommandProcessor commandProcessor = new(); - _channel = new Channel(new("myChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new("myChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), @@ -54,12 +54,12 @@ public MessagePumpCommandProcessingDeferMessageActionTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilder(messageMapperRegistry, null) + var msg = new TransformPipelineBuilder(messageMapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory) .BuildWrapPipeline() .Wrap(new MyCommand(), new RequestContext(), new Publication{Topic = _routingKey}); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs index 59d978136c..69aab091f4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs @@ -24,20 +24,20 @@ public MessagePumpCommandProcessingExceptionTests() SpyExceptionCommandProcessor commandProcessor = new(); InternalBus bus = new(); - _channel = new Channel(new("myChannel"),_routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new("myChannel"),_routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var msg = new TransformPipelineBuilder(messageMapperRegistry, null) + var msg = new TransformPipelineBuilder(messageMapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory) .BuildWrapPipeline() .Wrap(new MyCommand(), new RequestContext(), new Publication{Topic = _routingKey}); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges.cs index 8e6b155f55..9e461e0344 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_dispatch_exception_is_thrown_the_catch_all_acknowledges.cs @@ -40,7 +40,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -58,7 +58,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesTests() null, requestContextFactory, _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, @@ -67,7 +67,7 @@ public MessagePumpDispatchExceptionCatchAllAcknowledgesTests() }; // Build a properly-mapped command message so that mapping succeeds and the exception comes from dispatch - var mappableMessage = new TransformPipelineBuilder(messageMapperRegistry, null) + var mappableMessage = new TransformPipelineBuilder(messageMapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory) .BuildWrapPipeline() .Wrap(new MyCommand(), requestContextFactory.Create(), new Publication { Topic = _routingKey }); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_nack_the_message.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_nack_the_message.cs index a6174f4a58..6093633dbf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_nack_the_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_nack_the_message.cs @@ -28,7 +28,7 @@ public MessagePumpCommandDontAckActionNackTests() _channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -42,7 +42,7 @@ public MessagePumpCommandDontAckActionNackTests() messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge.cs index 872a3a932a..c24dfee9aa 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_handler_throws_dont_ack_action_should_not_acknowledge.cs @@ -26,7 +26,7 @@ public MessagePumpCommandDontAckActionTests() var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -40,7 +40,7 @@ public MessagePumpCommandDontAckActionTests() messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), - channel) + channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched.cs index 241c70d849..fff135c29f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_mapper_release_throws_the_mapped_message_is_still_dispatched.cs @@ -44,12 +44,12 @@ public MessagePumpMapperReleaseThrowsTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel(new("myChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); //a mapper factory whose Release throws, standing in for a user Dispose/Release that faults var messageMapperRegistry = new MessageMapperRegistry( @@ -58,7 +58,7 @@ public MessagePumpMapperReleaseThrowsTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, _ => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_has_a_new_connection_added_while_running.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_has_a_new_connection_added_while_running.cs index feed2a4c16..6919b22a45 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_has_a_new_connection_added_while_running.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_has_a_new_connection_added_while_running.cs @@ -21,7 +21,7 @@ public class DispatcherAddNewConnectionTests : IDisposable public DispatcherAddNewConnectionTests() { _bus = new InternalBus(); - + IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); var messageMapperRegistry = new MessageMapperRegistry( @@ -30,16 +30,16 @@ public DispatcherAddNewConnectionTests() messageMapperRegistry.Register(); Subscription subscription = new Subscription( - new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), channelName: new ChannelName("fakeChannel"), + new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey ); - + _newSubscription = new Subscription( - new SubscriptionName("newTest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), + new SubscriptionName("newTest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeChannelTwo"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKeyTwo); - _dispatcher = new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { subscription }, Initializer.TestLoggerFactory, messageMapperRegistry); var @event = new MyEvent(); var message = new MyEventMessageMapper().MapToMessage(@event, new Publication{Topic = _routingKey}); @@ -47,7 +47,7 @@ public DispatcherAddNewConnectionTests() Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_is_asked_to_connect_a_channel_and_handler.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_is_asked_to_connect_a_channel_and_handler.cs index b56fc3807c..9e8fa37aaa 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_is_asked_to_connect_a_channel_and_handler.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_is_asked_to_connect_a_channel_and_handler.cs @@ -31,7 +31,7 @@ public MessageDispatcherRoutingTests() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey @@ -40,7 +40,7 @@ public MessageDispatcherRoutingTests() _dispatcher = new Dispatcher( _commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, requestContextFactory: new InMemoryRequestContextFactory() ); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection.cs index 97d0817069..dafbb1930d 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection.cs @@ -29,18 +29,18 @@ public MessageDispatcherResetConnection() messageMapperRegistry.Register(); _subscription = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 1, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: new ChannelName("myChannel"), + new SubscriptionName("test"), + noOfPerformers: 1, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey ); - + _publication = new Publication{Topic = _subscription.RoutingKey, RequestType = typeof(MyEvent)}; - - _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistry); + + _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, Initializer.TestLoggerFactory, messageMapperRegistry); var @event = new MyEvent(); var message = new MyEventMessageMapper().MapToMessage(@event, _publication); @@ -50,9 +50,9 @@ public MessageDispatcherResetConnection() _dispatcher.Receive(); Task.Delay(1000).Wait(); _dispatcher.Shut(_subscription); - + } - + #pragma warning disable xUnit1031 [Fact] public void When_A_Message_Dispatcher_Restarts_A_Connection() @@ -64,7 +64,7 @@ public void When_A_Message_Dispatcher_Restarts_A_Connection() _bus.Enqueue(message); Task.Delay(1000).Wait(); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages _dispatcher.End().Wait(); @@ -73,7 +73,7 @@ public void When_A_Message_Dispatcher_Restarts_A_Connection() Assert.Equal(DispatcherState.DS_STOPPED, _dispatcher.State); } #pragma warning restore xUnit1031 - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped.cs index 7d5f6ac2a7..e99f9d37b4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_restarts_a_connection_after_all_connections_have_stopped.cs @@ -34,44 +34,44 @@ public DispatcherRestartConnectionTests() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: _channelName, messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey ); - + Subscription newSubscription = new Subscription( - new SubscriptionName("newTest"), - noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), - channelName: _channelName, + new SubscriptionName("newTest"), + noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(100), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: _channelName, messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey ); - + _publication = new Publication{Topic = subscription.RoutingKey}; - + _dispatcher = new Dispatcher( - commandProcessor, - new List { subscription, newSubscription }, - messageMapperRegistry) + commandProcessor, + new List { subscription, newSubscription }, + Initializer.TestLoggerFactory, messageMapperRegistry) ; var @event = new MyEvent(); var message = new MyEventMessageMapper().MapToMessage(@event, _publication ); - + _bus.Enqueue(message); Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); - + _dispatcher.Receive(); Task.Delay(250).Wait(); _dispatcher.Shut(subscription.Name); _dispatcher.Shut(newSubscription.Name); Task.Delay(1000).Wait(); - + Assert.Empty(_dispatcher.Consumers); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_shuts_a_connection.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_shuts_a_connection.cs index d69c9d1bbb..9287b46a92 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_shuts_a_connection.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_shuts_a_connection.cs @@ -22,7 +22,7 @@ public class MessageDispatcherShutConnectionTests : IDisposable public MessageDispatcherShutConnectionTests() { InternalBus bus = new(); - + IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); var messageMapperRegistry = new MessageMapperRegistry( @@ -31,15 +31,15 @@ public MessageDispatcherShutConnectionTests() messageMapperRegistry.Register(); _subscription = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 3, - timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(bus, _timeProvider), - channelName: new ChannelName(ChannelName), + new SubscriptionName("test"), + noOfPerformers: 3, + timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { _subscription }, Initializer.TestLoggerFactory, messageMapperRegistry); var @event = new MyEvent(); var message = new MyEventMessageMapper().MapToMessage(@event, new Publication{ Topic = _subscription.RoutingKey}); @@ -48,7 +48,7 @@ public MessageDispatcherShutConnectionTests() Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); - + } [Fact] @@ -62,7 +62,7 @@ public async Task When_A_Message_Dispatcher_Shuts_A_Connection() Assert.Equal(DispatcherState.DS_STOPPED, _dispatcher.State); Assert.Empty(_dispatcher.Consumers); } - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_different_types_of_performers.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_different_types_of_performers.cs index 9bbd7701f4..91644867a3 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_different_types_of_performers.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_different_types_of_performers.cs @@ -26,7 +26,7 @@ public MessageDispatcherMultipleConnectionTests() { var commandProcessor = new SpyCommandProcessor(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); @@ -37,16 +37,16 @@ public MessageDispatcherMultipleConnectionTests() messageMapperRegistry.Register(); var myEventConnection = new Subscription( - new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), channelFactory: - new InMemoryChannelFactory(_bus, _timeProvider), messagePumpType: MessagePumpType.Reactor, channelName: new ChannelName("fakeEventChannel"), + new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), channelFactory: + new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), messagePumpType: MessagePumpType.Reactor, channelName: new ChannelName("fakeEventChannel"), routingKey: _eventRoutingKey ); var myCommandConnection = new Subscription( - new SubscriptionName("anothertest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + new SubscriptionName("anothertest"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("fakeCommandChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _commandRoutingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { myEventConnection, myCommandConnection }, messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { myEventConnection, myCommandConnection }, Initializer.TestLoggerFactory, messageMapperRegistry); var @event = new MyEvent(); var eventMessage = new MyEventMessageMapper().MapToMessage(@event, new Publication{Topic = _eventRoutingKey}); @@ -55,7 +55,7 @@ public MessageDispatcherMultipleConnectionTests() var command = new MyCommand(); var commandMessage = new MyCommandMessageMapper().MapToMessage(command, new Publication{Topic = _commandRoutingKey}); _bus.Enqueue(commandMessage); - + Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); } @@ -67,9 +67,9 @@ public void When_A_Message_Dispatcher_Starts_Different_Types_Of_Performers() { Task.Delay(1000).Wait(); _numberOfConsumers = _dispatcher.Consumers.Count(); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages - + _dispatcher.End().Wait(); @@ -80,7 +80,7 @@ public void When_A_Message_Dispatcher_Starts_Different_Types_Of_Performers() Assert.Equal(2, _numberOfConsumers); } #pragma warning restore xUnit1031 - + public void Dispose() { if (_dispatcher?.State == DispatcherState.DS_RUNNING) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_multiple_performers.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_multiple_performers.cs index 562c67c129..2c037a3ff0 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_multiple_performers.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_dispatcher_starts_multiple_performers.cs @@ -21,8 +21,8 @@ public MessageDispatcherMultiplePerformerTests() { var routingKey = new RoutingKey(Topic); _bus = new InternalBus(); - var consumer = new InMemoryMessageConsumer(routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000)); - + var consumer = new InMemoryMessageConsumer(routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); + IAmAChannelSync channel = new Channel(new (ChannelName), new(Topic), consumer, 6); IAmACommandProcessor commandProcessor = new SpyCommandProcessor(); @@ -32,21 +32,21 @@ public MessageDispatcherMultiplePerformerTests() messageMapperRegistry.Register(); var connection = new Subscription( - new SubscriptionName("test"), - noOfPerformers: 3, - timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System), - channelName: new ChannelName("fakeChannel"), + new SubscriptionName("test"), + noOfPerformers: 3, + timeOut: TimeSpan.FromMilliseconds(100), + channelFactory: new InMemoryChannelFactory(_bus, TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory), + channelName: new ChannelName("fakeChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: routingKey ); - _dispatcher = new Dispatcher(commandProcessor, new List { connection }, messageMapperRegistry); + _dispatcher = new Dispatcher(commandProcessor, new List { connection }, Initializer.TestLoggerFactory, messageMapperRegistry); var @event = new MyEvent(); var message = new MyEventMessageMapper().MapToMessage(@event, new Publication{Topic = connection.RoutingKey}); for (var i = 0; i < 6; i++) channel.Enqueue(message); - + Assert.Equal(DispatcherState.DS_AWAITING, _dispatcher.State); _dispatcher.Receive(); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status.cs index eb7c1e8d88..858137ef0b 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_the_rejection_description_matches_the_span_status.cs @@ -40,7 +40,7 @@ public MessagePumpMappingRejectionDescriptionMatchesSpanStatusTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -56,7 +56,7 @@ public MessagePumpMappingRejectionDescriptionMatchesSpanStatusTests() messageTransformerFactory, new InMemoryRequestContextFactory(), _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs index 9070708a8a..209ddb75fa 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs @@ -40,7 +40,7 @@ public MessagePumpFailingMessageTranslationTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -56,7 +56,7 @@ public MessagePumpFailingMessageTranslationTests() messageTransformerFactory, new InMemoryRequestContextFactory(), _channel, - tracer, + Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs index 2c5da67e10..4b75536208 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs @@ -48,14 +48,14 @@ public MessagePumpUnacceptableMessageLimitTests() Channel channel = new(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000))); + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new FailingEventMessageMapper()), null); messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyFailingMapperEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs index 664540d258..0d4984593c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs @@ -32,13 +32,13 @@ public MessagePumpDispatchTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new("myChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( @@ -47,7 +47,7 @@ public MessagePumpDispatchTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_mapper_throws_invalid_message_action.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_mapper_throws_invalid_message_action.cs index e3f5abee5e..4cc3b5d32c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_mapper_throws_invalid_message_action.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_mapper_throws_invalid_message_action.cs @@ -45,14 +45,14 @@ public MessageDispatchInvalidMessageActionTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var subscription = new InMemorySubscription( new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey @@ -63,7 +63,7 @@ public MessageDispatchInvalidMessageActionTests() _dispatcher = new Dispatcher( commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, requestContextFactory: new InMemoryRequestContextFactory() ); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs index 5f72e509b3..c534b6a415 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs @@ -24,24 +24,24 @@ public class MessagePumpCommandRequeueCountThresholdTests public MessagePumpCommandRequeueCountThresholdTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - _channel = new Channel(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; - var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize((MyCommand)new(), JsonSerialisationOptions.Options)) ); - var message2 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + var message2 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize((MyCommand)new(), JsonSerialisationOptions.Options)) ); _bus.Enqueue(message1); _bus.Enqueue(message2); - + } [Fact] @@ -49,7 +49,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Commands_Has_Been_Reached() { var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages var quitMessage = MessageFactory.CreateQuitMessage(new RoutingKey("MyTopic")); @@ -61,7 +61,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Commands_Has_Been_Reached() Assert.Equal(6, _commandProcessor.SendCount); Assert.Empty(_bus.Stream(_routingKey)); - + //TODO: How can we observe that the channel has been closed? Observability? } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs index a75c39770f..c7d0b8541f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs @@ -24,26 +24,26 @@ public class MessagePumpEventRequeueCountThresholdTests public MessagePumpEventRequeueCountThresholdTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - _channel = new Channel(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); - - _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); _bus.Enqueue(message1); _bus.Enqueue(message2); - + } [Fact] @@ -51,7 +51,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Events_Has_Been_Reached() { var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.Delay(1000); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); @@ -63,7 +63,7 @@ public async Task When_A_Requeue_Count_Threshold_For_Events_Has_Been_Reached() Assert.Equal(6, _commandProcessor.PublishCount); Assert.Empty(_bus.Stream(_routingKey)); - + //TODO: How do we assert that the channel was closed? Observability? } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs index 276b186b7e..adf4570f63 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs @@ -24,33 +24,33 @@ public class MessagePumpCommandRequeueTests public MessagePumpCommandRequeueTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - Channel channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), 2); + Channel channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyCommand), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) ); - + var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(_command, JsonSerialisationOptions.Options)) ); - + channel.Enqueue(message1); channel.Enqueue(message2); var quitMessage = new Message( - new MessageHeader(string.Empty, RoutingKey.Empty, MessageType.MT_QUIT), + new MessageHeader(string.Empty, RoutingKey.Empty, MessageType.MT_QUIT), new MessageBody("") ); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs index b51e06f697..bbdabebade 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs @@ -24,48 +24,48 @@ public MessagePumpEventRequeueTests() { _commandProcessor = new SpyRequeueCommandProcessor(); Channel channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 2 ); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); - - _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); var message2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize((MyEvent)new(), JsonSerialisationOptions.Options)) ); - + channel.Enqueue(message1); channel.Enqueue(message2); var quitMessage = MessageFactory.CreateQuitMessage(new RoutingKey("MyTopic")); channel.Enqueue(quitMessage); - + } [Fact] public void When_A_Requeue_Of_Event_Exception_Is_Thrown() { _messagePump.Run(); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages //Should publish the message via the_command_processor Assert.Equal(CommandType.Publish, _commandProcessor.Commands[0]); - + //_should_requeue_the_messages Assert.Equal(2, _bus.Stream(_routingKey).Count()); - + //TODO: How do we know that the channel has been disposed? Observability } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge.cs index 277d184fb0..4b097c0c2f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_aggregate_exception_containing_dont_ack_action_should_not_acknowledge.cs @@ -26,7 +26,7 @@ public MessagePumpEventDontAckAggregateExceptionTests() var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -40,7 +40,7 @@ public MessagePumpEventDontAckAggregateExceptionTests() messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), - channel) + channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throw_a_reject_message_exception.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throw_a_reject_message_exception.cs index c94f63bed1..7961c4606a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throw_a_reject_message_exception.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throw_a_reject_message_exception.cs @@ -45,14 +45,14 @@ public MessageDispatchRejectMessageExceptionTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); var subscription = new InMemorySubscription( new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(_bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(_bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName("myChannel"), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey @@ -63,7 +63,7 @@ public MessageDispatchRejectMessageExceptionTests() _dispatcher = new Dispatcher( commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, requestContextFactory: new InMemoryRequestContextFactory() ); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs index 5a6f338ded..99345b6e62 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs @@ -54,7 +54,7 @@ public MessagePumpEventProcessingDeferMessageActionTests() _channel = new Channel( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -63,12 +63,12 @@ public MessagePumpEventProcessingDeferMessageActionTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, null); + var transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory); var msg = transformPipelineBuilder.BuildWrapPipeline() .Wrap(new MyEvent(), new RequestContext(), new Publication{Topic = _routingKey}); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs index c06674903b..c531c0dd28 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs @@ -30,7 +30,7 @@ public MessagePumpEventProcessingExceptionTests() _channel = new Channel( new (Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), @@ -38,13 +38,13 @@ public MessagePumpEventProcessingExceptionTests() messageMapperRegistry.Register(); var requestContextFactory = new InMemoryRequestContextFactory(); - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, requestContextFactory, _channel) + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, null, requestContextFactory, _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; - var transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, null); + var transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory); var msg = transformPipelineBuilder.BuildWrapPipeline() .Wrap(new MyEvent(), requestContextFactory.Create(), new Publication{Topic = _routingKey}); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs index 9712367054..eb444547c0 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs @@ -49,7 +49,7 @@ public MessagePumpUnacceptableMessageTests() _bus = new InternalBus(); - _channel = new Channel(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), @@ -57,7 +57,7 @@ public MessagePumpUnacceptableMessageTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_dlq.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_dlq.cs index ce34ef27ed..40a6fb9d4c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_dlq.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_dlq.cs @@ -53,7 +53,7 @@ public MessagePumpUnacceptableMessageDeadLetterChannelTests() _channel = new Channel( new (Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -62,7 +62,7 @@ public MessagePumpUnacceptableMessageDeadLetterChannelTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_imc.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_imc.cs index ed46198f97..f4acbfa917 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_imc.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved_and_there_is_a_imc.cs @@ -53,7 +53,7 @@ public MessagePumpUnacceptableMessageInvalidMessageChannelTests() _channel = new Channel( new (Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -62,7 +62,7 @@ public MessagePumpUnacceptableMessageInvalidMessageChannelTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs index dd58fea533..d5e132ab67 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs @@ -22,43 +22,43 @@ public MessagePumpUnacceptableMessageLimitBreachedTests() SpyRequeueCommandProcessor commandProcessor = new(); _bus = new InternalBus(); - + var channel = new Channel( new(Channel), - _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 3 ); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); - - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, - timeProvider:_timeProvider) + + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, + timeProvider:_timeProvider, loggerFactory: Initializer.TestLoggerFactory) { - Channel = channel, - TimeOut = TimeSpan.FromMilliseconds(5000), - RequeueCount = 3, - UnacceptableMessageLimit = 3, + Channel = channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3, + UnacceptableMessageLimit = 3, UnacceptableMessageLimitWindow = TimeSpan.FromMinutes(1) }; var unacceptableMessage1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); var unacceptableMessage2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); var unacceptableMessage3 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); var unacceptableMessage4 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); @@ -66,7 +66,7 @@ public MessagePumpUnacceptableMessageLimitBreachedTests() channel.Enqueue(unacceptableMessage2); channel.Enqueue(unacceptableMessage3); channel.Enqueue(unacceptableMessage4); - + } [Fact] @@ -75,7 +75,7 @@ public async Task When_An_Unacceptable_Message_Limit_Is_Reached() var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); await Task.WhenAll(task); - + _timeProvider.Advance(TimeSpan.FromSeconds(2)); //This will trigger requeue of not acked/rejected messages Assert.Empty(_bus.Stream(_routingKey)); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reset.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reset.cs index a0c0b021e7..beffa0a3cd 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reset.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reset.cs @@ -27,14 +27,14 @@ public class MessagePumpUnacceptableMessageLimitResetTests public MessagePumpUnacceptableMessageLimitResetTests() { _bus = new InternalBus(); - + _channel = new Channel( new(Channel), - _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), 10 ); - + var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register(); @@ -44,8 +44,8 @@ public MessagePumpUnacceptableMessageLimitResetTests() ); var resiliencePipelineRegistry = new ResiliencePipelineRegistry(); - resiliencePipelineRegistry.AddBrighterDefault(); - + resiliencePipelineRegistry.AddBrighterDefault(); + var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyAdvanceTimerEventMessageMapper()), new SimpleMessageMapperFactoryAsync(_ => throw new NotImplementedException())); @@ -57,39 +57,39 @@ public MessagePumpUnacceptableMessageLimitResetTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), resiliencePipelineRegistry, - new InMemorySchedulerFactory() - ); - - _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyAdvanceTimerEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, - timeProvider:_timeProvider) + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); + + _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyAdvanceTimerEvent), + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, + timeProvider:_timeProvider, loggerFactory: Initializer.TestLoggerFactory) { - Channel = _channel, - TimeOut = TimeSpan.FromMilliseconds(5000), - RequeueCount = 3, - UnacceptableMessageLimit = 3, + Channel = _channel, + TimeOut = TimeSpan.FromMilliseconds(5000), + RequeueCount = 3, + UnacceptableMessageLimit = 3, UnacceptableMessageLimitWindow = TimeSpan.FromMinutes(1) }; _unacceptableMessage1 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage2 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage3 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _unacceptableMessage4 = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_UNACCEPTABLE), new MessageBody("") ); _timeAdvanceMessage = new MyAdvanceTimerEventMessageMapper().MapToMessage( - new MyAdvanceTimerEvent(2), + new MyAdvanceTimerEvent(2), new Publication { Topic = _routingKey @@ -102,22 +102,22 @@ public async Task When_An_Unacceptable_Message_Limit_Is_Reached() { _channel.Enqueue(_unacceptableMessage1); _channel.Enqueue(_unacceptableMessage2); - + //force the time forward, whilst in the message loop _channel.Enqueue(_timeAdvanceMessage); - + //will trigger reset of unacceptable message count as window has passed _channel.Enqueue(_unacceptableMessage3); _channel.Enqueue(_unacceptableMessage4); var task = Task.Factory.StartNew(() => _messagePump.Run(), TaskCreationOptions.LongRunning); - - + + _channel.Stop(_routingKey); - + await Task.WhenAll(task); - + Assert.Empty(_bus.Stream(_routingKey)); Assert.Equal(MessagePumpStatus.MP_STOPPED, _messagePump.Status); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_consuming_a_message_the_reactor_releases_every_mapper_it_creates.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_consuming_a_message_the_reactor_releases_every_mapper_it_creates.cs index 0bbdeb2e1d..000a6e038b 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_consuming_a_message_the_reactor_releases_every_mapper_it_creates.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_consuming_a_message_the_reactor_releases_every_mapper_it_creates.cs @@ -38,20 +38,20 @@ public ReactorConsumeMapperReleaseTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new("myChannel"), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry(_mapperFactory, null); messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, _ => typeof(MyEvent), - messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_dispatcher_shuts_immediately_after_receive_should_not_hang.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_dispatcher_shuts_immediately_after_receive_should_not_hang.cs index 30c9cf1abc..71ea2e32ca 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_dispatcher_shuts_immediately_after_receive_should_not_hang.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_dispatcher_shuts_immediately_after_receive_should_not_hang.cs @@ -107,13 +107,13 @@ private static Dispatcher BuildDispatcher(int noOfPerformers, string subscriptio new SubscriptionName(subscriptionName), noOfPerformers: noOfPerformers, timeOut: TimeSpan.FromMilliseconds(100), - channelFactory: new InMemoryChannelFactory(bus, new FakeTimeProvider()), + channelFactory: new InMemoryChannelFactory(bus, new FakeTimeProvider(), loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Reactor, routingKey: RoutingKey ); - return new Dispatcher(commandProcessor, new List { subscription }, messageMapperRegistry); + return new Dispatcher(commandProcessor, new List { subscription }, Initializer.TestLoggerFactory, messageMapperRegistry); } private static void DrainDispatcher(Dispatcher dispatcher) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_no_imq_configured_reject_falls_back_to_dlq.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_no_imq_configured_reject_falls_back_to_dlq.cs index 60a99ca34c..8209cee30e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_no_imq_configured_reject_falls_back_to_dlq.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_no_imq_configured_reject_falls_back_to_dlq.cs @@ -47,7 +47,7 @@ public MessagePumpMappingFailureNoImqFallsToDlqTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, deadLetterTopic: _deadLetterKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -61,7 +61,7 @@ public MessagePumpMappingFailureNoImqFallsToDlqTests() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs index 00ef17e270..7c7e9274d2 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a__dynamic_message_from_a_channel_pump_out_to_command_processor.cs @@ -24,10 +24,10 @@ public MessagePumpToCommandProcessorDynamicMappingTests() { _commandProcessor = new SpyCommandProcessor(); _channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); - + var messagerMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(type => type switch @@ -39,15 +39,15 @@ public MessagePumpToCommandProcessorDynamicMappingTests() null); messagerMapperRegistry.Register(); messagerMapperRegistry.Register(); - + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => message switch { - var m when m.Header.Type == new CloudEventsType("io.brighter.paramore.myevent") => typeof(MyEvent), + var m when m.Header.Type == new CloudEventsType("io.brighter.paramore.myevent") => typeof(MyEvent), var m when m.Header.Type == new CloudEventsType("io.brighter.paramore.myotherevent") => typeof(MyOtherEvent), _ => throw new ArgumentException($"No type mapping found for message with type {message.Header.Type}", nameof(message)), - }, - messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + }, + messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; } @@ -55,20 +55,20 @@ public MessagePumpToCommandProcessorDynamicMappingTests() public void When_Reading_A_MyOtherEvent_Message_From_A_Channel_Pump_Out_To_Command_Processor() { //arrange - var @event = new MyEvent(); //although we send a MyEvent, we will map it dynamically to a MyOtherEvent + var @event = new MyEvent(); //although we send a MyEvent, we will map it dynamically to a MyOtherEvent var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myotherevent") ), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myotherevent") ), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); - + _channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); _channel.Enqueue(quitMessage); - + //act _messagePump.Run(); - + //assert Assert.Equal(CommandType.Publish, _commandProcessor.Commands[0]); @@ -76,25 +76,25 @@ public void When_Reading_A_MyOtherEvent_Message_From_A_Channel_Pump_Out_To_Comma Assert.Equal(@event.Id, myOtherEvent.Id); Assert.Equal(@event.Data, myOtherEvent.Data); } - + [Fact] public void When_Reading_A_MyEvent_Message_From_A_Channel_Pump_Out_To_Command_Processor() { //arrange - var @event = new MyEvent(); //we send a MyEvent, we will map it dynamically to a MyEvent + var @event = new MyEvent(); //we send a MyEvent, we will map it dynamically to a MyEvent var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myevent") ), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT, type: new CloudEventsType("io.brighter.paramore.myevent") ), new MessageBody(JsonSerializer.Serialize(@event, JsonSerialisationOptions.Options)) ); - + _channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); _channel.Enqueue(quitMessage); - + //act _messagePump.Run(); - + //assert Assert.Equal(CommandType.Publish, _commandProcessor.Commands[0]); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs index e68d13165e..30e52905cc 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs @@ -24,30 +24,30 @@ public MessagePumpToCommandProcessorTests() { _commandProcessor = new SpyCommandProcessor(); Channel channel = new( - new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new(Channel), _routingKey, + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); - + var messagerMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messagerMapperRegistry.Register(); - - _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), - messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + + _messagePump = new ServiceActivator.Reactor(_commandProcessor, (message) => typeof(MyEvent), + messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; _event = new MyEvent(); var message = new Message( - new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), + new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(_event, JsonSerialisationOptions.Options)) ); - + channel.Enqueue(message); var quitMessage = MessageFactory.CreateQuitMessage(_routingKey); channel.Enqueue(quitMessage); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs index aa9a89f7cf..c9e29a8602 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs @@ -25,7 +25,7 @@ public PerformerCanStopTests() SpyCommandProcessor commandProcessor = new(); Channel channel = new( new(Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -34,7 +34,7 @@ public PerformerCanStopTests() messageMapperRegistry.Register(); var messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel); + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory); messagePump.Channel = channel; messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_mapping_reject_path_is_compared_across_pumps.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_mapping_reject_path_is_compared_across_pumps.cs index 2adad95555..30f7f9fa17 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_mapping_reject_path_is_compared_across_pumps.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_mapping_reject_path_is_compared_across_pumps.cs @@ -48,7 +48,7 @@ public MessagePumpMappingRejectPathParityTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -62,7 +62,7 @@ public MessagePumpMappingRejectPathParityTests() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit.cs index ba81af5c6d..73a34e90d6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_the_unacceptable_message_limit_is_zero_mapping_failures_never_trip_the_limit.cs @@ -24,7 +24,7 @@ public MessagePumpDefaultLimitZeroMappingFailuresNeverTripLimitTests() new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, invalidMessageTopic: _invalidMessageKey, - ackTimeout: TimeSpan.FromMilliseconds(1000)) + ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -39,7 +39,7 @@ public MessagePumpDefaultLimitZeroMappingFailuresNeverTripLimitTests() messageMapperRegistry, null, new InMemoryRequestContextFactory(), - _channel) + _channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_async_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_async_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs index d0f68a010f..1d6724517a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_async_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_async_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs @@ -49,7 +49,7 @@ public DispatcherAsyncDisposalDrainsPumpsTests() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey); @@ -57,7 +57,7 @@ public DispatcherAsyncDisposalDrainsPumpsTests() _dispatcher = new Dispatcher( commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, messageTransformerFactory: _transformerFactory, ownsTransformerFactories: true); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_building_a_dispatcher_ownership_flows_from_the_builder.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_building_a_dispatcher_ownership_flows_from_the_builder.cs index 54d8725351..c69cb7c267 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_building_a_dispatcher_ownership_flows_from_the_builder.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_building_a_dispatcher_ownership_flows_from_the_builder.cs @@ -63,14 +63,15 @@ private static IAmADispatchBuilder BuildDispatcher( IAmAMessageTransformerFactory syncTransformerFactory, IAmAMessageTransformerFactoryAsync asyncTransformerFactory) { - var channelFactory = new InMemoryChannelFactory(new InternalBus(), TimeProvider.System); + var channelFactory = new InMemoryChannelFactory(new InternalBus(), TimeProvider.System, loggerFactory: Initializer.TestLoggerFactory); return DispatchBuilder .StartNew() .CommandProcessor(new SpyCommandProcessor(), new InMemoryRequestContextFactory()) .MessageMappers(mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory) .ChannelFactory(channelFactory) .Subscriptions(new List()) - .NoInstrumentation(); + .NoInstrumentation() + .ConfigureLogging(Initializer.TestLoggerFactory); } private sealed class DisposeCountingMapperFactory : IAmAMessageMapperFactory, IDisposable diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_configuring_the_dispatcher_shutdown_timeout.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_configuring_the_dispatcher_shutdown_timeout.cs index 917660e922..65c192739e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_configuring_the_dispatcher_shutdown_timeout.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_configuring_the_dispatcher_shutdown_timeout.cs @@ -45,7 +45,7 @@ private static Dispatcher BuildDispatcher(TimeSpan? shutdownTimeout) return new Dispatcher( commandProcessor, new List(), - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, shutdownTimeout: shutdownTimeout); } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs index f5036b1bd9..3b2444e1ad 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_a_running_dispatcher_it_drains_before_disposing_factories.cs @@ -48,7 +48,7 @@ public DispatcherDisposalDrainsPumpsTests() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey); @@ -56,7 +56,7 @@ public DispatcherDisposalDrainsPumpsTests() _dispatcher = new Dispatcher( commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, ownsRegistry: true); //the factory can only read the dispatcher's state at dispose time once the dispatcher exists diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_the_dispatcher_it_disposes_its_factories.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_the_dispatcher_it_disposes_its_factories.cs index d910568886..a7b9aa8d95 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_the_dispatcher_it_disposes_its_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_disposing_the_dispatcher_it_disposes_its_factories.cs @@ -29,7 +29,7 @@ public void When_disposing_the_dispatcher_it_disposes_the_registry_and_transform var dispatcher = new Dispatcher( commandProcessor, new List(), - mapperRegistry, + Initializer.TestLoggerFactory, mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory, @@ -65,7 +65,7 @@ public void When_disposing_the_dispatcher_twice_it_disposes_each_factory_once() var dispatcher = new Dispatcher( commandProcessor, new List(), - mapperRegistry, + Initializer.TestLoggerFactory, mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_dispatcher_does_not_own_its_factories.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_dispatcher_does_not_own_its_factories.cs index 3555b48305..5b047c2af7 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_dispatcher_does_not_own_its_factories.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_dispatcher_does_not_own_its_factories.cs @@ -33,7 +33,7 @@ public void When_the_dispatcher_does_not_own_its_factories_it_does_not_dispose_t var dispatcher = new Dispatcher( new SpyCommandProcessor(), new List(), - mapperRegistry, + Initializer.TestLoggerFactory, mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory); @@ -63,7 +63,7 @@ public void When_the_dispatcher_owns_only_the_registry_it_disposes_only_the_regi var dispatcher = new Dispatcher( new SpyCommandProcessor(), new List(), - mapperRegistry, + Initializer.TestLoggerFactory, mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory, @@ -93,7 +93,7 @@ public void When_the_dispatcher_owns_only_the_transform_factories_it_disposes_on var dispatcher = new Dispatcher( new SpyCommandProcessor(), new List(), - mapperRegistry, + Initializer.TestLoggerFactory, mapperRegistry, mapperRegistry, syncTransformerFactory, asyncTransformerFactory, diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_drain_exceeds_the_shutdown_timeout_dispose_still_returns.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_drain_exceeds_the_shutdown_timeout_dispose_still_returns.cs index 76c1641174..9d99905f0a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_drain_exceeds_the_shutdown_timeout_dispose_still_returns.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/When_the_drain_exceeds_the_shutdown_timeout_dispose_still_returns.cs @@ -46,7 +46,7 @@ public DispatcherDisposeHonoursShutdownTimeoutTests() new SubscriptionName("test"), noOfPerformers: 1, timeOut: TimeSpan.FromMilliseconds(1000), - channelFactory: new InMemoryChannelFactory(bus, _timeProvider), + channelFactory: new InMemoryChannelFactory(bus, _timeProvider, loggerFactory: Initializer.TestLoggerFactory), channelName: new ChannelName(ChannelName), messagePumpType: MessagePumpType.Reactor, routingKey: _routingKey); @@ -54,7 +54,7 @@ public DispatcherDisposeHonoursShutdownTimeoutTests() _dispatcher = new Dispatcher( _commandProcessor, new List { subscription }, - messageMapperRegistry, + Initializer.TestLoggerFactory, messageMapperRegistry, messageTransformerFactory: _transformerFactory, ownsTransformerFactories: true, shutdownTimeout: TimeSpan.FromMilliseconds(250)); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released.cs index 23937dd7ea..62932df3e3 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released.cs @@ -22,7 +22,7 @@ public TransformPipelinePartialWrapBuildReleaseTests() mapperRegistry.Register(); _transformerFactory = new RecordingTransformerFactory(); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released_Async.cs index 53d6d7580b..8719e85f8e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Later_Wrap_Transform_Cannot_Be_Created_Earlier_Transforms_Are_Released_Async.cs @@ -26,7 +26,7 @@ public AsyncTransformPipelinePartialWrapBuildReleaseTests() mapperRegistry.RegisterAsync(); _transformerFactory = new RecordingTransformerFactoryAsync(); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_Transform.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_Transform.cs index 5a9aed385f..7f459ce316 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_Transform.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_Transform.cs @@ -20,7 +20,7 @@ public MessageUnwrapPathPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_TransformAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_TransformAsync.cs index 6e0295a556..2cb82546e6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_TransformAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_A_TransformAsync.cs @@ -21,7 +21,7 @@ public AsyncMessageUnwrapPathPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_Transform.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_Transform.cs index eded1cda11..b09ab8b848 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_Transform.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_Transform.cs @@ -20,7 +20,7 @@ public MessageUnwrapPathNoTransformPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => null)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_TransformAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_TransformAsync.cs index efc330dbc3..9f62a04792 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_TransformAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Message_Has_No_TransformAsync.cs @@ -21,7 +21,7 @@ public AsyncMessageUnwrapPathNoTransformPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => null)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_Transform.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_Transform.cs index 3c7d1c9fa1..b06689b460 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_Transform.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_Transform.cs @@ -21,7 +21,7 @@ public MessageWrapPathPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_TransformAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_TransformAsync.cs index 893a36aa12..0b2a579c4c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_TransformAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_A_TransformAsync.cs @@ -22,7 +22,7 @@ public AsyncMessageWrapPathPipelineTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform.cs index 0cb27b1bde..277a95cefb 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform.cs @@ -20,7 +20,7 @@ public MessageWrapPathPipelineNoTransformTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => null)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform_Async.cs index 607c8110a4..233d4a2741 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Message_Mapper_Map_To_Request_Has_No_Transform_Async.cs @@ -21,7 +21,7 @@ public AsyncMessageWrapPathPipelineNoTransformTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => null)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Transform_Release_Throws_During_A_Failed_Build.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Transform_Release_Throws_During_A_Failed_Build.cs index 31586f1c6f..c14edbbe42 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Transform_Release_Throws_During_A_Failed_Build.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Transform_Release_Throws_During_A_Failed_Build.cs @@ -31,7 +31,7 @@ public void When_a_transform_release_throws_during_a_partial_build_the_others_ar new SimpleMessageMapperFactory(_ => new MyThreeWrapTransformMessageMapper()), null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactory); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactory, loggerFactory: Initializer.TestLoggerFactory); //act var exception = Catch.Exception(() => pipelineBuilder.BuildWrapPipeline()); @@ -62,7 +62,7 @@ public void When_cleanup_of_a_failed_build_throws_the_original_error_is_not_mask new SimpleMessageMapperFactory(_ => new MyExplicitUnwrapWrapMessageMapper()), null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactory); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactory, loggerFactory: Initializer.TestLoggerFactory); //act var exception = Catch.Exception(() => pipelineBuilder.BuildWrapPipeline()); @@ -170,7 +170,7 @@ public void When_a_transform_release_throws_during_a_partial_build_the_others_ar null, new SimpleMessageMapperFactoryAsync(_ => new MyThreeWrapTransformMessageMapperAsync())); mapperRegistry.RegisterAsync(); - var pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactory, InstrumentationOptions.All); + var pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); //act var exception = Catch.Exception(() => pipelineBuilder.BuildWrapPipeline()); @@ -194,7 +194,7 @@ public void When_cleanup_of_a_failed_build_throws_the_original_error_is_not_mask null, new SimpleMessageMapperFactoryAsync(_ => new MyExplicitUnwrapWrapMessageMapperAsync())); mapperRegistry.RegisterAsync(); - var pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactory, InstrumentationOptions.All); + var pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); //act var exception = Catch.Exception(() => pipelineBuilder.BuildWrapPipeline()); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released.cs index a2f7f8898c..9c8a2eb62e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released.cs @@ -22,7 +22,7 @@ public TransformerFactoryInitializeFailureReleaseTests() mapperRegistry.Register(); _transformerFactory = new RecordingTransformerFactory(); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released_Async.cs index f180526802..3774481f3e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_A_Wrap_Transform_Fails_To_Initialize_It_Is_Released_Async.cs @@ -25,7 +25,7 @@ public AsyncTransformerFactoryInitializeFailureReleaseTests() mapperRegistry.RegisterAsync(); _transformerFactory = new RecordingTransformerFactoryAsync(); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs index 1cae2b663e..6ab8b32c08 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs @@ -93,7 +93,7 @@ public void When_a_single_mapper_is_built_twice_should_leave_one_entry_per_trans registry.Register(); var transformerFactory = new SimpleMessageTransformerFactory(_ => new Reuse.ReuseTransform()); - var builder = new TransformPipelineBuilder(registry, transformerFactory); + var builder = new TransformPipelineBuilder(registry, transformerFactory, loggerFactory: Initializer.TestLoggerFactory); // Act — build the same mapper's wrap and unwrap pipelines twice (single-threaded) string firstWrap = Trace(builder.BuildWrapPipeline()).ToString(); @@ -128,7 +128,7 @@ private static TransformPipelineBuilder CreateCollidingBuilder() ? new A.FirstTransform() : (IAmAMessageTransform)new B.SecondTransform()); - return new TransformPipelineBuilder(registry, transformerFactory); + return new TransformPipelineBuilder(registry, transformerFactory, loggerFactory: Initializer.TestLoggerFactory); } private static TransformPipelineTracer Trace(WrapPipeline pipeline) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released.cs index 955be0e9dd..7bccaac4c9 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released.cs @@ -22,7 +22,7 @@ public TransformPipelinePostConstructionFailureReleaseTests() mapperRegistry.Register(); _transformerFactory = new RecordingTransformerFactory(); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, _transformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released_Async.cs index fd4c62b6d1..3ec8ae84f8 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_A_Wrap_Pipeline_Fails_After_Construction_Transforms_Are_Released_Async.cs @@ -25,7 +25,7 @@ public AsyncTransformPipelinePostConstructionFailureReleaseTests() mapperRegistry.RegisterAsync(); _transformerFactory = new RecordingTransformerFactoryAsync(); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, _transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_An_Async_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_An_Async_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs index d356ffed36..13c2605a8c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_An_Async_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Building_An_Async_Transform_Pipeline_Disambiguates_Mappers_By_Type.cs @@ -94,7 +94,7 @@ public void When_a_single_async_mapper_is_built_twice_post_warmup_should_keep_on registry.RegisterAsync(); var transformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new Reuse.ReuseTransformAsync()); - var builder = new TransformPipelineBuilderAsync(registry, transformerFactory, InstrumentationOptions.All); + var builder = new TransformPipelineBuilderAsync(registry, transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); // Act — build the same mapper's wrap and unwrap pipelines twice (single-threaded, so the // GetOrAdd factory has already run and the retained entry is served thereafter) @@ -130,7 +130,7 @@ private static TransformPipelineBuilderAsync CreateCollidingBuilder() ? new A.FirstTransformAsync() : (IAmAMessageTransformAsync)new B.SecondTransformAsync()); - return new TransformPipelineBuilderAsync(registry, transformerFactory, InstrumentationOptions.All); + return new TransformPipelineBuilderAsync(registry, transformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } private static TransformPipelineTracer Trace(WrapPipelineAsync pipeline) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry.cs index d4c8dc670a..1f5929a3f4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry.cs @@ -15,7 +15,7 @@ public void When_Creating_A_Pipeline_Builder_Without_A_Registry() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); //act - var exception = Catch.Exception(() => new TransformPipelineBuilder(null, messageTransformerFactory)); + var exception = Catch.Exception(() => new TransformPipelineBuilder(null, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory)); //assert Assert.NotNull(exception); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry_Async.cs index c5fb4bf80c..9b1273437d 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Pipeline_Builder_Without_A_Registry_Async.cs @@ -16,7 +16,7 @@ public void When_Creating_A_Pipeline_Builder_Without_A_Registry() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); //act - var exception = Catch.Exception(() => new TransformPipelineBuilderAsync(null, messageTransformerFactory, InstrumentationOptions.All)); + var exception = Catch.Exception(() => new TransformPipelineBuilderAsync(null, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All)); //assert Assert.NotNull(exception); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory.cs index 1433af116e..5fc109342f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory.cs @@ -25,7 +25,7 @@ public TransformPipelineMissingFactoryWrapTests() _publication = new Publication { Topic = new RoutingKey("MyTransformableCommand") }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, null); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory_Async.cs index 30ac902219..a3054d2faa 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_A_Wrap_Without_A_Factory_Async.cs @@ -27,7 +27,7 @@ public AsyncTransformPipelineMissingFactoryWrapTests() _publication = new Publication{Topic = new RoutingKey("MyTransformableCommand"), RequestType= typeof(MyTransformableCommand)}; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, null, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory.cs index 289145caee..196d519565 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory.cs @@ -29,7 +29,7 @@ public TransformPipelineMissingFactoryUnwrapTests() new MessageBody(JsonSerializer.Serialize(_myCommand, new JsonSerializerOptions(JsonSerializerDefaults.General))) ); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, null); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, null, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory_Async.cs index 59cc0e0fdd..ac0b2a0b99 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Creating_An_Unwrap_Without_A_Factory_Async.cs @@ -31,7 +31,7 @@ public AsyncTransformPipelineMissingFactoryUnwrapTests() new MessageBody(JsonSerializer.Serialize(_myCommand, new JsonSerializerOptions(JsonSerializerDefaults.General))) ); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, null, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, null, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper.cs index 67227ff94a..732f2a0948 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper.cs @@ -26,7 +26,7 @@ public MessageUnwrapRequestTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_MapperAsync.cs index f8de6a010e..24027b5f14 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_MapperAsync.cs @@ -28,7 +28,7 @@ public AsyncMessageUnwrapRequestTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); _message = new Message( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs index 330012e95e..d099d54825 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs @@ -24,7 +24,7 @@ public MessageUnwrapRequestMissingTransformTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => null)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); Message message = new( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_With_Parameters.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_With_Parameters.cs index 459e967a46..879c852a1f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_With_Parameters.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Message_Mapper_With_Parameters.cs @@ -26,7 +26,7 @@ public MessageUnwrapRequestWithAttributesTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MyParameterizedTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_Mapper.cs index 893c24e722..f8484f57e1 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_Mapper.cs @@ -26,7 +26,7 @@ public VanillaMessageUnwrapRequestTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => null)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); _message = new Message( new MessageHeader(_myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_MapperAsync.cs index 80ed742308..6651c8464b 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_A_Vanilla_Message_MapperAsync.cs @@ -28,7 +28,7 @@ public AsyncVanillaMessageUnwrapRequestTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => null)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); _message = new Message( new MessageHeader(_myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null.cs index 17f27c7d9a..3e52a6b7f9 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null.cs @@ -25,7 +25,7 @@ public MessageUnwrapRequestFailingMapperFactoryTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); Message message = new( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null_Async.cs index 05a1360bda..7ad81f4425 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_Factory_Returns_Null_Async.cs @@ -27,7 +27,7 @@ public AsyncMessageUnwrapRequestFailingMapperFactoryTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); Message message = new( new MessageHeader(myCommand.Id, new("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_Mapper.cs index 95f119c95e..078246b3b1 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_Mapper.cs @@ -24,7 +24,7 @@ public MessageUnwrapRequestMissingMapperTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MySimpleTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); Message message = new( new MessageHeader(myCommand.Id, new RoutingKey("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_MapperAsync.cs index 47557cd3f6..1bee9e32ff 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Unwrapping_But_No_Registered_MapperAsync.cs @@ -25,7 +25,7 @@ public AsyncMessageUnwrapRequestMissingMapperTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); Message message = new( new MessageHeader(myCommand.Id, new RoutingKey("transform.event"), MessageType.MT_COMMAND, timeStamp: DateTime.UtcNow), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper.cs index 0593f1e3d6..565792adff 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper.cs @@ -27,7 +27,7 @@ public MessageWrapRequestTests() _publication = new Publication { Topic = new RoutingKey("MyTransformableCommand") }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_MapperAsync.cs index 39a5f1a090..ba63f742d5 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_MapperAsync.cs @@ -29,7 +29,7 @@ public AsyncMessageWrapRequestTests() _publication = new Publication{Topic = new RoutingKey("MyTransformableCommand"), RequestType= typeof(MyTransformableCommand)}; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs index 4598f3707e..b82caf5d1c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory.cs @@ -20,7 +20,7 @@ public MessageWrapRequestMissingTransformTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => null)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory_Async.cs index da12d72cee..d88f7226d1 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_But_Not_In_Transform_Factory_Async.cs @@ -21,7 +21,7 @@ public AsyncMessageWrapRequestMissingTransformTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => null)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters.cs index 594815e060..aa293cf3be 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters.cs @@ -28,7 +28,7 @@ public MessageWrapRequestWithAttributesTests() var messageTransformerFactory = new SimpleMessageTransformerFactory((_ => new MyParameterizedTransform())); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters_Async.cs index 0c40c7fd36..c017b4728a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Mapper_With_Parameters_Async.cs @@ -33,7 +33,7 @@ public AsyncMessageWrapRequestWithAttributesTests() Topic = new RoutingKey("MyTransformableCommand"), RequestType = typeof(MyTransformableCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Whose_Topic_Matches_The_Publication.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Whose_Topic_Matches_The_Publication.cs index 6ce0c9c5ce..e142e090fe 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Whose_Topic_Matches_The_Publication.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Message_Whose_Topic_Matches_The_Publication.cs @@ -30,7 +30,7 @@ public void When_The_Mapper_Topic_Matches_The_Publication_No_Producer_Topic_Bag_ var pipelineBuilder = new TransformPipelineBuilder( mapperRegistry, - new SimpleMessageTransformerFactory(_ => null)); + new SimpleMessageTransformerFactory(_ => null), loggerFactory: Initializer.TestLoggerFactory); var message = pipelineBuilder .BuildWrapPipeline() diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_Mapper.cs index f207b25a91..17801e4d61 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_Mapper.cs @@ -31,7 +31,7 @@ public ReplyMessageWrapRequestTests() RequestType = typeof(MyResponse) }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_MapperAsync.cs index 8ea68fae62..dedc946258 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Reply_Message_MapperAsync.cs @@ -33,7 +33,7 @@ public AsyncReplyMessageWrapRequestTests() RequestType = typeof(MyResponse) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_Mapper.cs index 28af2798a2..b10e41ac2c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_Mapper.cs @@ -27,7 +27,7 @@ public VanillaMessageWrapRequestTests() _publication = new Publication { Topic = new RoutingKey("MyTransformableCommand") }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_MapperAsync.cs index 218f11d241..88505dcea6 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_A_Vanilla_Message_MapperAsync.cs @@ -29,7 +29,7 @@ public AsyncVanillaMessageWrapRequestTests() _publication = new Publication{Topic = new RoutingKey("MyTransformableCommand"), RequestType = typeof(MyTransformableCommand)}; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_Mapper.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_Mapper.cs index 5ae561163b..a54370f3bf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_Mapper.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_Mapper.cs @@ -23,7 +23,7 @@ public MessageWrapRequestMissingMapperTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_MapperAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_MapperAsync.cs index 12df00937a..bc4868e505 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_MapperAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_But_No_Registered_MapperAsync.cs @@ -23,7 +23,7 @@ public AsyncMessageWrapRequestMissingMapperTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync((_ => new MySimpleTransformAsync())); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_Pipeline.cs index ed93927a7f..5597bde26c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_Pipeline.cs @@ -26,7 +26,7 @@ public MessageWrapCleanupTests() _publication = new Publication { Topic = new RoutingKey("MyTransformableCommand") }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new MyReleaseTrackingTransformFactory()); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new MyReleaseTrackingTransformFactory(), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_PipelineAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_PipelineAsync.cs index e0907a42ba..5909f549f4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_PipelineAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_Clean_Up_The_PipelineAsync.cs @@ -28,7 +28,7 @@ public AsyncMessageWrapCleanupTests() _publication = new Publication{Topic = new RoutingKey("MyTransformableCommand"), RequestType= typeof(MyTransformableCommand)}; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, new MyReleaseTrackingTransformFactoryAsync(), InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, new MyReleaseTrackingTransformFactoryAsync(), Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic.cs index 4f13cd354c..329ee1b240 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic.cs @@ -36,7 +36,7 @@ public WrapNullPublicationTopicTests() RequestType = typeof(MyResponse) }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic_Async.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic_Async.cs index 4d15fff484..89c2bc8fee 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_Wrapping_With_Null_Publication_Topic_Async.cs @@ -34,7 +34,7 @@ public AsyncWrapNullPublicationTopicTests() RequestType = typeof(MyResponse) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, Initializer.TestLoggerFactory, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_pipeline_finalizer_release_throws_it_should_not_escape.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_pipeline_finalizer_release_throws_it_should_not_escape.cs index 8b88adcf8b..d582fc6400 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_pipeline_finalizer_release_throws_it_should_not_escape.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_pipeline_finalizer_release_throws_it_should_not_escape.cs @@ -69,7 +69,7 @@ private static void CreateAndAbandonWrapPipeline() messageTransformerFactory: null, transformLeases: Array.Empty>(), instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new ThrowingOnReleaseRegistry()); + mapperRegistry: new ThrowingOnReleaseRegistry(), loggerFactory: Initializer.TestLoggerFactory); } [MethodImpl(MethodImplOptions.NoInlining)] @@ -80,7 +80,7 @@ private static void CreateAndAbandonWrapPipelineAsync() messageTransformerFactoryAsync: null, transformLeases: Array.Empty>(), instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new ThrowingOnReleaseRegistryAsync()); + mapperRegistry: new ThrowingOnReleaseRegistryAsync(), loggerFactory: Initializer.TestLoggerFactory); } private sealed class MinimalCommand() : Command(Guid.NewGuid()); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_lifetime_scope_finalizer_release_throws_it_should_not_escape.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_lifetime_scope_finalizer_release_throws_it_should_not_escape.cs index 22c7828633..b90ae461ff 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_lifetime_scope_finalizer_release_throws_it_should_not_escape.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_lifetime_scope_finalizer_release_throws_it_should_not_escape.cs @@ -59,14 +59,14 @@ private static void CollectAndRunFinalizers() [MethodImpl(MethodImplOptions.NoInlining)] private static void CreateAndAbandonLifetimeScope() { - var scope = new TransformLifetimeScope(new ThrowingOnReleaseTransformerFactory()); + var scope = new TransformLifetimeScope(new ThrowingOnReleaseTransformerFactory(), loggerFactory: Initializer.TestLoggerFactory); scope.Add(Lease.Untracked(new MinimalTransform())); } [MethodImpl(MethodImplOptions.NoInlining)] private static void CreateAndAbandonLifetimeScopeAsync() { - var scope = new TransformLifetimeScopeAsync(new ThrowingOnReleaseTransformerFactoryAsync()); + var scope = new TransformLifetimeScopeAsync(new ThrowingOnReleaseTransformerFactoryAsync(), loggerFactory: Initializer.TestLoggerFactory); scope.Add(Lease.Untracked(new MinimalTransformAsync())); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_release_throws_the_scope_still_releases_the_rest.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_release_throws_the_scope_still_releases_the_rest.cs index 133e52bdf9..e745d032df 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_release_throws_the_scope_still_releases_the_rest.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_release_throws_the_scope_still_releases_the_rest.cs @@ -20,7 +20,7 @@ public void When_a_transform_release_throws_the_scope_drains_the_rest_and_surfac var after = new CountingTransform(); factory.ThrowFor(throwing); - var scope = new TransformLifetimeScope(factory); + var scope = new TransformLifetimeScope(factory, loggerFactory: Initializer.TestLoggerFactory); scope.Add(Lease.Untracked(before)); scope.Add(Lease.Untracked(throwing)); scope.Add(Lease.Untracked(after)); @@ -54,7 +54,7 @@ public async Task When_an_async_transform_release_throws_the_scope_drains_the_re var after = new CountingTransformAsync(); factory.ThrowFor(throwing); - var scope = new TransformLifetimeScopeAsync(factory); + var scope = new TransformLifetimeScopeAsync(factory, loggerFactory: Initializer.TestLoggerFactory); scope.Add(Lease.Untracked(before)); scope.Add(Lease.Untracked(throwing)); scope.Add(Lease.Untracked(after)); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_scope_disposal_throws_the_mapper_is_still_released.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_scope_disposal_throws_the_mapper_is_still_released.cs index 0754983aab..7324831a80 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_scope_disposal_throws_the_mapper_is_still_released.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_a_transform_scope_disposal_throws_the_mapper_is_still_released.cs @@ -32,7 +32,7 @@ public void When_a_sync_pipelines_transform_scope_disposal_throws_the_mapper_is_ messageTransformerFactory: new ThrowingOnReleaseTransformerFactory(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransform()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new RecordingReleaseRegistry(mapper)); + mapperRegistry: new RecordingReleaseRegistry(mapper), loggerFactory: Initializer.TestLoggerFactory); //act — the transform-scope disposal exception still surfaces to the owner; the scope drains //deterministically and reports its release failure as an AggregateException @@ -53,7 +53,7 @@ public async Task When_an_async_pipelines_transform_scope_disposal_throws_the_ma messageTransformerFactoryAsync: new ThrowingOnReleaseTransformerFactoryAsync(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransformAsync()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new RecordingReleaseRegistryAsync(mapper)); + mapperRegistry: new RecordingReleaseRegistryAsync(mapper), loggerFactory: Initializer.TestLoggerFactory); //act var aggregate = await Assert.ThrowsAsync(async () => await pipeline.DisposeAsync()); @@ -74,7 +74,7 @@ public void When_an_async_pipelines_synchronous_disposal_throws_the_mapper_is_st messageTransformerFactoryAsync: new ThrowingOnReleaseTransformerFactoryAsync(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransformAsync()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new RecordingReleaseRegistryAsync(mapper)); + mapperRegistry: new RecordingReleaseRegistryAsync(mapper), loggerFactory: Initializer.TestLoggerFactory); //act var aggregate = Assert.Throws(() => pipeline.Dispose()); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_both_the_transform_scope_and_mapper_release_throw.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_both_the_transform_scope_and_mapper_release_throw.cs index ee19e2563f..bce1a1953e 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_both_the_transform_scope_and_mapper_release_throw.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_both_the_transform_scope_and_mapper_release_throw.cs @@ -29,7 +29,7 @@ public void When_a_sync_pipelines_transform_scope_and_mapper_release_both_throw_ messageTransformerFactory: new ThrowingOnReleaseTransformerFactory(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransform()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new ThrowingOnReleaseRegistry()); + mapperRegistry: new ThrowingOnReleaseRegistry(), loggerFactory: Initializer.TestLoggerFactory); var aggregate = Assert.Throws(() => pipeline.Dispose()); @@ -44,7 +44,7 @@ public async Task When_an_async_pipelines_transform_scope_and_mapper_release_bot messageTransformerFactoryAsync: new ThrowingOnReleaseTransformerFactoryAsync(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransformAsync()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new ThrowingOnReleaseRegistryAsync()); + mapperRegistry: new ThrowingOnReleaseRegistryAsync(), loggerFactory: Initializer.TestLoggerFactory); var aggregate = await Assert.ThrowsAsync(async () => await pipeline.DisposeAsync()); @@ -59,7 +59,7 @@ public void When_an_async_pipelines_synchronous_disposal_transform_scope_and_map messageTransformerFactoryAsync: new ThrowingOnReleaseTransformerFactoryAsync(), transformLeases: new Lease[] { Lease.Untracked(new NoOpTransformAsync()) }, instrumentationOptions: InstrumentationOptions.All, - mapperRegistry: new ThrowingOnReleaseRegistryAsync()); + mapperRegistry: new ThrowingOnReleaseRegistryAsync(), loggerFactory: Initializer.TestLoggerFactory); var aggregate = Assert.Throws(() => pipeline.Dispose()); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_constructing_a_pipeline_with_a_null_mapper_lease.cs b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_constructing_a_pipeline_with_a_null_mapper_lease.cs index a3b7fa1513..89fa8e5894 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_constructing_a_pipeline_with_a_null_mapper_lease.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageSerialisation/When_constructing_a_pipeline_with_a_null_mapper_lease.cs @@ -15,7 +15,7 @@ public void When_constructing_a_wrap_pipeline_with_a_null_mapper_lease_it_should messageMapperLease: null!, messageTransformerFactory: null, transformLeases: Array.Empty>(), - instrumentationOptions: InstrumentationOptions.All)); + instrumentationOptions: InstrumentationOptions.All, loggerFactory: Initializer.TestLoggerFactory)); //assert Assert.Equal("messageMapperLease", exception.ParamName); @@ -29,7 +29,7 @@ public void When_constructing_an_async_wrap_pipeline_with_a_null_mapper_lease_it messageMapperLease: null!, messageTransformerFactoryAsync: null, transformLeases: Array.Empty>(), - instrumentationOptions: InstrumentationOptions.All)); + instrumentationOptions: InstrumentationOptions.All, loggerFactory: Initializer.TestLoggerFactory)); //assert Assert.Equal("messageMapperLease", exception.ParamName); diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_A_Stop_Message_Is_Added_To_A_Channel.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_A_Stop_Message_Is_Added_To_A_Channel.cs index ac6a48a043..eeb1688ec4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_A_Stop_Message_Is_Added_To_A_Channel.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_A_Stop_Message_Is_Added_To_A_Channel.cs @@ -37,14 +37,14 @@ public class ChannelStopTests public ChannelStopTests() { _bus = new InternalBus(); - IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(_routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000)); + IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(_routingKey, _bus, TimeProvider.System, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new(ChannelName),_routingKey, gateway); Message sentMessage = new( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("a test body")); - + _bus.Enqueue(sentMessage); _channel.Stop(_routingKey); @@ -55,7 +55,7 @@ public void When_A_Stop_Message_Is_Added_To_A_Channel() { var stopMessage = _channel.Receive(TimeSpan.FromMilliseconds(1000)); Assert.Equal(MessageType.MT_QUIT, stopMessage.Header.MessageType); - + Assert.Single(_bus.Stream(new RoutingKey(_routingKey))); } } diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Acknowledge_Is_Called_On_A_Channel.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Acknowledge_Is_Called_On_A_Channel.cs index 57f2e2547d..47bfe26841 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Acknowledge_Is_Called_On_A_Channel.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Acknowledge_Is_Called_On_A_Channel.cs @@ -38,14 +38,14 @@ public class ChannelAcknowledgeTests public ChannelAcknowledgeTests() { - IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(Topic), _bus, _fakeTimeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(Topic), _bus, _fakeTimeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new (ChannelName), new(Topic), gateway); var sentMessage = new Message( new MessageHeader(Guid.NewGuid().ToString(), Topic, MessageType.MT_EVENT), new MessageBody("a test body")); - + _bus.Enqueue(sentMessage); } @@ -54,7 +54,7 @@ public void When_Acknowledge_Is_Called_On_A_Channel_Should_Be_Removed() { var receivedMessage = _channel.Receive(TimeSpan.FromMilliseconds(1000)); _channel.Acknowledge(receivedMessage); - + _fakeTimeProvider.Advance(TimeSpan.FromSeconds(2)); //allow for message to timeout if not acked } diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Constructing_A_Combined_Producer_Registry.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Constructing_A_Combined_Producer_Registry.cs index fb8ed6af3b..42bb4e3ba5 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Constructing_A_Combined_Producer_Registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Constructing_A_Combined_Producer_Registry.cs @@ -26,8 +26,8 @@ public void When_constructing_a_combined_producer_registry() } }; - var firstProducerFactory = new InMemoryMessageProducerFactory(bus, firstProducers, InstrumentationOptions.All); - var secondProducerFactory = new InMemoryMessageProducerFactory(bus, secondProducers, InstrumentationOptions.All); + var firstProducerFactory = new InMemoryMessageProducerFactory(bus, firstProducers, Initializer.TestLoggerFactory, InstrumentationOptions.All); + var secondProducerFactory = new InMemoryMessageProducerFactory(bus, secondProducers, Initializer.TestLoggerFactory, InstrumentationOptions.All); var combinedRegistryFactory = new CombinedProducerRegistryFactory(firstProducerFactory, secondProducerFactory); var producerRegistry = combinedRegistryFactory.Create(); diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Listening_To_Messages_On_A_Channel.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Listening_To_Messages_On_A_Channel.cs index 9c37236950..21fbd99b0c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Listening_To_Messages_On_A_Channel.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Listening_To_Messages_On_A_Channel.cs @@ -39,7 +39,7 @@ public class ChannelMessageReceiveTests public ChannelMessageReceiveTests() { - IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, _fakeTimeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, _fakeTimeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new(ChannelName),new(_routingKey), gateway); diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_No_Acknowledge_Is_Called_On_A_Channel.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_No_Acknowledge_Is_Called_On_A_Channel.cs index 4633f43a45..11040f83bf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_No_Acknowledge_Is_Called_On_A_Channel.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_No_Acknowledge_Is_Called_On_A_Channel.cs @@ -38,7 +38,7 @@ public class ChannelNackTests public ChannelNackTests() { - IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + IAmAMessageConsumerSync gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new(ChannelName), _routingKey, gateway); diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Requeuing_A_Message_With_No_Delay.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Requeuing_A_Message_With_No_Delay.cs index 6bb2f16fea..dc343207ce 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Requeuing_A_Message_With_No_Delay.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_Requeuing_A_Message_With_No_Delay.cs @@ -37,14 +37,14 @@ public class ChannelRequeueWithoutDelayTest public ChannelRequeueWithoutDelayTest() { - var consumer = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new(ChannelName),new (_routingKey), consumer); var sentMessage = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("a test body")); - + _bus.Enqueue(sentMessage); } diff --git a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_The_Buffer_Is_Not_Empty_Read_From_That_Before_Receiving.cs b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_The_Buffer_Is_Not_Empty_Read_From_That_Before_Receiving.cs index 6215cc75e1..20305c47cf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_The_Buffer_Is_Not_Empty_Read_From_That_Before_Receiving.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessagingGateway/When_The_Buffer_Is_Not_Empty_Read_From_That_Before_Receiving.cs @@ -15,7 +15,7 @@ public class BufferedChannelTests public BufferedChannelTests() { - _gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus,new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000)); + _gateway = new InMemoryMessageConsumer(new RoutingKey(_routingKey), _bus,new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory); _channel = new Channel(new (Channel), new (_routingKey), _gateway, BufferLimit); } @@ -26,26 +26,26 @@ public void When_the_buffer_is_not_empty_read_from_that_before_receiving() var messageOne = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("FirstMessage")); - + var messageTwo = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("SecondMessage")); - + //put BufferLimit messages on the channel first _channel.Enqueue(messageOne, messageTwo); - + var messageThree = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("ThirdMessage")); - + //put a message on the bus, to pull once the buffer is empty _bus.Enqueue(messageThree); - + //act var msgOne = _channel.Receive(TimeSpan.FromMilliseconds(10)); var msgTwo = _channel.Receive(TimeSpan.FromMilliseconds(10)); var msgThree = _channel.Receive(TimeSpan.FromMilliseconds(10)); - + //assert Assert.Equal(messageOne.Id, msgOne.Id); Assert.Equal(messageTwo.Id, msgTwo.Id); @@ -59,21 +59,21 @@ public void When_the_buffer_is_replenished_allow_up_to_the_maximum_number_of_new var messageOne = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("FirstMessage")); - + var messageTwo = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("SecondMessage")); - + var messageThree = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody("ThirdMessage")); - + // This should be fine _channel.Enqueue(messageOne, messageTwo, messageThree); - + //This should throw an exception Assert.Throws(() => _channel.Enqueue(messageThree)); - + } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler.cs b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler.cs index 20f7d67536..fcdd01960e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler.cs +++ b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler.cs @@ -55,7 +55,7 @@ public MonitorHandlerPipelineTests() registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(_controlBusSender); @@ -65,7 +65,7 @@ public MonitorHandlerPipelineTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); _command = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler_Async.cs b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler_Async.cs index b3aa967c64..9c1109fd38 100644 --- a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_Is_On_For_A_Handler_Async.cs @@ -55,7 +55,7 @@ public MonitorHandlerPipelineAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(_controlBusSender); @@ -65,7 +65,7 @@ public MonitorHandlerPipelineAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); _command = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions.cs b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions.cs index 545e56ef62..8b70d7f2e8 100644 --- a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions.cs +++ b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions.cs @@ -52,7 +52,7 @@ public MonitorHandlerTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(_controlBusSender); @@ -62,7 +62,7 @@ public MonitorHandlerTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); _command = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions_Async.cs b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions_Async.cs index f129d8e7ab..756aa5c996 100644 --- a/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Monitoring/When_Monitoring_We_Should_Record_But_Rethrow_Exceptions_Async.cs @@ -56,7 +56,7 @@ public MonitorHandlerMustObserveButRethrowTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); container.AddSingleton(_controlBusSender); @@ -66,7 +66,7 @@ public MonitorHandlerMustObserveButRethrowTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); _command = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox.cs b/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox.cs index 4d1955a942..26a00dba19 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox.cs @@ -53,7 +53,7 @@ public ExternalServiceBusArchiveObservabilityTests() Type = type, }; - var producer = new InMemoryMessageProducer(internalBus, _publication); + var producer = new InMemoryMessageProducer(internalBus, Initializer.TestLoggerFactory, _publication); var producerRegistry = new ProducerRegistry(new Dictionary { { new ProducerKey(_routingKey, type), producer } }); @@ -73,7 +73,7 @@ public ExternalServiceBusArchiveObservabilityTests() new EmptyMessageTransformerFactoryAsync(), _tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + Initializer.TestLoggerFactory, _outbox, timeProvider:_timeProvider); } @@ -104,7 +104,7 @@ public void When_archiving_from_the_outbox(InstrumentationOptions instrumentatio var archiveProvider = new InMemoryArchiveProvider(); var archiver = new OutboxArchiver(_outbox, archiveProvider, tracer: _tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); archiver.Archive(dispatchedSince, context); //should be no messages in the outbox diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox_async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox_async.cs index 8e3eb282ac..b2c11df0a4 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/Archive/When_archiving_from_the_outbox_async.cs @@ -54,7 +54,7 @@ public AsyncExternalServiceBusArchiveObservabilityTests() Type = type, }; - var producer = new InMemoryMessageProducer(internalBus, _publication); + var producer = new InMemoryMessageProducer(internalBus, Initializer.TestLoggerFactory, _publication); var producerRegistry = new ProducerRegistry(new Dictionary { { new ProducerKey(_routingKey, type), producer } }); @@ -74,7 +74,7 @@ public AsyncExternalServiceBusArchiveObservabilityTests() new EmptyMessageTransformerFactoryAsync(), _tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + Initializer.TestLoggerFactory, _outbox, timeProvider:_timeProvider); } @@ -105,7 +105,7 @@ public async Task When_archiving_from_the_outbox(InstrumentationOptions instrume var archiveProvider = new InMemoryArchiveProvider(); var archiver = new OutboxArchiver(_outbox, archiveProvider, tracer: _tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); await archiver.ArchiveAsync(dispatchedSince, context); //should be no messages in the outbox diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported.cs index 6c06f11c4f..85cdd867af 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported.cs @@ -234,7 +234,7 @@ private Brighter.CommandProcessor CreateCommandProcessor(InstrumentationOptions var messageProducer = new InMemoryMessageProducer( _internalBus, - new Publication + Initializer.TestLoggerFactory, new Publication { Source = publicationSource, RequestType = typeof(MyEvent), Topic = _routingKey, Type = _publicationType, }, @@ -270,7 +270,7 @@ private Brighter.CommandProcessor CreateCommandProcessor(InstrumentationOptions new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1, instrumentationOptions: instrumentationOptions ); @@ -282,9 +282,9 @@ private Brighter.CommandProcessor CreateCommandProcessor(InstrumentationOptions policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions - ); + instrumentationOptions: instrumentationOptions, + loggerFactory: Initializer.TestLoggerFactory); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported_Async.cs index 2dc5504a16..7a30842919 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_A_Span_Is_Exported_Async.cs @@ -60,8 +60,8 @@ public AsyncCommandProcessorClearObservabilityTests() messageMapperRegistry.RegisterAsync(); var type = new CloudEventsType("io.goparamore.brighter.myevent"); - _messageProducer = new InMemoryMessageProducer(_internalBus, - new Publication + _messageProducer = new InMemoryMessageProducer(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -82,7 +82,7 @@ public AsyncCommandProcessorClearObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -93,10 +93,10 @@ public AsyncCommandProcessorClearObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context.cs index 1bebe8b107..d2f4ea633e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context.cs @@ -61,8 +61,8 @@ public MessageDispatchPropogateContextTests() messageMapperRegistry.Register(); var cloudEventsType = new CloudEventsType("io.goparamore.brighter.myevent"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -84,7 +84,7 @@ public MessageDispatchPropogateContextTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -95,10 +95,10 @@ public MessageDispatchPropogateContextTests() policyRegistry, new ResiliencePipelineRegistry(), _mediator, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context_Asyn.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context_Asyn.cs index 5ec264fe71..3a59badb12 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context_Asyn.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_A_Message_Should_Propogate_Context_Asyn.cs @@ -61,8 +61,8 @@ public AsyncMessageDispatchPropogateContextTests() messageMapperRegistry.RegisterAsync(); var type = new CloudEventsType("io.goparamore.brighter.myevent"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -84,7 +84,7 @@ public AsyncMessageDispatchPropogateContextTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -95,10 +95,10 @@ public AsyncMessageDispatchPropogateContextTests() policyRegistry, new ResiliencePipelineRegistry(), _mediator, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multipile_Messages_Spans_Are_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multipile_Messages_Spans_Are_Exported_Async.cs index c59a56345c..4a5a6051bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multipile_Messages_Spans_Are_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multipile_Messages_Spans_Are_Exported_Async.cs @@ -63,8 +63,8 @@ public AsyncCommandProcessorMultipleClearObservabilityTests() var routingKey = new RoutingKey(_topic); var type = new CloudEventsType("io.goparamore.brighter.myevent"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -86,7 +86,7 @@ public AsyncCommandProcessorMultipleClearObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -97,10 +97,10 @@ public AsyncCommandProcessorMultipleClearObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multiple_Messages_Spans_Are_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multiple_Messages_Spans_Are_Exported.cs index e40f603c48..4f9c017100 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multiple_Messages_Spans_Are_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Multiple_Messages_Spans_Are_Exported.cs @@ -18,7 +18,7 @@ namespace Paramore.Brighter.Core.Tests.Observability.CommandProcessor.Clear; [Collection("Observability")] -public class CommandProcessorMultipleClearObservabilityTests +public class CommandProcessorMultipleClearObservabilityTests { private readonly List _exportedActivities; private readonly TracerProvider _traceProvider; @@ -28,7 +28,7 @@ public class CommandProcessorMultipleClearObservabilityTests public CommandProcessorMultipleClearObservabilityTests() { var routingKey = new RoutingKey("MyEvent"); - + var builder = Sdk.CreateTracerProviderBuilder(); _exportedActivities = new List(); @@ -37,22 +37,22 @@ public CommandProcessorMultipleClearObservabilityTests() .ConfigureResource(r => r.AddService("in-memory-tracer")) .AddInMemoryExporter(_exportedActivities) .Build(); - - + + var registry = new SubscriberRegistry(); - var handlerFactory = new PostCommandTests.EmptyHandlerFactorySync(); - + var handlerFactory = new PostCommandTests.EmptyHandlerFactorySync(); + var retryPolicy = Policy .Handle() .Retry(); - + var policyRegistry = new PolicyRegistry {{Brighter.CommandProcessor.RETRYPOLICY, retryPolicy}}; var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); InMemoryOutbox outbox = new(timeProvider){Tracer = tracer}; - + var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory((_) => new MyEventMessageMapper()), null); @@ -60,8 +60,8 @@ public CommandProcessorMultipleClearObservabilityTests() var cloudEventsType = new CloudEventsType("io.goparamore.brighter.myevent"); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -74,65 +74,65 @@ public CommandProcessorMultipleClearObservabilityTests() { {new ProducerKey(routingKey, cloudEventsType), messageProducer} }); - + IAmAnOutboxProducerMediator bus = new OutboxProducerMediator( - producerRegistry, - new ResiliencePipelineRegistry().AddBrighterDefault(), - messageMapperRegistry, - new EmptyMessageTransformerFactory(), + producerRegistry, + new ResiliencePipelineRegistry().AddBrighterDefault(), + messageMapperRegistry, + new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); - + _commandProcessor = new Brighter.CommandProcessor( - registry, - handlerFactory, + registry, + handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, + policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), - tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + tracer: tracer, + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } - + [Fact] public void When_Clearing_A_Message_A_Span_Is_Exported() { //arrange var parentActivity = new ActivitySource("Paramore.Brighter.Tests").StartActivity("BrighterTracerSpanTests"); - + var eventOne = new MyEvent(); var eventTwo = new MyEvent(); var eventThree = new MyEvent(); - + var context = new RequestContext { Span = parentActivity }; //act var messageIds = _commandProcessor.DepositPost([eventOne, eventTwo, eventThree], context); - + //reset the parent span as deposit and clear are siblings - + context.Span = parentActivity; _commandProcessor.ClearOutbox(messageIds, context); - + parentActivity?.Stop(); - + _traceProvider.ForceFlush(); - + //assert //+1 confirmation (settle) span emitted per confirmed message (3 messages) (FR-2) Assert.Equal(22, _exportedActivities.Count); Assert.Contains(_exportedActivities, a => a.Source.Name == "Paramore.Brighter"); - + //there should be a create span for the batch var createActivity = _exportedActivities.Single(a => a.DisplayName == $"{BrighterSemanticConventions.ClearMessages} {CommandProcessorSpanOperation.Create.ToSpanName()}"); Assert.NotNull(createActivity); - + //there should be a clear span for each message id var clearActivity = _exportedActivities.Where(a => a.DisplayName == $"{BrighterSemanticConventions.ClearMessages} {CommandProcessorSpanOperation.Clear.ToSpanName()}"); Assert.Equal(3, clearActivity.Count()); diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported.cs index 21d3b9f989..2df2f8731c 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported.cs @@ -20,7 +20,7 @@ namespace Paramore.Brighter.Core.Tests.Observability.CommandProcessor.Clear; [Collection("Observability")] -public class CommandProcessorClearOutstandingObservabilityTests +public class CommandProcessorClearOutstandingObservabilityTests { private readonly List _exportedActivities; private readonly TracerProvider _traceProvider; @@ -32,7 +32,7 @@ public class CommandProcessorClearOutstandingObservabilityTests public CommandProcessorClearOutstandingObservabilityTests() { _topic = "MyEvent"; - + var builder = Sdk.CreateTracerProviderBuilder(); _exportedActivities = new List(); @@ -41,31 +41,31 @@ public CommandProcessorClearOutstandingObservabilityTests() .ConfigureResource(r => r.AddService("in-memory-tracer")) .AddInMemoryExporter(_exportedActivities) .Build(); - - + + var registry = new SubscriberRegistry(); - var handlerFactory = new PostCommandTests.EmptyHandlerFactorySync(); - + var handlerFactory = new PostCommandTests.EmptyHandlerFactorySync(); + var retryPolicy = Policy .Handle() .Retry(); - + var policyRegistry = new PolicyRegistry {{Brighter.CommandProcessor.RETRYPOLICY, retryPolicy}}; var timeProvider = new FakeTimeProvider(); var tracer = new BrighterTracer(timeProvider); InMemoryOutbox outbox = new(timeProvider){Tracer = tracer}; - + var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory((_) => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); var routingKey = new RoutingKey(_topic); - - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -77,39 +77,39 @@ public CommandProcessorClearOutstandingObservabilityTests() { {routingKey, messageProducer} }); - + _mediator = new OutboxProducerMediator( - producerRegistry, - new ResiliencePipelineRegistry().AddBrighterDefault(), - messageMapperRegistry, - new EmptyMessageTransformerFactory(), + producerRegistry, + new ResiliencePipelineRegistry().AddBrighterDefault(), + messageMapperRegistry, + new EmptyMessageTransformerFactory(), new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); - + _commandProcessor = new Brighter.CommandProcessor( - registry, - handlerFactory, + registry, + handlerFactory, new InMemoryRequestContextFactory(), - policyRegistry, + policyRegistry, new ResiliencePipelineRegistry(), _mediator, - new InMemorySchedulerFactory(), - tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + tracer: tracer, + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } - + [Fact(Skip = "This test is fragile due to background processing")] //[Fact] public async Task When_Clearing_Outstanding_Messages_Spans_Are_Exported() { //arrange var parentActivity = new ActivitySource("Paramore.Brighter.Tests").StartActivity("BrighterTracerSpanTests"); - + var eventOne = new MyEvent(); var eventTwo = new MyEvent(); var eventThree = new MyEvent(); @@ -118,36 +118,36 @@ public async Task When_Clearing_Outstanding_Messages_Spans_Are_Exported() //act _commandProcessor.DepositPost([eventOne, eventTwo, eventThree], context); - + //reset the parent span as deposit and clear are siblings - + context.Span = parentActivity; await _mediator.ClearOutstandingFromOutboxAsync(3, TimeSpan.Zero, false, context); await Task.Delay(3000); //allow bulk clear to run -- can make test fragile - + parentActivity?.Stop(); - + _traceProvider.ForceFlush(); - - //assert + + //assert //_exportedActivities.Count.Should().Be(18); Assert.Contains(_exportedActivities, a => a.Source.Name == "Paramore.Brighter"); - + //there should be a create span for the batch var createActivity = _exportedActivities.Single(a => a.DisplayName == $"{BrighterSemanticConventions.ClearMessages} {CommandProcessorSpanOperation.Create.ToSpanName()}"); Assert.NotNull(createActivity); - + //there should be a clear span for the batch of messages var clearActivity = _exportedActivities.Single(a => a.DisplayName == $"{BrighterSemanticConventions.ClearMessages} {CommandProcessorSpanOperation.Clear.ToSpanName()}"); - + //retrieving the messages should be an event var events = clearActivity.Events.ToList(); var messages = _internalBus.Stream(new RoutingKey(_topic)).ToArray(); - + var depositEvents = events.Where(e => e.Name == BoxDbOperation.OutStandingMessages.ToSpanName()).ToArray(); Assert.Equal(messages.Length, depositEvents.Length); - + foreach (var message in messages) { var depositEvent = depositEvents.Single(e => e.Tags.Any(a => a.Key == BrighterSemanticConventions.MessageId && (string)a.Value == message.Id)); @@ -175,8 +175,8 @@ public async Task When_Clearing_Outstanding_Messages_Spans_Are_Exported() //there should be a span for publishing the message via the producer var producerActivity = _exportedActivities .Single(a => a.DisplayName == $"{_topic} {CommandProcessorSpanOperation.Publish.ToSpanName()}"); - + var producerEvents = producerActivity.Events.ToArray(); - Assert.Equal(3, producerEvents.Length); + Assert.Equal(3, producerEvents.Length); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported_Bulk.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported_Bulk.cs index cc43cda55a..26e8277c02 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported_Bulk.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Clear/When_Clearing_Outstanding_Messages_Spans_Are_Exported_Bulk.cs @@ -63,8 +63,8 @@ public AsyncCommandProcessorBulkClearOutstandingObservabilityTests() messageMapperRegistry.RegisterAsync(); var routingKey = new RoutingKey(_topic); - InMemoryMessageProducer messageProducer = new(_internalBus, - new Publication + InMemoryMessageProducer messageProducer = new(_internalBus, + Initializer.TestLoggerFactory, new Publication { Source = new Uri("http://localhost"), RequestType = typeof(MyEvent), @@ -86,7 +86,7 @@ public AsyncCommandProcessorBulkClearOutstandingObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -97,10 +97,10 @@ public AsyncCommandProcessorBulkClearOutstandingObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), _mediator, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact(Skip = "This test is fragile due to background processing")] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported.cs index d9d2d51795..ed3606ee66 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported.cs @@ -64,7 +64,7 @@ public CommandProcessorDepositObservabilityTests() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) } }); @@ -76,7 +76,7 @@ public CommandProcessorDepositObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + Initializer.TestLoggerFactory, _outbox, maxOutStandingMessages: -1 ); @@ -87,10 +87,10 @@ public CommandProcessorDepositObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported_Async.cs index 05f18504a5..819bade73e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_A_Request_A_Span_Is_Exported_Async.cs @@ -66,7 +66,7 @@ public AsyncCommandProcessorDepositObservabilityTests() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) } }); @@ -78,7 +78,7 @@ public AsyncCommandProcessorDepositObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + Initializer.TestLoggerFactory, _outbox, maxOutStandingMessages: -1 ); @@ -89,10 +89,10 @@ public AsyncCommandProcessorDepositObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported.cs index 4d071bac44..716b524bd6 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported.cs @@ -63,7 +63,7 @@ public CommandProcessorMultipleDepositObservabilityTests() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) } }); @@ -75,7 +75,7 @@ public CommandProcessorMultipleDepositObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -86,10 +86,10 @@ public CommandProcessorMultipleDepositObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported_Async.cs index 7076c23539..751c2d10ac 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Deposit/When_Depositing_Multiple_Requests_Spans_Are_Exported_Async.cs @@ -64,7 +64,7 @@ public AsyncCommandProcessorMultipleDepositObservabilityTests() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) + routingKey, new InMemoryMessageProducer(new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyEvent)}) } }); @@ -76,7 +76,7 @@ public AsyncCommandProcessorMultipleDepositObservabilityTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox, + Initializer.TestLoggerFactory, outbox, maxOutStandingMessages: -1 ); @@ -87,10 +87,10 @@ public AsyncCommandProcessorMultipleDepositObservabilityTests() policyRegistry, new ResiliencePipelineRegistry(), bus, - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported.cs index 03bca93acb..46d5ede299 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported.cs @@ -66,10 +66,10 @@ public CommandProcessorPublishObservabilityTests() new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported_Asyn.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported_Asyn.cs index f4260079b3..4da69e7837 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported_Asyn.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Publish/When_Publishing_A_Request_A_Span_Is_Exported_Asyn.cs @@ -66,10 +66,10 @@ public AsyncCommandProcessorPublishObservabilityTests() new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported.cs index d6e6bc55ae..fdd8de105d 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported.cs @@ -64,10 +64,10 @@ public CommandProcessorSchedulerObservabilityTests() new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory{TimeProvider = _timeProvider}, + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory) {TimeProvider = _timeProvider}, tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported_Async.cs index 46ff28597e..b324771940 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Scheduler/When_Scheduling_A_Request_A_Span_Is_Exported_Async.cs @@ -72,10 +72,10 @@ public CommandProcessorSchedulerObservabilityAsyncTests() new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory{TimeProvider = _timeProvider}, + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory) {TimeProvider = _timeProvider}, tracer: tracer, - instrumentationOptions: InstrumentationOptions.All - ); + instrumentationOptions: InstrumentationOptions.All, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported.cs index d965fb7353..0f0414b643 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported.cs @@ -177,9 +177,9 @@ private IAmACommandProcessor CreateCommandProcessor(InstrumentationOptions instr new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions - ); + instrumentationOptions: instrumentationOptions, + loggerFactory: Initializer.TestLoggerFactory); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported_Async.cs b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported_Async.cs index adc496eafa..2cc2bd5a3a 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/CommandProcessor/Send/When_Sending_A_Request_A_Span_Is_Exported_Async.cs @@ -181,10 +181,10 @@ private Brighter.CommandProcessor CreateCommandProcessor(InstrumentationOptions new InMemoryRequestContextFactory(), policyRegistry, new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: options - ); + instrumentationOptions: options, + loggerFactory: Initializer.TestLoggerFactory); } } diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Has_A_Malformed_Correlation_Id_The_Pump_Continues.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Has_A_Malformed_Correlation_Id_The_Pump_Continues.cs index 38e92c08a3..6e5e2e8831 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Has_A_Malformed_Correlation_Id_The_Pump_Continues.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Has_A_Malformed_Correlation_Id_The_Pump_Continues.cs @@ -62,15 +62,15 @@ public MalformedCorrelationIdPumpObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -80,7 +80,7 @@ public MalformedCorrelationIdPumpObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs index 6f99b24ad6..52783a7583 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs @@ -81,15 +81,15 @@ public MessagePumpDispatchObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new(ChannelName),_routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -99,7 +99,7 @@ public MessagePumpDispatchObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_The_Header_Is_Serialized_Once.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_The_Header_Is_Serialized_Once.cs index 2245bfbc6c..ad6685b6f4 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_The_Header_Is_Serialized_Once.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_The_Header_Is_Serialized_Once.cs @@ -80,15 +80,15 @@ public MessageHeaderSerializationObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -98,7 +98,7 @@ public MessageHeaderSerializationObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Processed_It_Should_Have_A_Process_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Processed_It_Should_Have_A_Process_Span.cs index 59136a1885..f0a813f6a5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Processed_It_Should_Have_A_Process_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Processed_It_Should_Have_A_Process_Span.cs @@ -83,15 +83,15 @@ public MessagePumpProcessSpanObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), @@ -99,7 +99,7 @@ public MessagePumpProcessSpanObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, _ => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_With_A_Correlation_Id_Is_Dispatched_Both_Spans_Share_One_Header.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_With_A_Correlation_Id_Is_Dispatched_Both_Spans_Share_One_Header.cs index 121a20e24f..1d9fc2197b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_With_A_Correlation_Id_Is_Dispatched_Both_Spans_Share_One_Header.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_With_A_Correlation_Id_Is_Dispatched_Both_Spans_Share_One_Header.cs @@ -80,15 +80,15 @@ public MessageHeaderCorrelationIdObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var channel = new Channel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( @@ -98,7 +98,7 @@ public MessageHeaderCorrelationIdObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Proactor_Loop_Throws_Close_The_Pump_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Proactor_Loop_Throws_Close_The_Pump_Span.cs index ab43dbdd8d..1cddb0fbc3 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Proactor_Loop_Throws_Close_The_Pump_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Proactor_Loop_Throws_Close_The_Pump_Span.cs @@ -73,9 +73,9 @@ public ProactorLoopThrowsPumpSpanObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); @@ -83,7 +83,7 @@ public ProactorLoopThrowsPumpSpanObservabilityTests() //which throws out of the receive loop (Proactor.cs:190) var channel = new NullReturningChannelAsync( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( null, @@ -91,7 +91,7 @@ public ProactorLoopThrowsPumpSpanObservabilityTests() messageMapperRegistry.RegisterAsync(); _messagePump = new Proactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Reactor_Loop_Throws_Close_The_Pump_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Reactor_Loop_Throws_Close_The_Pump_Span.cs index decde8341b..7176965bb0 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Reactor_Loop_Throws_Close_The_Pump_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_The_Reactor_Loop_Throws_Close_The_Pump_Span.cs @@ -74,9 +74,9 @@ public ReactorLoopThrowsPumpSpanObservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); @@ -84,7 +84,7 @@ public ReactorLoopThrowsPumpSpanObservabilityTests() //which throws out of the receive loop (Reactor.cs:149) var channel = new NullReturningChannel( new(ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( @@ -93,7 +93,7 @@ public ReactorLoopThrowsPumpSpanObservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs index 67c3ffa991..f79e6ec477 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs @@ -54,13 +54,13 @@ public MessagePumpEmptyQueueOberservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); - Channel channel = new(new(ChannelName),_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + Channel channel = new(new(ChannelName),_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( _ => new MyEventMessageMapper()), @@ -68,7 +68,7 @@ public MessagePumpEmptyQueueOberservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs index 388cdd1d35..43ae37eb2b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs @@ -58,16 +58,16 @@ public MessagePumpBrokenCircuitChannelFailureOberservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); FailingChannel channel = new( new (ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), brokenCircuit: true); var messageMapperRegistry = new MessageMapperRegistry( @@ -77,7 +77,7 @@ public MessagePumpBrokenCircuitChannelFailureOberservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs index b545a21c2e..c743a96e78 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs @@ -58,16 +58,16 @@ public MessagePumpChannelFailureOberservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); FailingChannel channel = new( new (ChannelName), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)), + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory), brokenCircuit: false); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( @@ -77,7 +77,7 @@ public MessagePumpChannelFailureOberservabilityTests() _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactory(), - new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) + new InMemoryRequestContextFactory(), channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs index 8ae12f1bd4..6a797f4c86 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs @@ -53,15 +53,15 @@ public MessagePumpQuitOberservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); Channel channel = new( new (Channel), _routingKey, - new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)) + new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory) ); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( @@ -71,7 +71,7 @@ public MessagePumpQuitOberservabilityTests() _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), - channel, tracer, instrumentationOptions) + channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = channel, TimeOut= TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs index c43cec0dd6..57bf0644f1 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs @@ -55,13 +55,13 @@ public MessagePumpUnacceptableMessageOberservabilityTests() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory(), + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), tracer: tracer, - instrumentationOptions: instrumentationOptions); + instrumentationOptions: instrumentationOptions, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); - _channel = new Channel(new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + _channel = new Channel(new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory( _ => new MyEventMessageMapper()), @@ -69,7 +69,7 @@ public MessagePumpUnacceptableMessageOberservabilityTests() messageMapperRegistry.Register(); _messagePump = new Reactor(commandProcessor, (message) => typeof(MyEvent), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, tracer, instrumentationOptions) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, Initializer.TestLoggerFactory, tracer, instrumentationOptions) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled.cs index c610c0d686..d57e29dd91 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled.cs @@ -24,7 +24,7 @@ public OnceOnlyAttributeTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -35,7 +35,7 @@ public OnceOnlyAttributeTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled_Async.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled_Async.cs index 0781484897..721410e2f1 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Inbox_Enabled_Async.cs @@ -26,7 +26,7 @@ public OnceOnlyAttributeAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -38,7 +38,7 @@ public OnceOnlyAttributeAsyncTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled.cs index 5dab5c465c..f5bc730bc8 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled.cs @@ -48,7 +48,7 @@ public OnceOnlyAttributeWithThrowExceptionTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -59,7 +59,7 @@ public OnceOnlyAttributeWithThrowExceptionTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled_Async.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled_Async.cs index c4c2e2d77b..3b5cf90954 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Throw_Enabled_Async.cs @@ -49,7 +49,7 @@ public OnceOnlyAttributeWithThrowExceptionAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient>(); container.AddTransient(); container.AddSingleton(_inbox); @@ -60,7 +60,7 @@ public OnceOnlyAttributeWithThrowExceptionAsyncTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled.cs index fabb69a042..1b9081898c 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled.cs @@ -47,7 +47,7 @@ public OnceOnlyAttributeWithWarnExceptionTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -58,7 +58,7 @@ public OnceOnlyAttributeWithWarnExceptionTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled_Async.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled_Async.cs index c1dedfe6a7..00566e5afa 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_Once_Only_With_Warn_Enabled_Async.cs @@ -47,7 +47,7 @@ public OnceOnlyAttributeWithWarnExceptionAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddTransient>(); @@ -58,7 +58,7 @@ public OnceOnlyAttributeWithWarnExceptionAsyncTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled.cs index b3b7d60b8f..951eca18a4 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled.cs @@ -49,7 +49,7 @@ public CommandProcessorUsingInboxTests() registry.Register(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_inbox); @@ -63,7 +63,7 @@ public CommandProcessorUsingInboxTests() _contextKey = typeof(MyStoredCommandHandler).FullName; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled_Async.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled_Async.cs index b016d86f0a..b23fc0f5d8 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_Handling_A_Command_With_A_Inbox_Enabled_Async.cs @@ -26,7 +26,7 @@ public CommandProcessorUsingInboxAsyncTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient(); container.AddSingleton(_inbox); @@ -40,7 +40,7 @@ public CommandProcessorUsingInboxAsyncTests() _command = new MyCommand {Value = "My Test String"}; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_a_seen_message_is_replayed_end_to_end.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_a_seen_message_is_replayed_end_to_end.cs index 843ae38420..ea56aba1c9 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_a_seen_message_is_replayed_end_to_end.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_a_seen_message_is_replayed_end_to_end.cs @@ -102,9 +102,9 @@ public EndToEndReplayOnSeenTests() var producerRegistry = new ProducerRegistry(new Dictionary { { _inboundRoutingKey, new InMemoryMessageProducer(_internalBus, - new Publication { Topic = _inboundRoutingKey, RequestType = typeof(MyCommand) }) }, + Initializer.TestLoggerFactory, new Publication { Topic = _inboundRoutingKey, RequestType = typeof(MyCommand) }) }, { _outgoingRoutingKey, new InMemoryMessageProducer(_internalBus, - new Publication { Topic = _outgoingRoutingKey, RequestType = typeof(MyEvent) }) } + Initializer.TestLoggerFactory, new Publication { Topic = _outgoingRoutingKey, RequestType = typeof(MyEvent) }) } }); IAmAnOutboxProducerMediator mediator = new OutboxProducerMediator( @@ -115,14 +115,14 @@ public EndToEndReplayOnSeenTests() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox); + Initializer.TestLoggerFactory, _outbox); //The handler needs the command processor (to forward) and the signal channel; the command processor needs the //handler factory. Break the cycle by resolving the processor lazily from the container the factory wraps. var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(handledChannel.Writer); container.AddSingleton(_inbox); @@ -136,7 +136,7 @@ public EndToEndReplayOnSeenTests() new DefaultPolicy(), resiliencePipelineRegistry, mediator, - new InMemorySchedulerFactory())); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory)); _commandProcessor = container.BuildServiceProvider().GetRequiredService(); @@ -144,10 +144,10 @@ public EndToEndReplayOnSeenTests() var channel = new Channel( new ChannelName("MyChannel"), _inboundRoutingKey, - new InMemoryMessageConsumer(_inboundRoutingKey, _internalBus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000))); + new InMemoryMessageConsumer(_inboundRoutingKey, _internalBus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: Initializer.TestLoggerFactory)); var pump = new Reactor(_commandProcessor, _ => typeof(MyCommand), - messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel, loggerFactory: Initializer.TestLoggerFactory) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(200), EmptyChannelDelay = TimeSpan.FromMilliseconds(10) }; _performer = new Performer(channel, pump); diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_async_with_replay_and_no_outbox_should_return_without_error.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_async_with_replay_and_no_outbox_should_return_without_error.cs index 7f810248fb..a558fa4078 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_async_with_replay_and_no_outbox_should_return_without_error.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_async_with_replay_and_no_outbox_should_return_without_error.cs @@ -58,7 +58,7 @@ public UseInboxHandlerAsyncReplayWithNoOutboxTests() registry.RegisterAsync(); //Arrange — NO outbox is registered, so UseInboxHandlerAsync receives null for its optional outbox - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddTransient>(); @@ -67,7 +67,7 @@ public UseInboxHandlerAsyncReplayWithNoOutboxTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_async_with_replay_should_clear_outbox_dispatch.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_async_with_replay_should_clear_outbox_dispatch.cs index 5aa2d265da..1b4f55a21a 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_async_with_replay_should_clear_outbox_dispatch.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_async_with_replay_should_clear_outbox_dispatch.cs @@ -78,7 +78,7 @@ public UseInboxHandlerAsyncReplayTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddSingleton(_outbox); @@ -89,7 +89,7 @@ public UseInboxHandlerAsyncReplayTests() _context = new RequestContext(); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_with_replay_should_clear_outbox_dispatch.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_with_replay_should_clear_outbox_dispatch.cs index 2303d472c0..e67ee7aa2c 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_with_replay_should_clear_outbox_dispatch.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_command_with_replay_should_clear_outbox_dispatch.cs @@ -77,7 +77,7 @@ public UseInboxHandlerReplayTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddSingleton(_outbox); @@ -88,7 +88,7 @@ public UseInboxHandlerReplayTests() _context = new RequestContext(); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_with_replay_and_no_outbox_should_return_without_error.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_with_replay_and_no_outbox_should_return_without_error.cs index 8832cda1f3..ec36af112b 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_with_replay_and_no_outbox_should_return_without_error.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_duplicate_with_replay_and_no_outbox_should_return_without_error.cs @@ -57,7 +57,7 @@ public UseInboxHandlerReplayWithNoOutboxTests() registry.Register(); //Arrange — NO outbox is registered, so UseInboxHandler receives null for its optional outbox - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(inbox); container.AddTransient>(); @@ -66,7 +66,7 @@ public UseInboxHandlerReplayWithNoOutboxTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_async_should_set_causation_id_in_context_bag.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_async_should_set_causation_id_in_context_bag.cs index 5c225fbebd..66a149c243 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_async_should_set_causation_id_in_context_bag.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_async_should_set_causation_id_in_context_bag.cs @@ -48,7 +48,7 @@ public UseInboxHandlerAsyncCausationTrackingTests() var registry = new SubscriberRegistry(); registry.RegisterAsync(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -60,7 +60,7 @@ public UseInboxHandlerAsyncCausationTrackingTests() _contextKey = typeof(MyStoredCommandHandlerAsync).FullName!; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_should_set_causation_id_in_context_bag.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_should_set_causation_id_in_context_bag.cs index 3c3f9b57c2..967f51b6ae 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_should_set_causation_id_in_context_bag.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_handling_new_command_should_set_causation_id_in_context_bag.cs @@ -47,7 +47,7 @@ public UseInboxHandlerCausationTrackingTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddSingleton(_inbox); container.AddTransient>(); @@ -59,7 +59,7 @@ public UseInboxHandlerCausationTrackingTests() _contextKey = typeof(MyStoredCommandHandler).FullName!; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(), new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_inbox_handler_handles_command_should_add_telemetry_events.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_inbox_handler_handles_command_should_add_telemetry_events.cs index 25b9b88fcd..7fadcd6de2 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_inbox_handler_handles_command_should_add_telemetry_events.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_inbox_handler_handles_command_should_add_telemetry_events.cs @@ -63,7 +63,7 @@ public void When_inbox_handler_handles_command_should_add_telemetry_events() { //Arrange — first time the command is seen, so it is added to the inbox using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox); + var handler = new UseInboxHandler(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); handler.Context = new RequestContext { Span = span }; @@ -82,7 +82,7 @@ public async Task When_inbox_handler_handles_command_async_should_add_add_teleme { //Arrange — first time the command is seen using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandlerAsync(_inbox); + var handler = new UseInboxHandlerAsync(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); handler.Context = new RequestContext { Span = span }; @@ -100,7 +100,7 @@ public void When_duplicate_with_throw_should_add_throw_telemetry_event() //Arrange — the command has already been seen and the action is Throw SeedAsAlreadySeen(); using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox); + var handler = new UseInboxHandler(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); handler.Context = new RequestContext { Span = span }; @@ -120,7 +120,7 @@ public async Task When_duplicate_with_throw_async_should_add_throw_telemetry_eve //Arrange SeedAsAlreadySeen(); using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandlerAsync(_inbox); + var handler = new UseInboxHandlerAsync(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); handler.Context = new RequestContext { Span = span }; @@ -138,7 +138,7 @@ public void When_duplicate_with_warn_should_add_warn_telemetry_event() //Arrange — the command has already been seen and the action is Warn SeedAsAlreadySeen(); using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox); + var handler = new UseInboxHandler(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Warn); handler.Context = new RequestContext { Span = span }; @@ -158,7 +158,7 @@ public async Task When_duplicate_with_warn_async_should_add_warn_telemetry_event //Arrange SeedAsAlreadySeen(); using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandlerAsync(_inbox); + var handler = new UseInboxHandlerAsync(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Warn); handler.Context = new RequestContext { Span = span }; @@ -175,7 +175,7 @@ public void When_handling_command_without_brighter_instrumentation_should_not_ad { //Arrange — a context whose instrumentation does not include the Brighter flag using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox); + var handler = new UseInboxHandler(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); handler.Context = new RequestContext { @@ -193,7 +193,7 @@ public void When_handling_command_without_brighter_instrumentation_should_not_ad public void When_handling_command_with_no_span_should_not_throw_and_still_add() { //Arrange — no span on the context - var handler = new UseInboxHandler(_inbox); + var handler = new UseInboxHandler(_inbox, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Throw); var context = new RequestContext(); handler.Context = context; diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_registering_outbox_with_causation_tracking_should_register_role_interface.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_registering_outbox_with_causation_tracking_should_register_role_interface.cs index 44e0ee5018..43d9f52aea 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_registering_outbox_with_causation_tracking_should_register_role_interface.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_registering_outbox_with_causation_tracking_should_register_role_interface.cs @@ -46,7 +46,7 @@ private static IBrighterBuilder BrighterBuilder(IServiceCollection services) public void When_registering_outbox_with_causation_tracking_should_register_role_interface() { // Arrange — the default outbox (InMemoryOutbox) supports causation tracking - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); BrighterBuilder(services).AddProducers(config => { }); var provider = services.BuildServiceProvider(); @@ -61,7 +61,7 @@ public void When_registering_outbox_with_causation_tracking_should_register_role public void When_registering_outbox_with_causation_tracking_should_resolve_same_instance() { // Arrange — the default outbox (InMemoryOutbox) supports causation tracking - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); BrighterBuilder(services).AddProducers(config => { }); var provider = services.BuildServiceProvider(); @@ -77,7 +77,7 @@ public void When_registering_outbox_with_causation_tracking_should_resolve_same_ public void When_registering_outbox_without_causation_tracking_should_not_register_role_interface() { // Arrange — SpyOutbox does NOT implement IAmACausationTrackingOutbox - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); BrighterBuilder(services).AddProducers(config => { config.Outbox = new SpyOutbox { Tracer = new BrighterTracer(TimeProvider.System) }; diff --git a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_replaying_duplicate_should_add_replay_telemetry_event_to_span.cs b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_replaying_duplicate_should_add_replay_telemetry_event_to_span.cs index 374916fcef..d8fcce66a9 100644 --- a/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_replaying_duplicate_should_add_replay_telemetry_event_to_span.cs +++ b/tests/Paramore.Brighter.Core.Tests/OnceOnly/When_replaying_duplicate_should_add_replay_telemetry_event_to_span.cs @@ -74,7 +74,7 @@ public void When_replaying_duplicate_should_add_replay_telemetry_event_to_span() { //Arrange using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox, _outbox); + var handler = new UseInboxHandler(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), _outbox); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { Span = span }; @@ -96,7 +96,7 @@ public async Task When_replaying_duplicate_async_should_add_replay_telemetry_eve { //Arrange using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandlerAsync(_inbox, _outbox); + var handler = new UseInboxHandlerAsync(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), _outbox); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { Span = span }; @@ -123,7 +123,7 @@ public void When_replaying_duplicate_with_no_causation_id_should_add_distinct_sk inbox.Add(command, ContextKey, new RequestContext()); using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(inbox, outbox); + var handler = new UseInboxHandler(inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), outbox); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { Span = span }; @@ -146,7 +146,7 @@ public void When_replaying_duplicate_but_outbox_could_not_replay_should_add_dist //Arrange — a seen command WITH a causation id, but the outbox cannot replay it because its live //schema does not support causation tracking (the "inbox migrated, outbox not" mixed state). using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox, new MixedMigrationOutbox()); + var handler = new UseInboxHandler(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), new MixedMigrationOutbox()); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { Span = span }; @@ -168,7 +168,7 @@ public async Task When_replaying_duplicate_async_but_outbox_could_not_replay_sho { //Arrange — a seen command WITH a causation id, but the outbox cannot replay it (mixed-migration state) using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandlerAsync(_inbox, new MixedMigrationOutbox()); + var handler = new UseInboxHandlerAsync(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), new MixedMigrationOutbox()); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { Span = span }; @@ -190,7 +190,7 @@ public void When_replaying_duplicate_without_brighter_instrumentation_should_not { //Arrange — a context whose instrumentation does not include the Brighter flag using var span = new Activity("pipeline").Start(); - var handler = new UseInboxHandler(_inbox, _outbox); + var handler = new UseInboxHandler(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), _outbox); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); handler.Context = new RequestContext { @@ -208,7 +208,7 @@ public void When_replaying_duplicate_without_brighter_instrumentation_should_not public void When_replaying_duplicate_with_no_span_should_not_throw_and_still_replay() { //Arrange — no span on the context - var handler = new UseInboxHandler(_inbox, _outbox); + var handler = new UseInboxHandler(_inbox, global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory), _outbox); handler.InitializeFromAttributeParams(true, ContextKey, OnceOnlyAction.Replay); var context = new RequestContext(); handler.Context = context; diff --git a/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_succeeds_should_not_reject_message.cs b/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_succeeds_should_not_reject_message.cs index 56d3e9ba3b..a435f03b41 100644 --- a/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_succeeds_should_not_reject_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_succeeds_should_not_reject_message.cs @@ -48,7 +48,7 @@ public When_async_handler_succeeds_should_not_reject_message() if (type == typeof(MySucceedingRejectHandlerAsync)) return new MySucceedingRejectHandlerAsync(); if (type == typeof(RejectMessageOnErrorHandlerAsync)) - return new RejectMessageOnErrorHandlerAsync(); + return new RejectMessageOnErrorHandlerAsync(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -60,8 +60,8 @@ public When_async_handler_succeeds_should_not_reject_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_throws_exception_should_reject_message.cs b/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_throws_exception_should_reject_message.cs index 2a23497405..974bb6c9c5 100644 --- a/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_throws_exception_should_reject_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Reject/When_async_handler_throws_exception_should_reject_message.cs @@ -49,7 +49,7 @@ public When_async_handler_throws_exception_should_reject_message() if (type == typeof(MyFailingRejectHandlerAsync)) return new MyFailingRejectHandlerAsync(); if (type == typeof(RejectMessageOnErrorHandlerAsync)) - return new RejectMessageOnErrorHandlerAsync(); + return new RejectMessageOnErrorHandlerAsync(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -61,8 +61,8 @@ public When_async_handler_throws_exception_should_reject_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_succeeds_should_not_reject_message.cs b/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_succeeds_should_not_reject_message.cs index b464ba84fe..ceccff6a08 100644 --- a/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_succeeds_should_not_reject_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_succeeds_should_not_reject_message.cs @@ -47,7 +47,7 @@ public When_handler_succeeds_should_not_reject_message() if (type == typeof(MySucceedingRejectHandler)) return new MySucceedingRejectHandler(); if (type == typeof(RejectMessageOnErrorHandler)) - return new RejectMessageOnErrorHandler(); + return new RejectMessageOnErrorHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -59,8 +59,8 @@ public When_handler_succeeds_should_not_reject_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_throws_exception_should_reject_message.cs b/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_throws_exception_should_reject_message.cs index cc2a7966b5..84685a07fb 100644 --- a/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_throws_exception_should_reject_message.cs +++ b/tests/Paramore.Brighter.Core.Tests/Reject/When_handler_throws_exception_should_reject_message.cs @@ -48,7 +48,7 @@ public When_handler_throws_exception_should_reject_message() if (type == typeof(MyFailingRejectHandler)) return new MyFailingRejectHandler(); if (type == typeof(RejectMessageOnErrorHandler)) - return new RejectMessageOnErrorHandler(); + return new RejectMessageOnErrorHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -60,8 +60,8 @@ public When_handler_throws_exception_should_reject_message() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Reject/When_reject_handler_at_step_zero_catches_inner_exceptions.cs b/tests/Paramore.Brighter.Core.Tests/Reject/When_reject_handler_at_step_zero_catches_inner_exceptions.cs index f3b76bcc16..f8fcd8508c 100644 --- a/tests/Paramore.Brighter.Core.Tests/Reject/When_reject_handler_at_step_zero_catches_inner_exceptions.cs +++ b/tests/Paramore.Brighter.Core.Tests/Reject/When_reject_handler_at_step_zero_catches_inner_exceptions.cs @@ -53,9 +53,9 @@ public When_reject_handler_at_step_zero_catches_inner_exceptions() if (type == typeof(MyMultiStepFailingHandler)) return new MyMultiStepFailingHandler(); if (type == typeof(RejectMessageOnErrorHandler)) - return new RejectMessageOnErrorHandler(); + return new RejectMessageOnErrorHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); if (type == typeof(RequestLoggingHandler)) - return new RequestLoggingHandler(); + return new RequestLoggingHandler(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger>(Initializer.TestLoggerFactory)); throw new ArgumentOutOfRangeException(nameof(type), type.Name, null); }); @@ -67,8 +67,8 @@ public When_reject_handler_at_step_zero_catches_inner_exceptions() new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory() - ); + new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_failing_a_timeout_policy_check.cs b/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_failing_a_timeout_policy_check.cs index 4758cbdd67..5bf24bb6aa 100644 --- a/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_failing_a_timeout_policy_check.cs +++ b/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_failing_a_timeout_policy_check.cs @@ -46,14 +46,14 @@ public TimeoutHandlerFailsCheckTests() var registry = new SubscriberRegistry(); registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_passing_a_timeout_policy_check.cs b/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_passing_a_timeout_policy_check.cs index a463672302..ec9d955caf 100644 --- a/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_passing_a_timeout_policy_check.cs +++ b/tests/Paramore.Brighter.Core.Tests/Timeout/When_sending_a_command_to_the_processor_passing_a_timeout_policy_check.cs @@ -44,14 +44,14 @@ public MyPassesTimeoutHandlerTests() //Handler is decorated with UsePolicy registry.Register(); - var container = new ServiceCollection(); + var container = new ServiceCollection().AddLogging(); container.AddTransient(); container.AddTransient>(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); } //We have to catch the final exception that bubbles out after retry diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_both_validate_and_describe_registered_should_describe_once.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_both_validate_and_describe_registered_should_describe_once.cs index 43b52b885b..06dc661d3f 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_both_validate_and_describe_registered_should_describe_once.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_both_validate_and_describe_registered_should_describe_once.cs @@ -44,7 +44,7 @@ public async Task When_both_validate_and_describe_registered_should_describe_onc var validator = SpyPipelineValidator.WithNoErrors(); var options = Options.Create(new BrighterPipelineValidationOptions { ConsumerOwnsValidation = false }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_brighter_and_producers_configured_should_run_handler_and_producer_checks.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_brighter_and_producers_configured_should_run_handler_and_producer_checks.cs index be54865db5..a5bdbd0ddf 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_brighter_and_producers_configured_should_run_handler_and_producer_checks.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_brighter_and_producers_configured_should_run_handler_and_producer_checks.cs @@ -37,7 +37,7 @@ public void When_brighter_and_producers_configured_should_run_handler_and_produc // Arrange — handler path: internal handler triggers visibility error var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyInternalHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Producer path: null RequestType triggers producer error diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_should_register_diagnostic_writer_in_di.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_should_register_diagnostic_writer_in_di.cs index 45ba0bf3ec..ea0af1b36e 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_should_register_diagnostic_writer_in_di.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_should_register_diagnostic_writer_in_di.cs @@ -35,7 +35,7 @@ public class DescribePipelinesRegistrationTests public void When_describe_pipelines_called_should_register_diagnostic_writer_in_di() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_standalone_should_run_at_startup.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_standalone_should_run_at_startup.cs index 5d98f98332..b91e80c8ef 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_standalone_should_run_at_startup.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_called_standalone_should_run_at_startup.cs @@ -42,7 +42,7 @@ public class DescribePipelinesStandaloneTests public void When_describe_pipelines_called_should_register_diagnostic_hosted_service() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); @@ -60,7 +60,7 @@ public void When_describe_pipelines_called_should_register_diagnostic_hosted_ser public async Task When_describe_pipelines_standalone_should_produce_log_output_at_startup() { // Arrange — DescribePipelines without ValidatePipelines, real diagnostic writer with captured logs - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); subscriberRegistry.Register(); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_with_producers_should_log_publications.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_with_producers_should_log_publications.cs index ed89cb0f4f..b952788ff6 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_with_producers_should_log_publications.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_describe_pipelines_with_producers_should_log_publications.cs @@ -41,11 +41,11 @@ public void When_describe_pipelines_with_producers_should_log_publication_summar var routingKey = new RoutingKey("greeting.created"); var producer = new InMemoryMessageProducer( new InternalBus(), - new Publication { Topic = routingKey, RequestType = typeof(MyDescribableEvent) }); + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyDescribableEvent) }); var producerRegistry = new ProducerRegistry( new Dictionary { { routingKey, producer } }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); services.AddSingleton(producerRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_handler_pipeline_detail_at_debug.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_handler_pipeline_detail_at_debug.cs index ef146c9144..f335adc1c0 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_handler_pipeline_detail_at_debug.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_handler_pipeline_detail_at_debug.cs @@ -38,7 +38,7 @@ public void When_diagnostic_writer_describes_should_log_handler_pipeline_detail_ // Arrange — handler with two before-step attributes (backstop at 5, resilience at 3) var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyMisorderedBackstopHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var logger = new SpyLogger(); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_publication_detail_at_debug.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_publication_detail_at_debug.cs index dde73bec8c..614a833105 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_publication_detail_at_debug.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_publication_detail_at_debug.cs @@ -38,7 +38,7 @@ public void When_diagnostic_writer_describes_should_log_publication_detail_at_de // Arrange — one publication with a custom mapper that has a wrap transform var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyPublicSyncHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var mapperRegistry = new MessageMapperRegistry( diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_subscription_detail_at_debug.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_subscription_detail_at_debug.cs index 77a3105641..e3de127d39 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_subscription_detail_at_debug.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_subscription_detail_at_debug.cs @@ -38,7 +38,7 @@ public void When_diagnostic_writer_describes_should_log_subscription_detail_at_d // Arrange — one subscription with known channel, routing key, and pump type var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyPublicSyncHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var subscriptions = new[] diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_summary_at_information.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_summary_at_information.cs index eae4311806..d4f8257cd3 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_summary_at_information.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_describes_should_log_summary_at_information.cs @@ -39,7 +39,7 @@ public void When_diagnostic_writer_describes_should_log_summary_at_information() var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyPublicSyncHandler)); registry.Add(typeof(MyDescribableCommand), typeof(MyPublicAsyncHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var publications = new[] diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_has_no_items_should_produce_no_output.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_has_no_items_should_produce_no_output.cs index ebe4ea00ef..accafe3eb7 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_has_no_items_should_produce_no_output.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_diagnostic_writer_has_no_items_should_produce_no_output.cs @@ -35,7 +35,7 @@ public void When_diagnostic_writer_has_no_items_should_produce_no_output() { // Arrange — empty registry, no publications, no subscriptions var registry = new SubscriberRegistry(); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var logger = new SpyLogger(); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_disposing_validation_components_they_dispose_the_registry.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_disposing_validation_components_they_dispose_the_registry.cs index ff7c232e96..3e7a569cd9 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_disposing_validation_components_they_dispose_the_registry.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_disposing_validation_components_they_dispose_the_registry.cs @@ -21,7 +21,7 @@ public void When_disposing_the_validator_it_disposes_the_mapper_registry() var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); var subscriberRegistry = new SubscriberRegistry(); - var pipelineBuilder = new PipelineBuilder(subscriberRegistry); + var pipelineBuilder = new PipelineBuilder(subscriberRegistry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var validator = new PipelineValidator( @@ -54,7 +54,7 @@ public void When_disposing_the_diagnostic_writer_it_disposes_the_mapper_registry var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); var subscriberRegistry = new SubscriberRegistry(); - var pipelineBuilder = new PipelineBuilder(subscriberRegistry); + var pipelineBuilder = new PipelineBuilder(subscriberRegistry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var writer = new PipelineDiagnosticWriter( diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_only_brighter_configured_should_run_only_handler_checks.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_only_brighter_configured_should_run_only_handler_checks.cs index 20dd99545c..22d308f917 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_only_brighter_configured_should_run_only_handler_checks.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_only_brighter_configured_should_run_only_handler_checks.cs @@ -38,7 +38,7 @@ public void When_only_brighter_configured_should_run_only_handler_checks() // no publications or subscriptions provided var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyInternalHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var validator = new PipelineValidator(pipelineBuilder); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_pipeline_builder_describes_handler_should_return_pipeline_description.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_pipeline_builder_describes_handler_should_return_pipeline_description.cs index c8e6992106..112534df30 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_pipeline_builder_describes_handler_should_return_pipeline_description.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_pipeline_builder_describes_handler_should_return_pipeline_description.cs @@ -39,7 +39,7 @@ public void When_describing_sync_handler_should_return_description_with_request_ var registry = new SubscriberRegistry(); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act @@ -60,7 +60,7 @@ public void When_describing_sync_handler_should_list_before_steps_in_step_order( var registry = new SubscriberRegistry(); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act @@ -82,7 +82,7 @@ public void When_describing_sync_handler_should_list_after_steps() var registry = new SubscriberRegistry(); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act @@ -104,7 +104,7 @@ public void When_describing_async_handler_should_set_IsAsync_true() var registry = new SubscriberRegistry(); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandlerAsync)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act @@ -123,7 +123,7 @@ public void When_multiple_handlers_registered_should_produce_multiple_descriptio registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandler)); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandlerAsync)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act @@ -142,7 +142,7 @@ public void When_parameterless_describe_should_iterate_all_registered_request_ty var registry = new SubscriberRegistry(); registry.Add(typeof(MyCommand), typeof(MyPreAndPostDecoratedHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Act — parameterless Describe() should find all registered request types diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_publication_wrap_transform_unresolvable_through_di_should_surface_warning.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_publication_wrap_transform_unresolvable_through_di_should_surface_warning.cs index 7a9dbeedc0..8c7a1f3f10 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_publication_wrap_transform_unresolvable_through_di_should_surface_warning.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_publication_wrap_transform_unresolvable_through_di_should_surface_warning.cs @@ -43,11 +43,11 @@ public void When_publication_wrap_transform_unresolvable_through_di_should_surfa var routingKey = new RoutingKey("greeting"); var producer = new InMemoryMessageProducer( new InternalBus(), - new Publication { Topic = routingKey, RequestType = typeof(MyDescribableCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyDescribableCommand) }); var producerRegistry = new ProducerRegistry( new Dictionary { { routingKey, producer } }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); services.AddSingleton(producerRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_scanning_assemblies_should_exclude_open_generic_handlers.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_scanning_assemblies_should_exclude_open_generic_handlers.cs index 940a28e3f3..1b7d711456 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_scanning_assemblies_should_exclude_open_generic_handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_scanning_assemblies_should_exclude_open_generic_handlers.cs @@ -37,7 +37,7 @@ public class AssemblyScanningOpenGenericExclusionTests public void When_scanning_assemblies_should_not_register_open_generic_type_parameters() { // Arrange — scan the Brighter core assembly, which contains DeferMessageOnErrorHandler - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_service_collection_subscriber_registry_should_implement_inspector.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_service_collection_subscriber_registry_should_implement_inspector.cs index 89e61b16ab..d0d6e57c5b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_service_collection_subscriber_registry_should_implement_inspector.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_service_collection_subscriber_registry_should_implement_inspector.cs @@ -38,7 +38,7 @@ public class ServiceCollectionSubscriberRegistryInspectorTests public ServiceCollectionSubscriberRegistryInspectorTests() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); _registry = new ServiceCollectionSubscriberRegistry(services); _registry.Register(); } diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_the_mapper_registry_is_not_needed_it_is_not_built.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_the_mapper_registry_is_not_needed_it_is_not_built.cs index 24b4f8b2d6..40c1b8978b 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_the_mapper_registry_is_not_needed_it_is_not_built.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_the_mapper_registry_is_not_needed_it_is_not_built.cs @@ -30,7 +30,7 @@ public void When_the_validator_has_no_transformer_probe_it_does_not_build_the_re return NewRegistry(); }; - var pipelineBuilder = new PipelineBuilder(new SubscriberRegistry()); + var pipelineBuilder = new PipelineBuilder(new SubscriberRegistry(), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var validator = new PipelineValidator( @@ -58,7 +58,7 @@ public void When_the_diagnostic_writer_has_no_publications_it_does_not_build_the return NewRegistry(); }; - var pipelineBuilder = new PipelineBuilder(new SubscriberRegistry()); + var pipelineBuilder = new PipelineBuilder(new SubscriberRegistry(), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var writer = new PipelineDiagnosticWriter( diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_false_should_log_errors_not_throw.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_false_should_log_errors_not_throw.cs index 96ee03f6c6..6827f434bd 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_false_should_log_errors_not_throw.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_false_should_log_errors_not_throw.cs @@ -42,7 +42,7 @@ private static BrighterValidationHostedService BuildService( IAmAPipelineValidator validator, SpyLogger logger) { - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var provider = services.BuildServiceProvider(); return new BrighterValidationHostedService( @@ -56,7 +56,7 @@ private static BrighterValidationHostedService BuildService( public void When_validate_pipelines_with_throw_on_error_false_should_store_in_options() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); @@ -74,7 +74,7 @@ public void When_validate_pipelines_with_throw_on_error_false_should_store_in_op public void When_validate_pipelines_with_throw_on_error_true_should_store_in_options() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); @@ -92,7 +92,7 @@ public void When_validate_pipelines_with_throw_on_error_true_should_store_in_opt public void When_validate_pipelines_default_should_have_throw_on_error_true() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_true_with_transform_and_provider_triggers_should_not_block.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_true_with_transform_and_provider_triggers_should_not_block.cs index 9afcdadaab..1206b6ad74 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_true_with_transform_and_provider_triggers_should_not_block.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_throw_on_error_true_with_transform_and_provider_triggers_should_not_block.cs @@ -47,11 +47,11 @@ public async Task When_throw_on_error_true_with_transform_and_provider_triggers_ var routingKey = new RoutingKey("greeting"); var producer = new InMemoryMessageProducer( new InternalBus(), - new Publication { Topic = routingKey, RequestType = typeof(MyDescribableCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyDescribableCommand) }); var producerRegistry = new ProducerRegistry( new Dictionary { { routingKey, producer } }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); subscriberRegistry.Register(); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_two_publications_same_request_different_topics_should_report_two_ordered_warnings.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_two_publications_same_request_different_topics_should_report_two_ordered_warnings.cs index 206869de03..5c7eb0fb90 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_two_publications_same_request_different_topics_should_report_two_ordered_warnings.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_two_publications_same_request_different_topics_should_report_two_ordered_warnings.cs @@ -50,7 +50,7 @@ private static PipelineValidationResult ValidateTwoPublications(MessageMapperReg new Publication { Topic = new RoutingKey("greeting-v2"), RequestType = typeof(MyDescribableCommand) } }; var validator = new PipelineValidator( - new PipelineBuilder(new SubscriberRegistry()), + new PipelineBuilder(new SubscriberRegistry(), loggerFactory: Initializer.TestLoggerFactory), publications, transformerProbe: StubTransformerResolvabilityProbe.ResolvesNothing, mapperRegistryFactory: () => registry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_hosted_service_and_options.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_hosted_service_and_options.cs index 3d4218da69..bafa68c057 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_hosted_service_and_options.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_hosted_service_and_options.cs @@ -37,7 +37,7 @@ public class ValidatePipelinesHostedServiceRegistrationTests public void When_validate_pipelines_called_should_register_hosted_service() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); @@ -55,7 +55,7 @@ public void When_validate_pipelines_called_should_register_hosted_service() public void When_validate_pipelines_called_should_register_options_with_consumer_owns_false() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_validator_in_di.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_validator_in_di.cs index bd0cdacc6f..b1a4be0624 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_validator_in_di.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_called_should_register_validator_in_di.cs @@ -35,7 +35,7 @@ public class ValidatePipelinesRegistrationTests public void When_validate_pipelines_called_should_register_validator_in_di() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); var builder = new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_disabled_should_not_register.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_disabled_should_not_register.cs index 6e90b53fd7..2fca3a6af0 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_disabled_should_not_register.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_disabled_should_not_register.cs @@ -36,6 +36,7 @@ public class ValidatePipelinesDisabledTests private static IBrighterBuilder CreateBuilder(out ServiceCollection services) { services = new ServiceCollection(); + services.AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); var mapperRegistry = new ServiceCollectionMessageMapperRegistryBuilder(services); return new ServiceCollectionBrighterBuilder(services, subscriberRegistry, mapperRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_with_producers_should_receive_publications.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_with_producers_should_receive_publications.cs index 66ed031e2d..b065755585 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_with_producers_should_receive_publications.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_with_producers_should_receive_publications.cs @@ -38,11 +38,11 @@ public void When_validate_pipelines_with_producers_should_detect_missing_request // Arrange — set up a producer whose publication has no RequestType var routingKey = new RoutingKey("test.validation.topic"); var producer = new InMemoryMessageProducer( - new InternalBus(), new Publication { Topic = routingKey }); + new InternalBus(), Initializer.TestLoggerFactory, new Publication { Topic = routingKey }); var producerRegistry = new ProducerRegistry( new Dictionary { { routingKey, producer } }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); services.AddSingleton(producerRegistry); @@ -69,11 +69,11 @@ public void When_validate_pipelines_with_valid_producers_should_pass_producer_ch var routingKey = new RoutingKey("test.validation.topic"); var producer = new InMemoryMessageProducer( new InternalBus(), - new Publication { Topic = routingKey, RequestType = typeof(MyValidationCommand) }); + Initializer.TestLoggerFactory, new Publication { Topic = routingKey, RequestType = typeof(MyValidationCommand) }); var producerRegistry = new ProducerRegistry( new Dictionary { { routingKey, producer } }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); services.AddSingleton(producerRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_without_describe_should_build_service_provider.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_without_describe_should_build_service_provider.cs index cb5f8c2734..fe6cd21771 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_without_describe_should_build_service_provider.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validate_pipelines_without_describe_should_build_service_provider.cs @@ -38,7 +38,7 @@ public class ValidatePipelinesWithoutDescribeTests public async Task When_validate_pipelines_called_without_describe_should_build_and_start() { // Arrange — register ValidatePipelines but NOT DescribePipelines - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); services.AddSingleton(subscriberRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_has_warnings_should_log_them.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_has_warnings_should_log_them.cs index b85b14b991..ccaded9ec6 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_has_warnings_should_log_them.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_has_warnings_should_log_them.cs @@ -45,7 +45,7 @@ public async Task When_validation_has_warnings_should_log_them_at_warning_level( var validator = SpyPipelineValidator.WithWarningsOnly(warning1, warning2); var options = Options.Create(new BrighterPipelineValidationOptions { ConsumerOwnsValidation = false }); var logger = new SpyLogger(); - var provider = new ServiceCollection().BuildServiceProvider(); + var provider = new ServiceCollection().AddLogging().BuildServiceProvider(); var service = new BrighterValidationHostedService(options, validator, provider, logger); // Act @@ -67,7 +67,7 @@ public async Task When_validation_has_no_warnings_should_not_log_warnings() var validator = SpyPipelineValidator.WithNoErrors(); var options = Options.Create(new BrighterPipelineValidationOptions { ConsumerOwnsValidation = false }); var logger = new SpyLogger(); - var provider = new ServiceCollection().BuildServiceProvider(); + var provider = new ServiceCollection().AddLogging().BuildServiceProvider(); var service = new BrighterValidationHostedService(options, validator, provider, logger); // Act diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_starts_without_consumers_should_validate.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_starts_without_consumers_should_validate.cs index 4dcae60297..b8e3abd5f3 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_starts_without_consumers_should_validate.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_hosted_service_starts_without_consumers_should_validate.cs @@ -41,7 +41,7 @@ private static BrighterValidationHostedService BuildService( IAmAPipelineValidator validator, IAmAPipelineDiagnosticWriter? diagnosticWriter = null) { - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); if (diagnosticWriter != null) services.AddSingleton(diagnosticWriter); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_step_present_and_no_provider_through_di_should_surface_warning.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_step_present_and_no_provider_through_di_should_surface_warning.cs index 9307a259dd..bfadef252c 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_step_present_and_no_provider_through_di_should_surface_warning.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validation_step_present_and_no_provider_through_di_should_surface_warning.cs @@ -38,7 +38,7 @@ public void When_validation_step_present_and_no_provider_through_di_should_surfa // Arrange — a handler whose pipeline declares a validation step ([ValidateRequest]) but no // validation provider is registered; ValidatePipelines must compute the (false,false) // registrations from the service collection and thread them into the validator. - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); subscriberRegistry.Register(); services.AddSingleton(subscriberRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_encounters_warnings_and_errors_should_collect_separately.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_encounters_warnings_and_errors_should_collect_separately.cs index 6d7988ace8..7bd2cff760 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_encounters_warnings_and_errors_should_collect_separately.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_encounters_warnings_and_errors_should_collect_separately.cs @@ -39,7 +39,7 @@ public void When_validator_encounters_warnings_and_errors_should_collect_separat // Handler path: misordered backstop/resilience triggers a Warning var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyMisorderedBackstopHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Producer path: null RequestType triggers an Error diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_finds_errors_across_paths_should_aggregate_all.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_finds_errors_across_paths_should_aggregate_all.cs index e4c13f6dd2..48b8d4d847 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_finds_errors_across_paths_should_aggregate_all.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_finds_errors_across_paths_should_aggregate_all.cs @@ -40,7 +40,7 @@ public void When_all_paths_have_errors_should_collect_errors_from_each() // Handler path: internal handler triggers HandlerTypeVisibility error var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyInternalHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // Producer path: null RequestType triggers PublicationRequestTypeSet error diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_resolved_from_di_should_validate_through_full_path.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_resolved_from_di_should_validate_through_full_path.cs index 15d7564326..ca188309da 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_resolved_from_di_should_validate_through_full_path.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_resolved_from_di_should_validate_through_full_path.cs @@ -36,7 +36,7 @@ public class ValidatePipelinesThroughDiPathTests public void When_validator_resolved_from_di_should_validate_without_configuration_exception() { // Arrange — wire up Brighter with a handler and ValidatePipelines through the builder - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var subscriberRegistry = new ServiceCollectionSubscriberRegistry(services); subscriberRegistry.Register(); services.AddSingleton(subscriberRegistry); diff --git a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_result_has_only_warnings_should_be_valid.cs b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_result_has_only_warnings_should_be_valid.cs index 80c80a911b..be086eb188 100644 --- a/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_result_has_only_warnings_should_be_valid.cs +++ b/tests/Paramore.Brighter.Core.Tests/Validation/When_validator_result_has_only_warnings_should_be_valid.cs @@ -36,7 +36,7 @@ public void When_validator_result_has_only_warnings_should_be_valid() // Arrange — handler with misordered backstop/resilience produces only a warning var registry = new SubscriberRegistry(); registry.Add(typeof(MyDescribableCommand), typeof(MyMisorderedBackstopHandler)); - var pipelineBuilder = new PipelineBuilder(registry); + var pipelineBuilder = new PipelineBuilder(registry, loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); // No publications or subscriptions — only handler path runs diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_blocking_wait_workflow.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_blocking_wait_workflow.cs index ca92e7bd19..f1262c95f2 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_blocking_wait_workflow.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_blocking_wait_workflow.cs @@ -30,7 +30,7 @@ public MediatorWaitStepFlowTests(ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -42,26 +42,26 @@ public MediatorWaitStepFlowTests(ITestOutputHelper testOutputHelper) "Test of Job", new ChangeAsync( (_) => Task.CompletedTask), () => { _stepCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); var firstStep = new Wait("Test of Job", TimeSpan.FromMilliseconds(100), - secondStep - ); + secondStep, + loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(_timeProvider); - InMemoryJobChannel channel = new(); + InMemoryStateStoreAsync store = new(Initializer.TestLoggerFactory, _timeProvider); + InMemoryJobChannel channel = new(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( channel, store ); - _runner = new Runner(channel, store, commandProcessor, _scheduler); - _waker = new Waker(TimeSpan.FromMilliseconds(100), _scheduler); + _runner = new Runner(channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); + _waker = new Waker(TimeSpan.FromMilliseconds(100), _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_change_workflow.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_change_workflow.cs index 3dc66d708b..97a77138c8 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_change_workflow.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_change_workflow.cs @@ -28,7 +28,7 @@ public MediatorChangeStepFlowTests (ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData { Bag = { ["MyValue"] = "Test" } }; @@ -45,20 +45,20 @@ public MediatorChangeStepFlowTests (ITestOutputHelper testOutputHelper) return tcs.Task; }), () => { _stepCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(firstStep); - var store = new InMemoryStateStoreAsync (); - _channel = new InMemoryJobChannel(); + var store = new InMemoryStateStoreAsync (loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_failing_choice_workflow_step.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_failing_choice_workflow_step.cs index 6263daac96..d3ff67bd48 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_failing_choice_workflow_step.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_failing_choice_workflow_step.cs @@ -39,7 +39,7 @@ public MediatorFailingChoiceFlowTests(ITestOutputHelper testOutputHelper) }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -52,33 +52,33 @@ public MediatorFailingChoiceFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyOtherCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepCompletedThree = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); var stepTwo = new Sequential( "Test of Job SequenceStep Two", new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepCompletedTwo = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); var stepOne = new ExclusiveChoice( "Test of Job SequenceStep One", new Specification(data => data.Bag["MyValue"] as string == "Pass"), () => { _stepCompletedOne = true; }, stepTwo, - stepThree); + stepThree, loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(stepOne); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_multistep_workflow_with_reply.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_multistep_workflow_with_reply.cs index 663166bd3f..d9e12e4289 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_multistep_workflow_with_reply.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_multistep_workflow_with_reply.cs @@ -36,7 +36,7 @@ public MediatorReplyMultiStepFlowTests(ITestOutputHelper testOutputHelper) }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -49,7 +49,7 @@ public MediatorReplyMultiStepFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepCompletedTwo = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); Sequential stepOne = new( "Test of Job SequenceStep One", @@ -57,19 +57,19 @@ public MediatorReplyMultiStepFlowTests(ITestOutputHelper testOutputHelper) (data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }, (reply, data) => data.Bag["MyReply"] = ((MyEvent)reply).Value), () => { _stepCompletedOne = true; }, - stepTwo); + stepTwo, loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(stepOne); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_passing_choice_workflow_step.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_passing_choice_workflow_step.cs index 375c452713..be19569916 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_passing_choice_workflow_step.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_passing_choice_workflow_step.cs @@ -39,7 +39,7 @@ public MediatorPassingChoiceFlowTests(ITestOutputHelper testOutputHelper) }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -52,33 +52,33 @@ public MediatorPassingChoiceFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyOtherCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepCompletedThree = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); var stepTwo = new Sequential( "Test of Job SequenceStep Two", new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepCompletedTwo = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); var stepOne = new ExclusiveChoice( "Test of Job SequenceStep One", new Specification(x => x.Bag["MyValue"] as string == "Pass"), () => { _stepCompletedOne = true; }, stepTwo, - stepThree); + stepThree, loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(stepOne); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_single_step_workflow.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_single_step_workflow.cs index b1674e286f..f6f75f1e31 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_single_step_workflow.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_single_step_workflow.cs @@ -28,7 +28,7 @@ public MediatorOneStepFlowTests(ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -41,20 +41,20 @@ public MediatorOneStepFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyCommand { Value = (workflowData.Bag["MyValue"] as string)!}), () => { _stepCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_two_step_workflow.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_two_step_workflow.cs index 0a69e1288e..9a7bf0fcb9 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_two_step_workflow.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_two_step_workflow.cs @@ -28,7 +28,7 @@ public MediatorTwoStepFlowTests(ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -41,28 +41,28 @@ public MediatorTwoStepFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _stepsCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); var firstStep = new Sequential( "Test of Job One", new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { workflowData.Bag["MyValue"] = "TestTwo"; }, - secondStep - ); + secondStep, + loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_a_parallel_split.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_a_parallel_split.cs index fe2e01f0d2..1fb576064f 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_a_parallel_split.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_a_parallel_split.cs @@ -29,7 +29,7 @@ public MediatorParallelSplitFlowTests(ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -48,32 +48,32 @@ public MediatorParallelSplitFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((d) => new MyCommand { Value = (d.Bag["MyOtherValue"] as string)! }), () => { _secondBranchFinished = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); var firstBranch = new Sequential( "Test of Job One", new FireAndForgetAsync((d) => new MyCommand { Value = (d.Bag["MyValue"] as string)! }), () => { _firstBranchFinished = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); return [firstBranch, secondBranch]; - } - ); + }, + loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(parallelSplit); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_reply.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_reply.cs index bcae7c5cc3..588b2e4805 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_reply.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_reply.cs @@ -39,7 +39,7 @@ public MediatorReplyStepFlowTests(ITestOutputHelper testOutputHelper) }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); var workflowData= new WorkflowTestData(); @@ -53,19 +53,19 @@ public MediatorReplyStepFlowTests(ITestOutputHelper testOutputHelper) (data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }, (reply,data) => { data.Bag["MyReply"] = reply!.Value; }), () => { _stepCompleted = true; }, - null); + null, loggerFactory: Initializer.TestLoggerFactory); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_nofault.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_nofault.cs index f91fb791b0..1822978f6d 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_nofault.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_nofault.cs @@ -36,7 +36,7 @@ public MediatorRobustReplyNoFaultStepFlowTests(ITestOutputHelper testOutputHelpe }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); @@ -53,20 +53,20 @@ public MediatorRobustReplyNoFaultStepFlowTests(ITestOutputHelper testOutputHelpe (fault, data) => { data.Bag["MyFault"] = ((MyFault)fault).Value; }), () => { _stepCompleted = true; }, null, - () => { _stepFaulted = true; }, + Initializer.TestLoggerFactory, () => { _stepFaulted = true; }, null); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_with_fault.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_with_fault.cs index 2026ab30b7..059368edff 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_with_fault.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_a_workflow_with_robust_reply_with_fault.cs @@ -38,7 +38,7 @@ public MediatorRobustReplyFaultStepFlowTests(ITestOutputHelper testOutputHelper) }); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); @@ -55,20 +55,20 @@ public MediatorRobustReplyFaultStepFlowTests(ITestOutputHelper testOutputHelper) (fault, data) => { data.Bag["MyFault"] = fault!.Value; }), () => { _stepCompleted = true; }, null, - () => { _stepFaulted = true; }, + Initializer.TestLoggerFactory, () => { _stepFaulted = true; }, null); _job.InitSteps(firstStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_multiple_workflows.cs b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_multiple_workflows.cs index cea7bc1574..6086515055 100644 --- a/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_multiple_workflows.cs +++ b/tests/Paramore.Brighter.Core.Tests/Workflows/When_running_multiple_workflows.cs @@ -30,7 +30,7 @@ public MediatorMultipleWorkflowFlowTests(ITestOutputHelper testOutputHelper) var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(commandProcessor)); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), - new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory()); + new PolicyRegistry(), new ResiliencePipelineRegistry(),new InMemorySchedulerFactory(loggerFactory: Initializer.TestLoggerFactory), loggerFactory: Initializer.TestLoggerFactory); PipelineBuilder.ClearPipelineCache(); @@ -43,8 +43,8 @@ public MediatorMultipleWorkflowFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)!}), () => { _jobOneCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); _firstJob.InitSteps(firstStep); @@ -57,20 +57,20 @@ public MediatorMultipleWorkflowFlowTests(ITestOutputHelper testOutputHelper) new FireAndForgetAsync((data) => new MyCommand { Value = (data.Bag["MyValue"] as string)! }), () => { _jobTwoCompleted = true; }, - null - ); + null, + loggerFactory: Initializer.TestLoggerFactory); _secondJob.InitSteps(secondStep); - InMemoryStateStoreAsync store = new(); - _channel = new InMemoryJobChannel(); + InMemoryStateStoreAsync store = new(loggerFactory: Initializer.TestLoggerFactory); + _channel = new InMemoryJobChannel(loggerFactory: Initializer.TestLoggerFactory); _scheduler = new Scheduler( _channel, store ); - _runner = new Runner(_channel, store, commandProcessor, _scheduler); + _runner = new Runner(_channel, store, commandProcessor, _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.DynamoDB.Tests/Locking/DynamoDbLockingTest.cs b/tests/Paramore.Brighter.DynamoDB.Tests/Locking/DynamoDbLockingTest.cs index 54238d081c..ea8e397f60 100644 --- a/tests/Paramore.Brighter.DynamoDB.Tests/Locking/DynamoDbLockingTest.cs +++ b/tests/Paramore.Brighter.DynamoDB.Tests/Locking/DynamoDbLockingTest.cs @@ -19,6 +19,6 @@ protected override IDistributedLock CreateDistributedLock() new DynamoDbLockingProviderOptions(tableName, _leaseholderGroupId) { LeaseValidity = TimeSpan.FromSeconds(10) - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } } diff --git a/tests/Paramore.Brighter.DynamoDB.V4.Tests/Locking/DynamoDbLockingTest.cs b/tests/Paramore.Brighter.DynamoDB.V4.Tests/Locking/DynamoDbLockingTest.cs index 48d1f3ce20..c4821381d0 100644 --- a/tests/Paramore.Brighter.DynamoDB.V4.Tests/Locking/DynamoDbLockingTest.cs +++ b/tests/Paramore.Brighter.DynamoDB.V4.Tests/Locking/DynamoDbLockingTest.cs @@ -19,6 +19,6 @@ protected override IDistributedLock CreateDistributedLock() new DynamoDbLockingProviderOptions(tableName, _leaseholderGroupId) { LeaseValidity = TimeSpan.FromSeconds(10) - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } } diff --git a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionDefaultTransientTests.cs b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionDefaultTransientTests.cs index 986d10944f..e54a2fecee 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionDefaultTransientTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionDefaultTransientTests.cs @@ -20,7 +20,7 @@ public class AssemblyResolutionDefaultTransientTests public AssemblyResolutionDefaultTransientTests() { - _services = new ServiceCollection(); + _services = new ServiceCollection().AddLogging(); _services.AddConsumers().AutoFromAssemblies(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTests.cs b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTests.cs index df5eca91fc..3eced371c3 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTests.cs @@ -20,7 +20,7 @@ public class AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTe public AssemblyResolutionHandlerLifetimeScopedAndMapperLifetimeSingletonTests() { - _services = new ServiceCollection(); + _services = new ServiceCollection().AddLogging(); _services.AddConsumers() .AutoFromAssemblies(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionMissingDependenciesTests.cs b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionMissingDependenciesTests.cs index f33f184ea2..46e571d210 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionMissingDependenciesTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/AssemblyResolutionMissingDependenciesTests.cs @@ -17,7 +17,7 @@ public void When_we_auto_register_handlers_from_assemblies_with_missing_dependen ValidateOnBuild = true, ValidateScopes = true }); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddConsumers().AutoFromAssemblies(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorIsolationTests.cs b/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorIsolationTests.cs index 58ff79237d..05ec8dcfb7 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorIsolationTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorIsolationTests.cs @@ -43,11 +43,11 @@ public class CommandProcessorIsolationTests public void TwoCommandProcessors_HaveIsolatedState() { // Arrange - Create two independent service providers - var services1 = new ServiceCollection(); + var services1 = new ServiceCollection().AddLogging(); services1.AddBrighter(); var provider1 = services1.BuildServiceProvider(); - var services2 = new ServiceCollection(); + var services2 = new ServiceCollection().AddLogging(); services2.AddBrighter(); var provider2 = services2.BuildServiceProvider(); @@ -71,7 +71,7 @@ public async Task ParallelTests_DoNotInterfere() var index = i; tasks[i] = Task.Run(() => { - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); processors[index] = provider.GetRequiredService(); @@ -115,7 +115,7 @@ public async Task ParallelBrighterSetups_WithProducers_HaveIsolatedOutboxes() var routingKey = new RoutingKey($"test.command.{index}"); var internalBus = new InternalBus(); - var producer = new InMemoryMessageProducer(internalBus, new Publication + var producer = new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = routingKey, RequestType = typeof(IsolationTestCommand) @@ -127,7 +127,7 @@ public async Task ParallelBrighterSetups_WithProducers_HaveIsolatedOutboxes() // Each test has its OWN outbox - this is the key isolation requirement outboxes[index] = new InMemoryOutbox(timeProvider); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .AddProducers(cfg => { @@ -186,7 +186,7 @@ public async Task ParallelBrighterSetups_WithFuncOverloads_AreIsolated() var routingKey = new RoutingKey($"test.func.{index}"); var internalBus = new InternalBus(); - var producer = new InMemoryMessageProducer(internalBus, new Publication + var producer = new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = routingKey, RequestType = typeof(IsolationTestCommand) @@ -196,7 +196,7 @@ public async Task ParallelBrighterSetups_WithFuncOverloads_AreIsolated() new Dictionary { { routingKey, producer } }); // Using the new Func overload pattern - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(outbox); services.AddSingleton(producerRegistry); diff --git a/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorSingletonTests.cs b/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorSingletonTests.cs index 3d970c875f..3ffb75959d 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorSingletonTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/CommandProcessorSingletonTests.cs @@ -49,7 +49,7 @@ public class CommandProcessorSingletonTests public void SameProvider_MultipleResolutions_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); @@ -71,7 +71,7 @@ public void SameProvider_MultipleResolutions_ReturnsSameInstance() public void SameProvider_DifferentScopes_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); @@ -106,7 +106,7 @@ public void SameProvider_DifferentScopes_ReturnsSameInstance() public async Task SameProvider_ConcurrentResolutions_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); var processors = new ConcurrentBag(); @@ -139,7 +139,7 @@ public async Task SameProvider_ConcurrentResolutions_ReturnsSameInstance() public void SameProvider_ResolvedWithOtherServices_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); services.AddScoped(); var provider = services.BuildServiceProvider(); @@ -173,7 +173,7 @@ public void SameProvider_ResolvedWithOtherServices_ReturnsSameInstance() public void SameProvider_ManySequentialResolutions_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); @@ -201,7 +201,7 @@ public void WithProducers_MultipleResolutions_ReturnsSameInstance() var internalBus = new InternalBus(); var routingKey = new RoutingKey("test.singleton.command"); - var producer = new InMemoryMessageProducer(internalBus, new Publication + var producer = new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = routingKey, RequestType = typeof(SingletonTestCommand) @@ -212,7 +212,7 @@ public void WithProducers_MultipleResolutions_ReturnsSameInstance() var outbox = new InMemoryOutbox(timeProvider); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .AddProducers(cfg => { @@ -246,7 +246,7 @@ public void WithFuncOverloads_MultipleResolutions_ReturnsSameInstance() var internalBus = new InternalBus(); var routingKey = new RoutingKey("test.func.singleton"); - var producer = new InMemoryMessageProducer(internalBus, new Publication + var producer = new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = routingKey, RequestType = typeof(SingletonTestCommand) @@ -257,7 +257,7 @@ public void WithFuncOverloads_MultipleResolutions_ReturnsSameInstance() var outbox = new InMemoryOutbox(timeProvider); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(producerRegistry); services.AddSingleton(outbox); @@ -298,7 +298,7 @@ public async Task WithProducers_ConcurrentResolutions_ReturnsSameInstance() var internalBus = new InternalBus(); var routingKey = new RoutingKey("test.concurrent.singleton"); - var producer = new InMemoryMessageProducer(internalBus, new Publication + var producer = new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = routingKey, RequestType = typeof(SingletonTestCommand) @@ -309,7 +309,7 @@ public async Task WithProducers_ConcurrentResolutions_ReturnsSameInstance() var outbox = new InMemoryOutbox(timeProvider); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .AddProducers(cfg => { @@ -348,7 +348,7 @@ public async Task WithProducers_ConcurrentResolutions_ReturnsSameInstance() public async Task SameProvider_ConcurrentScopedResolutions_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); var processors = new ConcurrentBag(); @@ -387,7 +387,7 @@ public async Task SameProvider_ConcurrentResolutions_OnlyInstantiatesOnce() // Arrange var instantiationCount = 0; - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); // Decorate the command processor factory to count instantiations @@ -438,7 +438,7 @@ public async Task SameProvider_ConcurrentResolutions_OnlyInstantiatesOnce() public async Task SameProvider_AllResolutions_HaveSameHashCode() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); var hashCodes = new ConcurrentBag(); @@ -469,7 +469,7 @@ public async Task SameProvider_AllResolutions_HaveSameHashCode() public void SameProvider_NestedScopes_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/DispatcherResolutionScopedDependencyTests.cs b/tests/Paramore.Brighter.Extensions.Tests/DispatcherResolutionScopedDependencyTests.cs index 689a0b6a68..633381feda 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/DispatcherResolutionScopedDependencyTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/DispatcherResolutionScopedDependencyTests.cs @@ -42,7 +42,7 @@ public void ShouldResolveIDispatcherCorrectlyWithHost() private void Build(InternalBus bus) { - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); AddServices(services, bus); @@ -74,7 +74,7 @@ private void AddServices(IServiceCollection services, InternalBus bus) options.HandlerLifetime = ServiceLifetime.Scoped; options.TransformerLifetime = ServiceLifetime.Scoped; - options.DefaultChannelFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + options.DefaultChannelFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }) .AddProducers(configure => { @@ -83,7 +83,7 @@ private void AddServices(IServiceCollection services, InternalBus bus) { { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, - new Publication { Topic = "test" }) + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); var outboxConfiguration = new RelationalDatabaseConfiguration( @@ -96,7 +96,7 @@ private void AddServices(IServiceCollection services, InternalBus bus) //We need this as it is a dependency of the SqliteConnectionProvider services.AddSingleton(outboxConfiguration); - configure.Outbox = new SqliteOutbox(outboxConfiguration, new SqliteConnectionProvider(outboxConfiguration)); + configure.Outbox = new SqliteOutbox(outboxConfiguration, new SqliteConnectionProvider(outboxConfiguration), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); configure.TransactionProvider = typeof(SqliteEntityFrameworkTransactionProvider); configure.ConnectionProvider = typeof(SqliteConnectionProvider); configure.MaxOutStandingMessages = 5; diff --git a/tests/Paramore.Brighter.Extensions.Tests/FactoryErrorHandlingTests.cs b/tests/Paramore.Brighter.Extensions.Tests/FactoryErrorHandlingTests.cs index fbc27b78cb..c9111c8e6c 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/FactoryErrorHandlingTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/FactoryErrorHandlingTests.cs @@ -37,7 +37,7 @@ public class FactoryErrorHandlingTests public void Factory_UnregisteredHandler_ReturnsNull() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Note: NOT registering TestHandler services.AddSingleton(new BrighterOptions { @@ -59,7 +59,7 @@ public void Factory_UnregisteredHandler_ReturnsNull() public void Factory_NullLifetime_HandlesGracefullyForTransient() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -88,7 +88,7 @@ public void Factory_NullLifetime_HandlesGracefullyForTransient() public void Factory_InvalidHandlerType_ReturnsNull() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient @@ -109,7 +109,7 @@ public void Factory_InvalidHandlerType_ReturnsNull() public void Factory_MissingBrighterOptions_UsesDefaultTransient() { // Arrange - Don't register IBrighterOptions - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); // NOT registering IBrighterOptions diff --git a/tests/Paramore.Brighter.Extensions.Tests/FactoryLifetimeTests.cs b/tests/Paramore.Brighter.Extensions.Tests/FactoryLifetimeTests.cs index 3185ccbcfb..3439bb2082 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/FactoryLifetimeTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/FactoryLifetimeTests.cs @@ -36,7 +36,7 @@ public class FactoryLifetimeTests public void Factory_WithScopedLifetime_ReturnsSameInstanceWithinScope() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -59,7 +59,7 @@ public void Factory_WithScopedLifetime_ReturnsSameInstanceWithinScope() public void Factory_WithScopedLifetime_ReturnsDifferentInstancesAcrossScopes() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -83,7 +83,7 @@ public void Factory_WithScopedLifetime_ReturnsDifferentInstancesAcrossScopes() public void Factory_WithTransientLifetime_ReturnsDifferentInstancesEachTime() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -106,7 +106,7 @@ public void Factory_WithTransientLifetime_ReturnsDifferentInstancesEachTime() public void Factory_WithSingletonLifetime_ReturnsSameInstanceAcrossScopes() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(); services.AddSingleton(new BrighterOptions { @@ -130,7 +130,7 @@ public void Factory_WithSingletonLifetime_ReturnsSameInstanceAcrossScopes() public void AsyncFactory_WithSingletonLifetime_ReturnsSameInstanceAcrossScopes() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(); services.AddSingleton(new BrighterOptions { @@ -154,7 +154,7 @@ public void AsyncFactory_WithSingletonLifetime_ReturnsSameInstanceAcrossScopes() public void AsyncFactory_WithScopedLifetime_ReturnsSameInstanceWithinScope() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -177,7 +177,7 @@ public void AsyncFactory_WithScopedLifetime_ReturnsSameInstanceWithinScope() public void AsyncFactory_WithScopedLifetime_ReturnsDifferentInstancesAcrossScopes() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -201,7 +201,7 @@ public void AsyncFactory_WithScopedLifetime_ReturnsDifferentInstancesAcrossScope public void AsyncFactory_WithTransientLifetime_ReturnsDifferentInstances() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -224,7 +224,7 @@ public void AsyncFactory_WithTransientLifetime_ReturnsDifferentInstances() public void Factory_HandlerWithDependency_ResolvesBothCorrectly() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(); services.AddTransient(); services.AddSingleton(new BrighterOptions @@ -248,7 +248,7 @@ public void Factory_HandlerWithDependency_ResolvesBothCorrectly() public void Factory_Release_ClearsHandlerFromCache() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -273,7 +273,7 @@ public void Factory_Release_ClearsHandlerFromCache() public void Factory_WithScopedLifetime_TracksDisposableHandler() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { diff --git a/tests/Paramore.Brighter.Extensions.Tests/FactoryThreadSafetyTests.cs b/tests/Paramore.Brighter.Extensions.Tests/FactoryThreadSafetyTests.cs index e9d8044d4b..6889530910 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/FactoryThreadSafetyTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/FactoryThreadSafetyTests.cs @@ -41,7 +41,7 @@ public class FactoryThreadSafetyTests public async Task ConcurrentSingletonResolution_ReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(); services.AddSingleton(new BrighterOptions { @@ -75,7 +75,7 @@ public async Task ConcurrentSingletonResolution_ReturnsSameInstance() public async Task ConcurrentScopedResolution_SameScopeReturnsSameInstance() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -109,7 +109,7 @@ public async Task ConcurrentScopedResolution_SameScopeReturnsSameInstance() public async Task ConcurrentTransientResolution_ReturnsDifferentInstances() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { @@ -145,7 +145,7 @@ public async Task ConcurrentSingletonResolution_OnlyCreatesOneInstance() // Arrange - Use a handler that tracks instantiation count CountingHandler.ResetCount(); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(); services.AddSingleton(new BrighterOptions { diff --git a/tests/Paramore.Brighter.Extensions.Tests/InstanceScopedLoggingTests.cs b/tests/Paramore.Brighter.Extensions.Tests/InstanceScopedLoggingTests.cs new file mode 100644 index 0000000000..3406711efd --- /dev/null +++ b/tests/Paramore.Brighter.Extensions.Tests/InstanceScopedLoggingTests.cs @@ -0,0 +1,110 @@ +#region Licence +/* The MIT License (MIT) +Copyright © 2026 Ian Cooper + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#endregion + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Paramore.Brighter.Extensions.DependencyInjection; +using Paramore.Brighter.Extensions.Tests.TestDoubles; +using Xunit; + +namespace Paramore.Brighter.Extensions.Tests; + +/// +/// Verifies that Brighter logging is instance-scoped: each logs through the +/// of the container that built it. This replaces the previous behaviour where the +/// container's factory was copied into the static ApplicationLogging.LoggerFactory, which caused +/// use-after-dispose (when a container was disposed) and cross-talk between two Brighter instances in one process. +/// +public class InstanceScopedLoggingTests +{ + private static ServiceProvider BuildProvider(CapturingLoggerProvider capture) + { + var services = new ServiceCollection(); + services.AddLogging(builder => + { + builder.SetMinimumLevel(LogLevel.Trace); + builder.AddProvider(capture); + }); + services.AddBrighter(); + return services.BuildServiceProvider(); + } + + private class LogProbeEvent() : Event(Guid.NewGuid()); + + [Fact] + public void CommandProcessor_LogsThroughItsOwnContainersFactory_NotAnothers() + { + var captureA = new CapturingLoggerProvider(); + var captureB = new CapturingLoggerProvider(); + + using var providerA = BuildProvider(captureA); + using var providerB = BuildProvider(captureB); + + var commandProcessorA = providerA.GetRequiredService(); + providerB.GetRequiredService(); + + // Publishing with no subscribers still emits pipeline log lines through A's logger only. + commandProcessorA.Publish(new LogProbeEvent()); + + Assert.NotEmpty(captureA.Entries); + Assert.Empty(captureB.Entries); + } + + [Fact] + public void DisposingOneContainer_DoesNotBreakLoggingInAnother() + { + var captureA = new CapturingLoggerProvider(); + var captureB = new CapturingLoggerProvider(); + + var providerA = BuildProvider(captureA); + using var providerB = BuildProvider(captureB); + + // Resolve B first, then A, so that under the previous (buggy) static behaviour the shared + // ApplicationLogging.LoggerFactory would have ended up pointing at A's factory (last writer wins). + var commandProcessorB = providerB.GetRequiredService(); + providerA.GetRequiredService(); + + // Disposing A disposes A's container (and its ILoggerFactory). B must be entirely unaffected: + // with instance-scoped logging, B logs through B's own factory and never touches A's. + providerA.Dispose(); + + var exception = Record.Exception(() => commandProcessorB.Publish(new LogProbeEvent())); + + Assert.Null(exception); + Assert.NotEmpty(captureB.Entries); + Assert.Empty(captureA.Entries); + } + + [Fact] + public void When_no_logger_factory_is_registered_should_fail_fast() + { + // No AddLogging(): callers must register a logger factory or explicitly register NullLoggerFactory.Instance. + var services = new ServiceCollection(); + services.AddBrighter(); + using var provider = services.BuildServiceProvider(); + + Assert.Throws(() => provider.GetRequiredService()); + } +} diff --git a/tests/Paramore.Brighter.Extensions.Tests/LifetimeConfigurationTests.cs b/tests/Paramore.Brighter.Extensions.Tests/LifetimeConfigurationTests.cs index 2e0fc456cd..a1bcab63e9 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/LifetimeConfigurationTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/LifetimeConfigurationTests.cs @@ -44,7 +44,7 @@ public class LifetimeConfigurationTests public void AddBrighter_WithDefaultLifetimes_RegistersAllAsTransient() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Act - Don't configure any lifetimes services.AddBrighter().AutoFromAssemblies(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/ServiceProviderLambdaTests.cs b/tests/Paramore.Brighter.Extensions.Tests/ServiceProviderLambdaTests.cs index 19bc267717..983ba035cc 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/ServiceProviderLambdaTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/ServiceProviderLambdaTests.cs @@ -41,7 +41,7 @@ public class ServiceProviderLambdaTests public void AddBrighter_WithServiceProviderFunc_ResolvesServicesCorrectly() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(); // Act @@ -62,7 +62,7 @@ public void AddBrighter_WithServiceProviderFunc_ResolvesServicesCorrectly() public void AddBrighter_SupportsPostConfigure_ForTestOverrides() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var customFactory = new InMemoryRequestContextFactory(); // Normal registration @@ -89,7 +89,7 @@ public void AddBrighter_SupportsPostConfigure_ForTestOverrides() public void AddProducers_WithServiceProviderFunc_DefersConfiguration() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var producerRegistry = new ProducerRegistry(new Dictionary()); services.AddSingleton(producerRegistry); @@ -112,9 +112,9 @@ public void AddProducers_WithServiceProviderFunc_DefersConfiguration() public void AddConsumers_WithServiceProviderFunc_ResolvesServicesCorrectly() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var internalBus = new InternalBus(); - var channelFactory = new InMemoryChannelFactory(internalBus, TimeProvider.System); + var channelFactory = new InMemoryChannelFactory(internalBus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); services.AddSingleton(channelFactory); // Act @@ -135,7 +135,7 @@ public void AddConsumers_WithServiceProviderFunc_ResolvesServicesCorrectly() public void AddBrighter_WithActionOverload_StillWorks() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Act - existing pattern services.AddBrighter(options => @@ -154,7 +154,7 @@ public void AddBrighter_WithActionOverload_StillWorks() public void AddBrighter_WithNoConfiguration_UsesDefaults() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Act services.AddBrighter(); @@ -170,7 +170,7 @@ public void AddBrighter_WithNoConfiguration_UsesDefaults() public void AddProducers_ResolvesTracerFromInterfaceRegistration() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var tracer = new BrighterTracer(); var outbox = new InMemoryOutbox(TimeProvider.System); var producerRegistry = new ProducerRegistry(new Dictionary()); diff --git a/tests/Paramore.Brighter.Extensions.Tests/TestDifferentSetups.cs b/tests/Paramore.Brighter.Extensions.Tests/TestDifferentSetups.cs index a02c0c55c3..7b6bbb9076 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/TestDifferentSetups.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/TestDifferentSetups.cs @@ -18,7 +18,7 @@ public partial class TestBrighterExtension [Fact] public void BasicSetup() { - var serviceCollection = new ServiceCollection(); + var serviceCollection = new ServiceCollection().AddLogging(); serviceCollection.AddBrighter().AutoFromAssemblies(); @@ -34,7 +34,7 @@ public void BasicSetup() [InlineData(typeof(Paramore.Brighter.Extensions.Tests.TestDoubles.TestBrighterExtension.StubSqlTransactionProvider), typeof(Paramore.Brighter.Extensions.Tests.TestDoubles.TestBrighterExtension.StubSqlTransactionProvider))] public void WithExternalBus(Type connectionProvider, Type transactionProvider) { - var serviceCollection = new ServiceCollection(); + var serviceCollection = new ServiceCollection().AddLogging(); const string mytopic = "MyTopic"; var routingKey = new RoutingKey(mytopic); @@ -42,7 +42,7 @@ public void WithExternalBus(Type connectionProvider, Type transactionProvider) new Dictionary { { - routingKey, new InMemoryMessageProducer(new InternalBus(), new Publication{ Topic = routingKey}) + routingKey, new InMemoryMessageProducer(new InternalBus(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = routingKey}) }, }); @@ -82,7 +82,7 @@ public void WithExternalBus(Type connectionProvider, Type transactionProvider) [Fact] public void WithCustomPolicy() { - var serviceCollection = new ServiceCollection(); + var serviceCollection = new ServiceCollection().AddLogging(); var retryPolicy = Policy.Handle().WaitAndRetry([TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150)]); var circuitBreakerPolicy = Policy.Handle().CircuitBreaker(1, TimeSpan.FromMilliseconds(500)); @@ -110,7 +110,7 @@ public void WithCustomPolicy() [Fact] public void WithScopedLifetime() { - var serviceCollection = new ServiceCollection(); + var serviceCollection = new ServiceCollection().AddLogging(); serviceCollection.AddBrighter( ).AutoFromAssemblies(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/TestDoubles/CapturingLoggerProvider.cs b/tests/Paramore.Brighter.Extensions.Tests/TestDoubles/CapturingLoggerProvider.cs new file mode 100644 index 0000000000..278ec37960 --- /dev/null +++ b/tests/Paramore.Brighter.Extensions.Tests/TestDoubles/CapturingLoggerProvider.cs @@ -0,0 +1,71 @@ +#region Licence +/* The MIT License (MIT) +Copyright © 2026 Ian Cooper + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.Logging; + +namespace Paramore.Brighter.Extensions.Tests.TestDoubles; + +/// +/// An that captures log messages so a test can assert which +/// a Brighter object actually logged through. Once disposed (as the DI +/// container does when its is disposed), logging through it throws +/// — this is what surfaces a use-after-dispose if an object is +/// still holding a reference to a factory owned by a disposed container. +/// +public sealed class CapturingLoggerProvider : ILoggerProvider +{ + private readonly List _entries = new(); + private readonly object _gate = new(); + + public bool IsDisposed { get; private set; } + + public IReadOnlyList Entries + { + get { lock (_gate) { return _entries.ToList(); } } + } + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(this); + + public void Dispose() => IsDisposed = true; + + private sealed class CapturingLogger(CapturingLoggerProvider provider) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + if (provider.IsDisposed) + throw new ObjectDisposedException(nameof(CapturingLoggerProvider)); + + lock (provider._gate) + provider._entries.Add(formatter(state, exception)); + } + } +} diff --git a/tests/Paramore.Brighter.Extensions.Tests/TransformerFactoryTests.cs b/tests/Paramore.Brighter.Extensions.Tests/TransformerFactoryTests.cs index 6459747650..60b9b517bb 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/TransformerFactoryTests.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/TransformerFactoryTests.cs @@ -14,7 +14,7 @@ public class TransformerFactoryTests public void When_resolving_a_transformer_from_the_factory() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(typeof(TestTransform),new TestTransform()); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Singleton }); var provider = collection.BuildServiceProvider(new ServiceProviderOptions{ValidateOnBuild = true}); @@ -32,7 +32,7 @@ public void When_resolving_a_transformer_from_the_factory() public void When_resolving_a_transformer_from_the_factory_async() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(typeof(TestTransform),new TestTransform()); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Singleton }); var provider = collection.BuildServiceProvider(new ServiceProviderOptions{ValidateOnBuild = true}); @@ -50,7 +50,7 @@ public void When_resolving_a_transformer_from_the_factory_async() public void When_resolving_a_missing_transformer_from_the_factory() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Singleton }); var provider = collection.BuildServiceProvider(); @@ -67,7 +67,7 @@ public void When_resolving_a_missing_transformer_from_the_factory() public void When_resolving_a_missing_transformer_from_the_factory_async() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Singleton }); var provider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_a_release_scope_disposal_throws_it_should_not_retain_the_instance.cs b/tests/Paramore.Brighter.Extensions.Tests/When_a_release_scope_disposal_throws_it_should_not_retain_the_instance.cs index e951c8e4cb..0f62bf0d27 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_a_release_scope_disposal_throws_it_should_not_retain_the_instance.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_a_release_scope_disposal_throws_it_should_not_retain_the_instance.cs @@ -15,7 +15,7 @@ public void When_a_release_scope_disposal_throws_it_should_not_retain_the_instan { // Arrange — a transient mapper resolved through a scope whose Dispose throws (as MS DI's sync scope // Dispose does for an IAsyncDisposable-only service). The scope is tracked against the instance. - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_a_scope_is_first_published_while_the_owner_is_disposing_it_should_not_leak.cs b/tests/Paramore.Brighter.Extensions.Tests/When_a_scope_is_first_published_while_the_owner_is_disposing_it_should_not_leak.cs index 753e6c03ac..cf5833a6fd 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_a_scope_is_first_published_while_the_owner_is_disposing_it_should_not_leak.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_a_scope_is_first_published_while_the_owner_is_disposing_it_should_not_leak.cs @@ -13,7 +13,7 @@ public class ScopedFirstResolutionVsDisposeRaceTests public void When_a_scope_is_first_published_while_the_owner_is_disposing_it_should_not_leak() { // Arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Scoped }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_handler_captures_the_service_provider_should_resolve_after_create.cs b/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_handler_captures_the_service_provider_should_resolve_after_create.cs index 9619df18b2..5a9944558e 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_handler_captures_the_service_provider_should_resolve_after_create.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_handler_captures_the_service_provider_should_resolve_after_create.cs @@ -11,7 +11,7 @@ public class TransientHandlerCapturedProviderTests public void When_a_transient_handler_captures_the_service_provider_should_resolve_after_create() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_mapper_resolution_throws_it_should_not_leak_a_scope.cs b/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_mapper_resolution_throws_it_should_not_leak_a_scope.cs index c1313d3a51..7ca9e8d336 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_mapper_resolution_throws_it_should_not_leak_a_scope.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_a_transient_mapper_resolution_throws_it_should_not_leak_a_scope.cs @@ -15,7 +15,7 @@ public void When_a_transient_mapper_resolution_throws_it_should_not_leak_a_scope // Arrange — the mapper is registered but its constructor dependency is NOT, so the // container throws while activating it (the most common DI misconfiguration). This is the // failure path GetTransient creates a scope for before resolution succeeds. - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_add_consumers_with_validation_should_set_consumer_owns_flag.cs b/tests/Paramore.Brighter.Extensions.Tests/When_add_consumers_with_validation_should_set_consumer_owns_flag.cs index d8b810043d..cf88ae58aa 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_add_consumers_with_validation_should_set_consumer_owns_flag.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_add_consumers_with_validation_should_set_consumer_owns_flag.cs @@ -36,7 +36,7 @@ public class AddConsumersValidationFlagTests public void When_validate_pipelines_then_add_consumers_should_set_consumer_owns_validation_true() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var brighterBuilder = services.AddBrighter(); // Act — ValidatePipelines first, then AddConsumers @@ -53,7 +53,7 @@ public void When_validate_pipelines_then_add_consumers_should_set_consumer_owns_ public void When_add_consumers_then_validate_pipelines_should_set_consumer_owns_validation_true() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Act — AddConsumers first, then ValidatePipelines (order independent) var brighterBuilder = services.AddConsumers(); @@ -69,7 +69,7 @@ public void When_add_consumers_then_validate_pipelines_should_set_consumer_owns_ public void When_add_consumers_without_validate_pipelines_should_not_register_validation_options() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); // Act — AddConsumers only, no ValidatePipelines services.AddConsumers(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_building_a_pipeline_throws_should_release_the_mapper.cs b/tests/Paramore.Brighter.Extensions.Tests/When_building_a_pipeline_throws_should_release_the_mapper.cs index d65f0595b0..f289ebcea9 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_building_a_pipeline_throws_should_release_the_mapper.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_building_a_pipeline_throws_should_release_the_mapper.cs @@ -19,7 +19,7 @@ public void When_building_a_wrap_pipeline_throws_should_release_the_mapper() var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new NullTransformerFactory()); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new NullTransformerFactory(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act — the mapper is created, then building the transforms fails, so no pipeline is ever //constructed to take ownership of it @@ -38,7 +38,7 @@ public void When_building_an_unwrap_pipeline_throws_should_release_the_mapper() var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new NullTransformerFactory()); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new NullTransformerFactory(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act Assert.Throws(() => pipelineBuilder.BuildUnwrapPipeline()); @@ -57,7 +57,7 @@ public void When_building_an_async_wrap_pipeline_throws_should_release_the_mappe mapperRegistry.RegisterAsync(); var pipelineBuilder = new TransformPipelineBuilderAsync( - mapperRegistry, new NullTransformerFactoryAsync(), InstrumentationOptions.None); + mapperRegistry, new NullTransformerFactoryAsync(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); //act Assert.Throws(() => pipelineBuilder.BuildWrapPipeline()); @@ -76,7 +76,7 @@ public void When_building_an_async_unwrap_pipeline_throws_should_release_the_map mapperRegistry.RegisterAsync(); var pipelineBuilder = new TransformPipelineBuilderAsync( - mapperRegistry, new NullTransformerFactoryAsync(), InstrumentationOptions.None); + mapperRegistry, new NullTransformerFactoryAsync(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); //act Assert.Throws(() => pipelineBuilder.BuildUnwrapPipeline()); @@ -87,7 +87,7 @@ public void When_building_an_async_unwrap_pipeline_throws_should_release_the_map private static ScopeTracker BuildScopeTracker(out IServiceProvider trackingProvider, bool async = false) { - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); if (async) collection.AddTransient(); else diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_channel_factory.cs b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_channel_factory.cs index 46ff04eaa7..a7111351dd 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_channel_factory.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_channel_factory.cs @@ -38,9 +38,9 @@ public void Should_set_scheduler_on_channel_factory_that_implements_scheduler_in { // Arrange — configure AddConsumers with an InMemoryChannelFactory (which implements IAmAChannelFactoryWithScheduler) var bus = new InternalBus(); - var channelFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + var channelFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services .AddConsumers(options => { @@ -60,7 +60,7 @@ public void Should_set_scheduler_on_channel_factory_that_implements_scheduler_in configure.ProducerRegistry = new ProducerRegistry( new Dictionary { - { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, new Publication { Topic = "test" }) } + { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); }) .AutoFromAssemblies(); @@ -81,10 +81,10 @@ public void Should_set_custom_scheduler_on_channel_factory_when_UseScheduler_con { // Arrange — configure with a custom scheduler factory var bus = new InternalBus(); - var channelFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + var channelFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var customSchedulerFactory = new StubSchedulerFactory(); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services .AddConsumers(options => { @@ -104,7 +104,7 @@ public void Should_set_custom_scheduler_on_channel_factory_when_UseScheduler_con configure.ProducerRegistry = new ProducerRegistry( new Dictionary { - { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, new Publication { Topic = "test" }) } + { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); }) .UseScheduler(customSchedulerFactory) diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_per_subscription_channel_factory.cs b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_per_subscription_channel_factory.cs index 0c7c248a0d..810ec1993c 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_per_subscription_channel_factory.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_should_set_scheduler_on_per_subscription_channel_factory.cs @@ -40,10 +40,10 @@ public void Should_set_scheduler_on_per_subscription_channel_factory() { // Arrange — one subscription uses a per-subscription channel factory var bus = new InternalBus(); - var defaultFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + var defaultFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var perSubFactory = new SchedulerAwareChannelFactory(bus); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services .AddConsumers(options => { @@ -70,7 +70,7 @@ public void Should_set_scheduler_on_per_subscription_channel_factory() configure.ProducerRegistry = new ProducerRegistry( new Dictionary { - { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, new Publication { Topic = "test" }) } + { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); }) .AutoFromAssemblies(); @@ -92,10 +92,10 @@ public void Should_set_scheduler_on_combined_channel_factory_and_propagate_to_in { // Arrange — use a CombinedChannelFactory as the default (multi-bus scenario) var bus = new InternalBus(); - var innerFactory = new InMemoryChannelFactory(bus, TimeProvider.System); + var innerFactory = new InMemoryChannelFactory(bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var combinedFactory = new CombinedChannelFactory([innerFactory]); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services .AddConsumers(options => { @@ -115,7 +115,7 @@ public void Should_set_scheduler_on_combined_channel_factory_and_propagate_to_in configure.ProducerRegistry = new ProducerRegistry( new Dictionary { - { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, new Publication { Topic = "test" }) } + { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); }) .AutoFromAssemblies(); @@ -144,7 +144,7 @@ public IAmAChannelSync CreateSyncChannel(Subscription subscription) return new Channel( subscription.ChannelName, subscription.RoutingKey, - new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System)); + new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) @@ -152,7 +152,7 @@ public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) return new ChannelAsync( subscription.ChannelName, subscription.RoutingKey, - new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System)); + new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public Task CreateAsyncChannelAsync(Subscription subscription, diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_with_non_scheduler_channel_factory_should_work.cs b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_with_non_scheduler_channel_factory_should_work.cs index 6b0cf396e6..6caacead1e 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_with_non_scheduler_channel_factory_should_work.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_building_dispatcher_with_non_scheduler_channel_factory_should_work.cs @@ -42,7 +42,7 @@ public void Should_build_dispatcher_without_errors() var bus = new InternalBus(); var channelFactory = new PlainChannelFactory(bus); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services .AddConsumers(options => { @@ -62,7 +62,7 @@ public void Should_build_dispatcher_without_errors() configure.ProducerRegistry = new ProducerRegistry( new Dictionary { - { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, new Publication { Topic = "test" }) } + { new ProducerKey("in-memory"), new InMemoryMessageProducer(bus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = "test" }) } }); }) .AutoFromAssemblies(); @@ -95,7 +95,7 @@ public IAmAChannelSync CreateSyncChannel(Subscription subscription) return new Channel( subscription.ChannelName, subscription.RoutingKey, - new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System)); + new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) @@ -103,7 +103,7 @@ public IAmAChannelAsync CreateAsyncChannel(Subscription subscription) return new ChannelAsync( subscription.ChannelName, subscription.RoutingKey, - new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System)); + new InMemoryMessageConsumer(subscription.RoutingKey, _bus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public Task CreateAsyncChannelAsync(Subscription subscription, diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_for_an_unregistered_type_it_should_return_false.cs b/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_for_an_unregistered_type_it_should_return_false.cs index 6d41d0c903..600e75609b 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_for_an_unregistered_type_it_should_return_false.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_for_an_unregistered_type_it_should_return_false.cs @@ -12,7 +12,7 @@ public class TransformPipelineBuilderHasPipelineForUnregisteredTypeTests public void When_checking_for_a_pipeline_for_an_unregistered_type_it_should_return_false() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(new MapperDisposalLog()); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); @@ -22,7 +22,7 @@ public void When_checking_for_a_pipeline_for_an_unregistered_type_it_should_retu var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); //no Register call for MinimalCommand - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory()); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act + assert — no mapper registered and no default, so no pipeline Assert.False(pipelineBuilder.HasPipeline()); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_should_not_create_a_probe_mapper.cs b/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_should_not_create_a_probe_mapper.cs index 5d8c2cbc72..8da6413f5f 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_should_not_create_a_probe_mapper.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_checking_for_a_pipeline_should_not_create_a_probe_mapper.cs @@ -15,7 +15,7 @@ public void When_checking_for_a_pipeline_should_not_create_a_probe_mapper() const int messageCount = 10; var disposals = new MapperDisposalLog(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(disposals); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); @@ -25,7 +25,7 @@ public void When_checking_for_a_pipeline_should_not_create_a_probe_mapper() var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory()); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act — HasPipeline resolves the mapper TYPE to answer "is there a pipeline?"; it no longer creates //an instance, so on the mediator's once-per-message probe there is nothing to release or leak diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_configuring_default_outbox_via_producers_configuration.cs b/tests/Paramore.Brighter.Extensions.Tests/When_configuring_default_outbox_via_producers_configuration.cs index 6fff1dda35..f54c0aae99 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_configuring_default_outbox_via_producers_configuration.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_configuring_default_outbox_via_producers_configuration.cs @@ -34,7 +34,7 @@ public class DefaultOutboxConfigurationTests public void When_custom_box_configuration_set_should_apply_to_default_outbox() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .AddProducers(config => { @@ -59,7 +59,7 @@ public void When_custom_box_configuration_set_should_apply_to_default_outbox() public void When_no_box_configuration_set_should_use_defaults() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .AddProducers(config => { diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_configuring_json_serialisation.cs b/tests/Paramore.Brighter.Extensions.Tests/When_configuring_json_serialisation.cs index 463fec8161..7ea9965512 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_configuring_json_serialisation.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_configuring_json_serialisation.cs @@ -40,7 +40,7 @@ public void Should_preserve_existing_options() var caseInsensitiveBefore = JsonSerialisationOptions.Options.PropertyNameCaseInsensitive; var writeIndentedBefore = JsonSerialisationOptions.Options.WriteIndented; - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var builder = services.AddBrighter(); // Act diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_mapper_after_the_factory_is_disposed_should_throw.cs b/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_mapper_after_the_factory_is_disposed_should_throw.cs index 71ffeed2e2..dae910617a 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_mapper_after_the_factory_is_disposed_should_throw.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_mapper_after_the_factory_is_disposed_should_throw.cs @@ -11,7 +11,7 @@ public class MapperFactoryDisposedCreateTests public void When_creating_a_mapper_after_the_factory_is_disposed_should_throw() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var provider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_request_from_a_reply_message_on_the_pump_context_it_should_not_deadlock.cs b/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_request_from_a_reply_message_on_the_pump_context_it_should_not_deadlock.cs index ee07641bfe..b52a0b3408 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_request_from_a_reply_message_on_the_pump_context_it_should_not_deadlock.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_creating_a_request_from_a_reply_message_on_the_pump_context_it_should_not_deadlock.cs @@ -100,7 +100,7 @@ private static void RunOnPumpThread(Action pump, string deadlockMessage) private static DisposeProbe BuildMediator(out OutboxProducerMediator mediator) { var probe = new DisposeProbe(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(probe); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); @@ -120,7 +120,7 @@ private static DisposeProbe BuildMediator(out OutboxProducerMediator(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); @@ -44,7 +44,7 @@ public void When_creating_transient_non_disposable_mappers_the_factory_should_no public void When_creating_a_transient_mapper_the_scope_should_survive_until_release() { // Arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_factory_holding_a_scoped_async_disposable_only_mapper_should_dispose_it.cs b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_factory_holding_a_scoped_async_disposable_only_mapper_should_dispose_it.cs index bfe107be84..f63232be94 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_factory_holding_a_scoped_async_disposable_only_mapper_should_dispose_it.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_factory_holding_a_scoped_async_disposable_only_mapper_should_dispose_it.cs @@ -15,7 +15,7 @@ public void When_disposing_a_factory_holding_a_scoped_async_disposable_only_mapp //arrange var disposals = new MapperDisposalLog(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(disposals); collection.AddScoped(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Scoped }); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_wrap_pipeline_should_release_the_transient_disposable_mapper.cs b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_wrap_pipeline_should_release_the_transient_disposable_mapper.cs index 8554b06ad6..2d26b9c8d5 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_wrap_pipeline_should_release_the_transient_disposable_mapper.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_a_wrap_pipeline_should_release_the_transient_disposable_mapper.cs @@ -14,7 +14,7 @@ public void When_disposing_a_wrap_pipeline_should_release_the_transient_disposab //arrange var disposals = new MapperDisposalLog(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(disposals); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); @@ -24,7 +24,7 @@ public void When_disposing_a_wrap_pipeline_should_release_the_transient_disposab var mapperRegistry = new MessageMapperRegistry(mapperFactory, null); mapperRegistry.Register(); - var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory()); + var pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, new EmptyMessageTransformerFactory(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act using (pipelineBuilder.BuildWrapPipeline()) diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_and_a_scope_disposal_throws_should_still_dispose_remaining_scopes.cs b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_and_a_scope_disposal_throws_should_still_dispose_remaining_scopes.cs index 173a932442..bdc7dab4f6 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_disposing_and_a_scope_disposal_throws_should_still_dispose_remaining_scopes.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_disposing_and_a_scope_disposal_throws_should_still_dispose_remaining_scopes.cs @@ -21,7 +21,7 @@ public void When_disposing_and_a_scope_disposal_throws_should_still_dispose_rema // only thing that drains them. var disposalAttempts = new StrongBox(0); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_no_scheduler_configured_should_default_to_InMemorySchedulerFactory.cs b/tests/Paramore.Brighter.Extensions.Tests/When_no_scheduler_configured_should_default_to_InMemorySchedulerFactory.cs index 8cde9a0c53..2b71472fb7 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_no_scheduler_configured_should_default_to_InMemorySchedulerFactory.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_no_scheduler_configured_should_default_to_InMemorySchedulerFactory.cs @@ -32,7 +32,7 @@ public class When_no_scheduler_configured_should_default_to_InMemorySchedulerFac public void Should_resolve_InMemorySchedulerFactory_as_default() { // Arrange — AddBrighter with no explicit UseScheduler or UseMessageScheduler - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); @@ -48,7 +48,7 @@ public void Should_resolve_InMemorySchedulerFactory_as_default() public void Should_resolve_IAmAMessageScheduler_from_default_factory() { // Arrange — AddBrighter with no explicit UseScheduler - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); @@ -64,7 +64,7 @@ public void Should_resolve_IAmAMessageScheduler_from_default_factory() public void Should_resolve_IAmARequestSchedulerFactory_as_default() { // Arrange — AddBrighter with no explicit UseScheduler - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter(); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_probing_transformer_resolvability_should_match_registered_service_types.cs b/tests/Paramore.Brighter.Extensions.Tests/When_probing_transformer_resolvability_should_match_registered_service_types.cs index 02dc7ea190..81189d3540 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_probing_transformer_resolvability_should_match_registered_service_types.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_probing_transformer_resolvability_should_match_registered_service_types.cs @@ -37,7 +37,7 @@ public void When_probing_transformer_resolvability_should_match_registered_servi { // Arrange — a service collection with one transformer registered; a second transformer // type whose constructor throws is also registered to prove the probe never instantiates. - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddTransient(typeof(CompressPayloadTransformer)); services.AddTransient(typeof(ThrowOnConstructTransformer)); @@ -58,7 +58,7 @@ public void When_probing_transformer_resolvability_should_match_registered_servi public void When_probing_an_empty_service_collection_should_not_resolve_any_transformer() { // Arrange — no transformers registered - var probe = new ServiceCollectionTransformerResolvabilityProbe(new ServiceCollection()); + var probe = new ServiceCollectionTransformerResolvabilityProbe(new ServiceCollection().AddLogging()); // Act + Assert — nothing resolves Assert.False(probe.Resolves(typeof(CompressPayloadTransformer))); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_scoped_mapper_it_should_stay_usable_for_later_resolutions.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_scoped_mapper_it_should_stay_usable_for_later_resolutions.cs index 269e9ede51..2c4fc31bac 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_scoped_mapper_it_should_stay_usable_for_later_resolutions.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_scoped_mapper_it_should_stay_usable_for_later_resolutions.cs @@ -17,7 +17,7 @@ public void When_releasing_a_scoped_mapper_it_should_stay_usable_for_later_resol // disposing the cached instance would hand message #2 a disposed mapper. var disposals = new DisposalLog(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(disposals); collection.AddScoped(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Scoped }); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_async_disposable_only_mapper_should_dispose_it.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_async_disposable_only_mapper_should_dispose_it.cs index 7b37c1d95e..dff40cd6c2 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_async_disposable_only_mapper_should_dispose_it.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_async_disposable_only_mapper_should_dispose_it.cs @@ -44,7 +44,7 @@ public void When_disposing_a_factory_holding_a_transient_async_disposable_only_m private static IServiceProvider BuildProvider(MapperDisposalLog disposals) { - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(disposals); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_disposable_handler_should_dispose_it_once.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_disposable_handler_should_dispose_it_once.cs index f2494d4507..e69f94c57e 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_disposable_handler_should_dispose_it_once.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_disposable_handler_should_dispose_it_once.cs @@ -12,7 +12,7 @@ public class HandlerFactoryReleaseDisposalTests public void When_releasing_a_transient_disposable_handler_should_dispose_it_once() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Transient }); var provider = collection.BuildServiceProvider(); @@ -34,7 +34,7 @@ public void When_releasing_a_transient_disposable_handler_should_dispose_it_once public void When_releasing_a_scoped_disposable_handler_should_dispose_it_once() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddSingleton(new BrighterOptions { HandlerLifetime = ServiceLifetime.Scoped }); var provider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_async_the_factory_should_not_retain_it.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_async_the_factory_should_not_retain_it.cs index 20514d846a..73acea3d60 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_async_the_factory_should_not_retain_it.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_async_the_factory_should_not_retain_it.cs @@ -11,7 +11,7 @@ public class ServiceProviderTransformerFactoryAsyncLeakTests public void When_releasing_a_transient_transformer_async_the_factory_should_not_retain_it() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Transient }); var provider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_the_factory_should_not_retain_it.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_the_factory_should_not_retain_it.cs index 972e4fc830..7466d64c18 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_the_factory_should_not_retain_it.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_a_transient_transformer_the_factory_should_not_retain_it.cs @@ -11,7 +11,7 @@ public class ServiceProviderTransformerFactoryLeakTests public void When_releasing_a_transient_transformer_the_factory_should_not_retain_it() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { TransformerLifetime = ServiceLifetime.Transient }); var provider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_an_async_disposable_mapper_on_the_pump_context_it_should_not_deadlock.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_an_async_disposable_mapper_on_the_pump_context_it_should_not_deadlock.cs index a2099b6bc8..444808d21f 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_an_async_disposable_mapper_on_the_pump_context_it_should_not_deadlock.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_an_async_disposable_mapper_on_the_pump_context_it_should_not_deadlock.cs @@ -93,7 +93,7 @@ private static void RunOnPumpThread(Action pump, string deadlockMessage) private static DisposeProbe BuildPipelineFactory(out TransformPipelineBuilderAsync builder) { var probe = new DisposeProbe(); - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(probe); collection.AddTransient(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); @@ -104,7 +104,7 @@ private static DisposeProbe BuildPipelineFactory(out TransformPipelineBuilderAsy mapperRegistry.RegisterAsync(); builder = new TransformPipelineBuilderAsync( - mapperRegistry, new NoOpTransformerFactoryAsync(), InstrumentationOptions.None); + mapperRegistry, new NoOpTransformerFactoryAsync(), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); return probe; } diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_one_lease_of_a_shared_mapper_the_other_resolution_stays_usable.cs b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_one_lease_of_a_shared_mapper_the_other_resolution_stays_usable.cs index e3883271d7..f7824a5ac0 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_releasing_one_lease_of_a_shared_mapper_the_other_resolution_stays_usable.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_releasing_one_lease_of_a_shared_mapper_the_other_resolution_stays_usable.cs @@ -18,7 +18,7 @@ public void When_releasing_one_lease_of_a_shared_mapper_the_other_resolution_sta // instance (the pre-redesign model) could not tell the two resolutions apart, so releasing one could // pop and dispose the other still-live resolution's scope — a use-after-dispose. Keying on the lease // fixes that: each Create returns its own lease over its own scope. - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_scheduler_explicitly_configured_should_override_default.cs b/tests/Paramore.Brighter.Extensions.Tests/When_scheduler_explicitly_configured_should_override_default.cs index 5b0f1cf3ff..321f29d4b1 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_scheduler_explicitly_configured_should_override_default.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_scheduler_explicitly_configured_should_override_default.cs @@ -37,7 +37,7 @@ public void Should_resolve_custom_factory_instead_of_InMemorySchedulerFactory() // Arrange — configure a custom scheduler factory via UseScheduler var customFactory = new StubSchedulerFactory(); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .UseScheduler(customFactory); var provider = services.BuildServiceProvider(); @@ -57,7 +57,7 @@ public void Should_resolve_scheduler_from_custom_factory() // Arrange — configure a custom scheduler factory via UseScheduler var customFactory = new StubSchedulerFactory(); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .UseScheduler(customFactory); var provider = services.BuildServiceProvider(); @@ -76,7 +76,7 @@ public void Should_resolve_custom_request_scheduler_factory() // Arrange — configure a custom scheduler factory via UseScheduler var customFactory = new StubSchedulerFactory(); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddBrighter() .UseScheduler(customFactory); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_has_warnings_should_log_them.cs b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_has_warnings_should_log_them.cs index 7f70ff181c..aaeb56fa75 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_has_warnings_should_log_them.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_has_warnings_should_log_them.cs @@ -48,7 +48,7 @@ public async Task When_service_activator_has_warnings_should_log_them_at_warning var dispatcher = new SpyDispatcher(actionLog); var validator = SpyPipelineValidator.WithWarningsOnly(actionLog, warning1, warning2); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_single_constructor_should_resolve_optional_deps.cs b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_single_constructor_should_resolve_optional_deps.cs index 9cef83c75b..dbdeab7e2b 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_single_constructor_should_resolve_optional_deps.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_single_constructor_should_resolve_optional_deps.cs @@ -47,7 +47,7 @@ public async Task When_consumer_owns_validation_and_validator_registered_should_ var validator = SpyPipelineValidator.WithNoErrors(actionLog); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); @@ -72,7 +72,7 @@ public async Task When_consumer_owns_validation_and_validator_not_registered_sho var actionLog = new List(); var dispatcher = new SpyDispatcher(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var provider = services.BuildServiceProvider(); var options = Options.Create(new BrighterPipelineValidationOptions { ConsumerOwnsValidation = true }); @@ -95,7 +95,7 @@ public async Task When_consumer_does_not_own_validation_should_go_straight_to_re var dispatcher = new SpyDispatcher(actionLog); var validator = SpyPipelineValidator.WithNoErrors(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_starts_with_validator_should_validate_before_receive.cs b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_starts_with_validator_should_validate_before_receive.cs index c24889e507..6a5e4f64b6 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_starts_with_validator_should_validate_before_receive.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_starts_with_validator_should_validate_before_receive.cs @@ -47,7 +47,7 @@ public async Task When_validator_registered_should_validate_before_receive() var validator = SpyPipelineValidator.WithNoErrors(actionLog); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); @@ -72,7 +72,7 @@ public async Task When_validator_not_registered_should_go_straight_to_receive() var actionLog = new List(); var dispatcher = new SpyDispatcher(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); var provider = services.BuildServiceProvider(); var options = Options.Create(new BrighterPipelineValidationOptions { ConsumerOwnsValidation = false }); @@ -97,7 +97,7 @@ public async Task When_validation_has_errors_should_not_call_receive() var validator = SpyPipelineValidator.WithErrors(actionLog, error); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_throw_on_error_false_should_log_not_throw.cs b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_throw_on_error_false_should_log_not_throw.cs index a4b7062970..948cc596f1 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_throw_on_error_false_should_log_not_throw.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_service_activator_throw_on_error_false_should_log_not_throw.cs @@ -49,7 +49,7 @@ public async Task When_throw_on_error_false_and_errors_should_log_and_still_rece var validator = SpyPipelineValidator.WithErrors(actionLog, error); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); @@ -81,7 +81,7 @@ public async Task When_throw_on_error_true_and_errors_should_throw_and_not_recei var validator = SpyPipelineValidator.WithErrors(actionLog, error); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); @@ -109,7 +109,7 @@ public async Task When_throw_on_error_false_and_no_errors_should_receive_normall var validator = SpyPipelineValidator.WithNoErrors(actionLog); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); @@ -142,7 +142,7 @@ public async Task When_throw_on_error_false_should_still_log_warnings() var validator = new SpyPipelineValidator(new PipelineValidationResult([error], [warning]), actionLog); var diagnosticWriter = new SpyPipelineDiagnosticWriter(actionLog); - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddSingleton(validator); services.AddSingleton(diagnosticWriter); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_the_same_transient_mapper_is_resolved_twice_before_release_should_dispose_every_scope.cs b/tests/Paramore.Brighter.Extensions.Tests/When_the_same_transient_mapper_is_resolved_twice_before_release_should_dispose_every_scope.cs index d0ffc2650d..e1c5022a67 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_the_same_transient_mapper_is_resolved_twice_before_release_should_dispose_every_scope.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_the_same_transient_mapper_is_resolved_twice_before_release_should_dispose_every_scope.cs @@ -16,7 +16,7 @@ public void When_the_same_transient_mapper_is_resolved_twice_before_release_shou // reference every resolution, while MapperLifetime is configured Transient. Each Create // opens its own transient IServiceScope, but both scopes are keyed by the one shared // instance in the factory's reference-keyed tracking dictionary. - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_two_handlers_share_a_lifetime_the_scope_follows_the_handler_lifetime.cs b/tests/Paramore.Brighter.Extensions.Tests/When_two_handlers_share_a_lifetime_the_scope_follows_the_handler_lifetime.cs index 95523240d3..ae4abe1d3a 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_two_handlers_share_a_lifetime_the_scope_follows_the_handler_lifetime.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_two_handlers_share_a_lifetime_the_scope_follows_the_handler_lifetime.cs @@ -22,7 +22,7 @@ public class HandlerLifetimeCallChainScopeTests public void When_two_handlers_share_a_lifetime_the_scoped_lifetime_shares_a_dependency() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddTransient(); collection.AddTransient(); @@ -44,7 +44,7 @@ public void When_two_handlers_share_a_lifetime_the_scoped_lifetime_shares_a_depe public void When_two_handlers_share_a_lifetime_the_transient_lifetime_isolates_a_dependency() { //arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddTransient(); collection.AddTransient(); @@ -67,7 +67,7 @@ public void When_transient_handlers_opt_out_of_scope_isolation_they_share_a_depe { //arrange — Transient handlers, but IsolateHandlerScope turned off (the pre-#4254 model): //the pipeline shares one DI scope, so a scoped dependency is one instance across the chain - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddTransient(); collection.AddTransient(); @@ -96,7 +96,7 @@ public void When_a_transient_handler_pipeline_is_released_it_disposes_every_scop { //arrange — count scopes created and disposed so we can tell "restored the old scoping" apart from //"restored the old leak": in either mode, releasing the pipeline must dispose exactly what it created - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddTransient(); collection.AddTransient(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_two_threads_first_resolve_a_scoped_mapper_concurrently_it_should_not_leak_a_scope.cs b/tests/Paramore.Brighter.Extensions.Tests/When_two_threads_first_resolve_a_scoped_mapper_concurrently_it_should_not_leak_a_scope.cs index 9f673a3d81..2ac6cda071 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_two_threads_first_resolve_a_scoped_mapper_concurrently_it_should_not_leak_a_scope.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_two_threads_first_resolve_a_scoped_mapper_concurrently_it_should_not_leak_a_scope.cs @@ -13,7 +13,7 @@ public class ScopedMapperFirstResolutionRaceTests public void When_two_threads_first_resolve_a_scoped_mapper_concurrently_it_should_not_leak_a_scope() { // Arrange - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddScoped(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Scoped }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_two_transient_scopes_are_value_equal_releasing_one_should_not_reclaim_the_other.cs b/tests/Paramore.Brighter.Extensions.Tests/When_two_transient_scopes_are_value_equal_releasing_one_should_not_reclaim_the_other.cs index a4f942cdc3..8852803abf 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_two_transient_scopes_are_value_equal_releasing_one_should_not_reclaim_the_other.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_two_transient_scopes_are_value_equal_releasing_one_should_not_reclaim_the_other.cs @@ -25,7 +25,7 @@ public void When_two_transient_scopes_are_value_equal_releasing_one_should_not_r // Arrange — a SINGLETON mapper resolved under a Transient MapperLifetime, so each Create opens its own // scope over the one shared instance. The scope factory hands back scopes that are VALUE-equal (every // instance Equals every other, same hash) rather than reference-distinct. - var collection = new ServiceCollection(); + var collection = new ServiceCollection().AddLogging(); collection.AddSingleton(); collection.AddSingleton(new BrighterOptions { MapperLifetime = ServiceLifetime.Transient }); var rootProvider = collection.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Extensions.Tests/When_validate_pipelines_with_consumers_should_receive_subscriptions.cs b/tests/Paramore.Brighter.Extensions.Tests/When_validate_pipelines_with_consumers_should_receive_subscriptions.cs index dabc8d72f3..00dab3cc2a 100644 --- a/tests/Paramore.Brighter.Extensions.Tests/When_validate_pipelines_with_consumers_should_receive_subscriptions.cs +++ b/tests/Paramore.Brighter.Extensions.Tests/When_validate_pipelines_with_consumers_should_receive_subscriptions.cs @@ -40,7 +40,7 @@ public class ValidatePipelinesWithConsumersTests public void When_validate_pipelines_with_consumers_should_detect_missing_handler() { // Arrange — set up a subscription for a request type with no handler registered - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddConsumers(options => { options.Subscriptions = @@ -69,7 +69,7 @@ public void When_validate_pipelines_with_consumers_should_detect_missing_handler public void When_add_consumers_should_register_consumer_validation_specs() { // Arrange - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddConsumers(); var provider = services.BuildServiceProvider(); @@ -87,7 +87,7 @@ public void When_add_consumers_without_validate_pipelines_the_unwrap_transform_s // Arrange — AddConsumers WITHOUT ValidatePipelines: the transformer-resolvability probe is never // registered, so the unwrap-transform spec must be inert (yield nothing) and must not throw when // resolved and evaluated. - var services = new ServiceCollection(); + var services = new ServiceCollection().AddLogging(); services.AddConsumers(); var provider = services.BuildServiceProvider(); diff --git a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullMessageGatewayProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullMessageGatewayProvider.cs index d2cb30535d..98f9e7c703 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullMessageGatewayProvider.cs @@ -62,7 +62,7 @@ public GcpPullMessageGatewayProvider() cfg.EmulatorDetection = EmulatorDetection.EmulatorOrProduction; }, }; - _channelFactory = new GcpPubSubChannelFactory(_connection); + _channelFactory = new GcpPubSubChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public RoutingKey GetOrCreateRoutingKey([CallerMemberName] string? testName = null) diff --git a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullOrderingMessageGatewayProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullOrderingMessageGatewayProvider.cs index 0b96f55fc5..e4b514ba53 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullOrderingMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpPullOrderingMessageGatewayProvider.cs @@ -67,7 +67,7 @@ public GcpPullOrderingMessageGatewayProvider() cfg.EmulatorDetection = EmulatorDetection.EmulatorOrProduction; }, }; - _channelFactory = new GcpPubSubChannelFactory(_connection); + _channelFactory = new GcpPubSubChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public RoutingKey GetOrCreateRoutingKey([CallerMemberName] string? testName = null) diff --git a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamMessageGatewayProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamMessageGatewayProvider.cs index 7bd8b547b4..1706a7b97f 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamMessageGatewayProvider.cs @@ -62,7 +62,7 @@ public GcpStreamMessageGatewayProvider() cfg.EmulatorDetection = EmulatorDetection.EmulatorOrProduction; }, }; - _channelFactory = new GcpPubSubChannelFactory(_connection); + _channelFactory = new GcpPubSubChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public RoutingKey GetOrCreateRoutingKey([CallerMemberName] string? testName = null) diff --git a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamOrderingMessageGatewayProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamOrderingMessageGatewayProvider.cs index efd3b1df31..34beadd797 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamOrderingMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/MessagingGateway/GcpStreamOrderingMessageGatewayProvider.cs @@ -67,7 +67,7 @@ public GcpStreamOrderingMessageGatewayProvider() cfg.EmulatorDetection = EmulatorDetection.EmulatorOrProduction; }, }; - _channelFactory = new GcpPubSubChannelFactory(_connection); + _channelFactory = new GcpPubSubChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public RoutingKey GetOrCreateRoutingKey([CallerMemberName] string? testName = null) diff --git a/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerBinary/SpannerBinaryOutboxProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerBinary/SpannerBinaryOutboxProvider.cs index ffc93df077..89ca6ab407 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerBinary/SpannerBinaryOutboxProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerBinary/SpannerBinaryOutboxProvider.cs @@ -25,12 +25,12 @@ public class SpannerBinaryOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxP public IAmAnOutboxSync CreateOutbox() { - return new SpannerOutbox(_configuration); + return new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new SpannerOutbox(_configuration); + return new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -76,13 +76,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new SpannerOutbox(_configuration); + var outbox = new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new SpannerOutbox(_configuration); + var outbox = new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerText/SpannerTextOutboxProvider.cs b/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerText/SpannerTextOutboxProvider.cs index 39bb9e1cb0..931d65bb00 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerText/SpannerTextOutboxProvider.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Outbox/SpannerText/SpannerTextOutboxProvider.cs @@ -25,12 +25,12 @@ public class SpannerTextOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxPro public IAmAnOutboxSync CreateOutbox() { - return new SpannerOutbox(_configuration); + return new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new SpannerOutbox(_configuration); + return new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -76,13 +76,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new SpannerOutbox(_configuration); + var outbox = new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new SpannerOutbox(_configuration); + var outbox = new SpannerOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/Legacy/When_spanner_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/Legacy/When_spanner_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs index 197239047a..b49e450c97 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/Legacy/When_spanner_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/Legacy/When_spanner_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs @@ -203,10 +203,10 @@ private SpannerOutbox OutboxFor(string tableName) _connectionString, databaseName: "brightertests", outBoxTableName: tableName, - binaryMessagePayload: false)); + binaryMessagePayload: false), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private IAmAnInboxSync InboxFor(string tableName) - => new SpannerInboxAsync(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName)); + => new SpannerInboxAsync(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private void ExecuteDdl(string ddl) { diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_history_it_should_no_op_at_v_latest_and_throw_on_out_of_sync_installed_version.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_history_it_should_no_op_at_v_latest_and_throw_on_out_of_sync_installed_version.cs index 90540e9093..8a01ea6ada 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_history_it_should_no_op_at_v_latest_and_throw_on_out_of_sync_installed_version.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_history_it_should_no_op_at_v_latest_and_throw_on_out_of_sync_installed_version.cs @@ -58,7 +58,7 @@ public SpannerOutboxNormalPathTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), @@ -224,7 +224,7 @@ public SpannerInboxNormalPathTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerInboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_no_history_it_should_throw_if_discriminator_absent_and_stamp_v_latest_if_present.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_no_history_it_should_throw_if_discriminator_absent_and_stamp_v_latest_if_present.cs index a5eaf8a5e8..68264a4421 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_no_history_it_should_throw_if_discriminator_absent_and_stamp_v_latest_if_present.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_existing_table_has_no_history_it_should_throw_if_discriminator_absent_and_stamp_v_latest_if_present.cs @@ -52,7 +52,7 @@ public SpannerOutboxBootstrapDiscriminatorTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), @@ -175,7 +175,7 @@ public SpannerInboxBootstrapDiscriminatorTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerInboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_fresh_install_runs_it_should_create_table_and_stamp_v_latest_and_skip_duplicate_history_insert.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_fresh_install_runs_it_should_create_table_and_stamp_v_latest_and_skip_duplicate_history_insert.cs index 9d50596db9..a89923cf13 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_fresh_install_runs_it_should_create_table_and_stamp_v_latest_and_skip_duplicate_history_insert.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_fresh_install_runs_it_should_create_table_and_stamp_v_latest_and_skip_duplicate_history_insert.cs @@ -47,7 +47,7 @@ public SpannerOutboxFreshInstallTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), @@ -147,7 +147,7 @@ public SpannerInboxFreshInstallTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerInboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index cfbc9ecf06..f3727621ab 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -26,7 +26,7 @@ public When_spanner_inbox_provisioner_finds_existing_table_without_history_it_sh var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerInboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs index 178efab7c2..77fd57f3e5 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs @@ -25,7 +25,7 @@ public InboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerInboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index db9ec4e78b..6d7b45fb95 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -26,7 +26,7 @@ public When_spanner_outbox_provisioner_finds_existing_table_without_history_it_s var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs index 2a6602a247..d57e3d4e0f 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs @@ -25,7 +25,7 @@ public OutboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs index 38a2c29326..afe03225dc 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs @@ -54,7 +54,7 @@ public async Task Should_throw_when_existing_outbox_body_is_string_and_provision new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), config, - new SpannerBoxMigrationRunner(config)); + new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -75,7 +75,7 @@ public async Task Should_throw_when_existing_outbox_body_is_bytes_and_provisione new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), config, - new SpannerBoxMigrationRunner(config)); + new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_is_called_with_an_unsafe_table_name_it_should_throw.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_is_called_with_an_unsafe_table_name_it_should_throw.cs index 3a107808f3..2ef515e367 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_is_called_with_an_unsafe_table_name_it_should_throw.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_is_called_with_an_unsafe_table_name_it_should_throw.cs @@ -53,7 +53,7 @@ public async Task When_spanner_runner_migrates_an_outbox_with_an_unsafe_table_na { //Arrange var config = new RelationalDatabaseConfiguration("Data Source=ignored;"); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var tableState = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert @@ -70,7 +70,7 @@ public async Task When_spanner_runner_migrates_an_inbox_with_an_unsafe_table_nam { //Arrange var config = new RelationalDatabaseConfiguration("Data Source=ignored;"); - var runner = new SpannerBoxMigrationRunner(config); + var runner = new SpannerBoxMigrationRunner(config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var tableState = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_bootstrap_callers_against_an_existing_table_neither_should_throw.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_bootstrap_callers_against_an_existing_table_neither_should_throw.cs index afdfb38c96..b284fd0789 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_bootstrap_callers_against_an_existing_table_neither_should_throw.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_bootstrap_callers_against_an_existing_table_neither_should_throw.cs @@ -75,12 +75,12 @@ public async Task Should_not_throw_when_two_concurrent_bootstrap_callers_race_on new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), _config, - new SpannerBoxMigrationRunner(_config)); + new SpannerBoxMigrationRunner(_config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var provisionerB = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), _config, - new SpannerBoxMigrationRunner(_config)); + new SpannerBoxMigrationRunner(_config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); //Act var act = async () => await Task.WhenAll( diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_fresh_installers_neither_should_throw.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_fresh_installers_neither_should_throw.cs index bdb1ed1846..a3e87c5f4c 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_fresh_installers_neither_should_throw.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/BoxProvisioning/When_spanner_runner_runs_two_concurrent_fresh_installers_neither_should_throw.cs @@ -63,12 +63,12 @@ public async Task Should_not_throw_when_two_concurrent_fresh_installers_race_on_ new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), _config, - new SpannerBoxMigrationRunner(_config)); + new SpannerBoxMigrationRunner(_config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var provisionerB = new SpannerOutboxProvisioner( new SpannerBoxDetectionHelper(), new SpannerPayloadModeValidator(), _config, - new SpannerBoxMigrationRunner(_config)); + new SpannerBoxMigrationRunner(_config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); //Act var act = async () => await Task.WhenAll( diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxAsyncTest.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxAsyncTest.cs index 1acb53953a..a8c7e90823 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxAsyncTest.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxAsyncTest.cs @@ -15,7 +15,7 @@ public class SpannerInboxAsyncTest : RelationalDatabaseInboxAsyncTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new SpannerInboxAsync(configuration); + return new SpannerInboxAsync(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override async Task CreateInboxTableAsync(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxTest.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxTest.cs index edffe3a067..ab3ea19f0d 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxTest.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/SpannerInboxTest.cs @@ -14,7 +14,7 @@ public class SpannerInboxTest : RelationalDatabaseInboxTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new SpannerInboxAsync(configuration); + return new SpannerInboxAsync(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override void CreateInboxTable(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/When_spanner_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/When_spanner_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs index 68d1b9e086..29c095015a 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/When_spanner_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Spanner/Inbox/When_spanner_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs @@ -24,7 +24,7 @@ protected override void BeforeEachTest() _configuration = new RelationalDatabaseConfiguration( connectionString, inboxTableName: $"{Const.TablePrefix}{Uuid.New():N}"); - _inbox = new SpannerInboxAsync(_configuration); + _inbox = new SpannerInboxAsync(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); base.BeforeEachTest(); } diff --git a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs index c086a63af6..2585cf6f70 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_creating_luggagestore_missing_parameters.cs @@ -15,7 +15,7 @@ public void When_creating_luggagestore_missing_projectId() //arrange var exception = Assert.Throws(() => { - var gcs = new GcsLuggageStore(new GcsLuggageOptions()); + var gcs = new GcsLuggageStore(new GcsLuggageOptions(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); gcs.EnsureStoreExists(); }); @@ -34,7 +34,7 @@ public void When_creating_luggagestore_missing_bucketName(string? bucketName) { ProjectId = Guid.NewGuid().ToString(), BucketName = bucketName! - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); gcs.EnsureStoreExists(); }); @@ -47,7 +47,7 @@ public async Task When_creating_luggagestore_missing_projectId_async() //arrange var exception = await Assert.ThrowsAsync(async () => { - var gcs = new GcsLuggageStore(new GcsLuggageOptions()); + var gcs = new GcsLuggageStore(new GcsLuggageOptions(), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await gcs.EnsureStoreExistsAsync(); }); @@ -66,7 +66,7 @@ public async Task When_creating_luggagestore_missing_bucketName_async(string? bu { ProjectId = Guid.NewGuid().ToString(), BucketName = bucketName! - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await gcs.EnsureStoreExistsAsync(); }); diff --git a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_unwrapping_a_large_message.cs index c5fb1a6496..aecd783d73 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_unwrapping_a_large_message.cs @@ -39,14 +39,14 @@ public LargeMessagePaylodUnwrapTests() BucketName = _bucketName }; - _luggageStore = new GcsLuggageStore(_luggageStoreOptions); + _luggageStore = new GcsLuggageStore(_luggageStoreOptions, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _luggageStore.EnsureStoreExists(); var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.None); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); } [Fact] diff --git a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_uploading_luggage_to_S3.cs b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_uploading_luggage_to_S3.cs index c7f6122700..ceff9d30e6 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_uploading_luggage_to_S3.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_uploading_luggage_to_S3.cs @@ -24,7 +24,7 @@ public LuggageUploadTests() BucketName = _bucketName }; - _luggageStore = new GcsLuggageStore(_luggageStoreOptions); + _luggageStore = new GcsLuggageStore(_luggageStoreOptions, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } diff --git a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_validating_a_luggage_store_exists.cs b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_validating_a_luggage_store_exists.cs index d933ce0e91..fd83440cd8 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_validating_a_luggage_store_exists.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_validating_a_luggage_store_exists.cs @@ -21,7 +21,7 @@ public async Task When_checking_store_that_exists() Credential = GatewayFactory.GetCredential() }; - var luggageStore = new GcsLuggageStore(options); + var luggageStore = new GcsLuggageStore(options, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await luggageStore.EnsureStoreExistsAsync(); // act @@ -48,7 +48,7 @@ public async Task When_checking_store_that_does_not_exist() Credential = GatewayFactory.GetCredential() }; - var luggageStore = new GcsLuggageStore(options); + var luggageStore = new GcsLuggageStore(options, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await luggageStore.EnsureStoreExistsAsync(); }); diff --git a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_wrapping_a_large_message.cs index 9b27c33216..e9c831be47 100644 --- a/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.Gcp.Tests/Transformers/When_wrapping_a_large_message.cs @@ -42,14 +42,14 @@ public LargeMessagePayloadWrapTests() BucketName = _bucketName }; - _luggageStore = new GcsLuggageStore(_luggageStoreOptions); + _luggageStore = new GcsLuggageStore(_luggageStoreOptions, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _luggageStore.EnsureStoreExists(); var transformerFactoryAsync = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, InstrumentationOptions.None); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.None); } [Fact] diff --git a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message.cs b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message.cs index 9cbee61f89..2a98d3a769 100644 --- a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message.cs +++ b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message.cs @@ -47,7 +47,7 @@ public HangfireSchedulerMessageTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -67,7 +67,7 @@ public HangfireSchedulerMessageTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); GlobalConfiguration.Configuration @@ -91,8 +91,8 @@ public HangfireSchedulerMessageTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterActivator.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message_async.cs b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message_async.cs index 6f41bfbb63..4167603ebb 100644 --- a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message_async.cs +++ b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_message_async.cs @@ -54,7 +54,7 @@ public HangfireSchedulerMessageAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -74,7 +74,7 @@ public HangfireSchedulerMessageAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); GlobalConfiguration.Configuration @@ -97,8 +97,8 @@ public HangfireSchedulerMessageAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterActivator.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request.cs b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request.cs index 2fdfa9b9b2..56bea46758 100644 --- a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request.cs +++ b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request.cs @@ -48,7 +48,7 @@ public HangfireSchedulerRequestTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent)}) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent)}) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -68,7 +68,7 @@ public HangfireSchedulerRequestTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); GlobalConfiguration.Configuration @@ -91,8 +91,8 @@ public HangfireSchedulerRequestTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterActivator.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request_async.cs b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request_async.cs index 1aa3ae4989..889d68b80e 100644 --- a/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request_async.cs +++ b/tests/Paramore.Brighter.Hangfire.Tests/When_scheduling_a_request_async.cs @@ -56,7 +56,7 @@ public HangfireSchedulerRequestAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) } ) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) } ) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -76,7 +76,7 @@ public HangfireSchedulerRequestAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); GlobalConfiguration.Configuration @@ -99,8 +99,8 @@ public HangfireSchedulerRequestAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterActivator.Processor = _processor; } diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_off_should_write_and_confirm_synchronously.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_off_should_write_and_confirm_synchronously.cs index a1e840234e..dc30cbcc8e 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_off_should_write_and_confirm_synchronously.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_off_should_write_and_confirm_synchronously.cs @@ -41,7 +41,7 @@ public void When_async_confirmation_is_off_should_write_and_confirm_synchronousl new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = false }; @@ -70,7 +70,7 @@ public async Task When_async_confirmation_is_off_with_send_async_should_write_an new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All); + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var confirmations = new List(); producer.OnMessagePublished += confirmations.Add; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_enqueue_and_pump.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_enqueue_and_pump.cs index 151c2d4b1d..d7ad2052bc 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_enqueue_and_pump.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_enqueue_and_pump.cs @@ -42,7 +42,7 @@ public async Task When_async_confirmation_is_on_should_not_write_bus_before_retu new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; @@ -72,7 +72,7 @@ public async Task When_async_confirmation_is_on_should_drain_in_fifo_enqueue_ord const string topic = "test_topic_fifo"; const int count = 5; var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_fan_out_a_batch.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_fan_out_a_batch.cs index e3148ff486..cc8258d021 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_fan_out_a_batch.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_async_confirmation_is_on_should_fan_out_a_batch.cs @@ -39,7 +39,7 @@ public async Task When_async_confirmation_is_on_should_fan_out_a_batch() const string topic = "test_topic_batch_fanout"; const int batchSize = 3; var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_concurrent_first_enqueuers_should_start_one_worker.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_concurrent_first_enqueuers_should_start_one_worker.cs index 15b0d6d0fa..49f54ce0ae 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_concurrent_first_enqueuers_should_start_one_worker.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_concurrent_first_enqueuers_should_start_one_worker.cs @@ -39,7 +39,7 @@ public async Task When_concurrent_first_enqueuers_should_start_one_worker() const string topic = "test_topic_concurrent_start"; const int threadCount = 20; var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_disposing_should_drain_all_confirmations_before_returning.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_disposing_should_drain_all_confirmations_before_returning.cs index caab289bd1..11f885af80 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_disposing_should_drain_all_confirmations_before_returning.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_disposing_should_drain_all_confirmations_before_returning.cs @@ -43,7 +43,7 @@ public async Task When_disposing_should_drain_all_confirmations_before_returning var gate = new SemaphoreSlim(0, messageCount); var confirmationCount = 0; - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_publish_failure_predicate_returns_true_should_raise_failure.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_publish_failure_predicate_returns_true_should_raise_failure.cs index dc344d52b0..5ecaff3319 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_publish_failure_predicate_returns_true_should_raise_failure.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_publish_failure_predicate_returns_true_should_raise_failure.cs @@ -40,7 +40,7 @@ public void When_publish_failure_predicate_returns_true_should_raise_failure() new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { PublishFailurePredicate = _ => true }; @@ -69,7 +69,7 @@ public void When_publish_failure_predicate_is_null_should_succeed() new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All); + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var confirmations = new List(); producer.OnMessagePublished += confirmations.Add; @@ -93,7 +93,7 @@ public void When_publish_failure_predicate_returns_false_should_succeed() new MessageHeader(messageId, new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { PublishFailurePredicate = _ => false }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_sending_should_capture_publish_context_before_enqueue.cs b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_sending_should_capture_publish_context_before_enqueue.cs index 2731abc662..05ca0c3278 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_sending_should_capture_publish_context_before_enqueue.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Confirmation/When_sending_should_capture_publish_context_before_enqueue.cs @@ -49,7 +49,7 @@ public async Task When_sending_should_capture_publish_context_before_enqueue() var capturedContext = publishActivity.Context; // what we expect to arrive in the confirmation var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All) + var producer = new InMemoryMessageProducer(bus, instrumentationOptions: InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { UseAsyncPublishConfirmation = true }; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged.cs index 481dec375e..6115a3eb1f 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged.cs @@ -22,7 +22,7 @@ public void When_a_dequeud_item_lock_expires() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); @@ -49,7 +49,7 @@ public void When_a_dequeued_item_is_acknowledged() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged_async.cs index 786d7f0a44..dfff896867 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_acknowledged_async.cs @@ -23,7 +23,7 @@ public async Task When_a_dequeud_item_lock_expires() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); @@ -50,7 +50,7 @@ public async Task When_a_dequeued_item_is_acknowledged() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected.cs index f5595d775a..4a0860d39b 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected.cs @@ -22,7 +22,7 @@ public void When_a_dequeued_item_is_rejected() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected_async.cs index 6894a1f746..80344ce613 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_a_dequeued_item_is_rejected_async.cs @@ -23,7 +23,7 @@ public async Task When_a_dequeued_item_is_rejected() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_an_inmemory_channelfactory_is_called.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_an_inmemory_channelfactory_is_called.cs index 47f10cb390..c014746110 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_an_inmemory_channelfactory_is_called.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_an_inmemory_channelfactory_is_called.cs @@ -11,7 +11,7 @@ public void When_an_inmemory_channelfactory_is_called() { //arrange var internalBus = new InternalBus(); - var inMemoryChannelFactory = new InMemoryChannelFactory(internalBus, TimeProvider.System); + var inMemoryChannelFactory = new InMemoryChannelFactory(internalBus, TimeProvider.System, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var channel = inMemoryChannelFactory.CreateSyncChannel(new Subscription(messagePumpType: MessagePumpType.Reactor)); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_creating_an_inmemory_producer_registry.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_creating_an_inmemory_producer_registry.cs index 06dbb53f70..77539fdf50 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_creating_an_inmemory_producer_registry.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_creating_an_inmemory_producer_registry.cs @@ -12,7 +12,7 @@ public void When_creating_an_inmemory_producer_registry() // arrange var bus = new InternalBus(); var publication = new Publication() { Topic = new RoutingKey("Topic") }; - var inMemoryProducerRegistryFactory = new InMemoryProducerRegistryFactory(bus, [publication], InstrumentationOptions.All); + var inMemoryProducerRegistryFactory = new InMemoryProducerRegistryFactory(bus, [publication], global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); //act var producerRegistry = inMemoryProducerRegistryFactory.Create(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_disposing_consumer_should_dispose_lazily_created_producer.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_disposing_consumer_should_dispose_lazily_created_producer.cs index 9856a1f5bd..958655fb51 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_disposing_consumer_should_dispose_lazily_created_producer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_disposing_consumer_should_dispose_lazily_created_producer.cs @@ -42,7 +42,7 @@ public void Should_dispose_without_error_when_producer_was_never_created() var bus = new InternalBus(); var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey("test.topic"); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act & Assert - should not throw var exception = Record.Exception(() => consumer.Dispose()); @@ -57,7 +57,7 @@ public void Should_dispose_producer_when_it_was_created_during_requeue() var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey("test.topic"); var scheduler = new SpyScheduler(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, scheduler: scheduler); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, scheduler: scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), routingKey, MessageType.MT_EVENT), @@ -80,7 +80,7 @@ public async Task Should_dispose_async_without_error_when_producer_was_never_cre var bus = new InternalBus(); var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey("test.topic"); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act & Assert - should not throw var exception = await Record.ExceptionAsync(async () => await consumer.DisposeAsync()); @@ -95,7 +95,7 @@ public async Task Should_dispose_async_producer_when_it_was_created_during_reque var timeProvider = new FakeTimeProvider(); var routingKey = new RoutingKey("test.topic"); var scheduler = new SpyScheduler(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, scheduler: scheduler); + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, scheduler: scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_handler_defers_message_should_requeue_via_scheduler_after_delay.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_handler_defers_message_should_requeue_via_scheduler_after_delay.cs index 11c39cf099..46aa36391d 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_handler_defers_message_should_requeue_via_scheduler_after_delay.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_handler_defers_message_should_requeue_via_scheduler_after_delay.cs @@ -61,7 +61,7 @@ public InMemoryConsumerRequeueWithDelayTests() _routingKey, _bus, _timeProvider, - scheduler: _scheduler); + scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_no_scheduler_configured_should_throw_configuration_exception_on_delayed_requeue.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_no_scheduler_configured_should_throw_configuration_exception_on_delayed_requeue.cs index 0a03cb521f..e46d3bb7b4 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_no_scheduler_configured_should_throw_configuration_exception_on_delayed_requeue.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_no_scheduler_configured_should_throw_configuration_exception_on_delayed_requeue.cs @@ -52,7 +52,7 @@ public AsyncInMemoryConsumerMissingSchedulerTests() _consumer = new InMemoryMessageConsumer( _routingKey, _bus, - _timeProvider); + _timeProvider, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer.cs index 0301949f74..d314e4586c 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer.cs @@ -26,7 +26,7 @@ public void When_reading_messages_via_a_consumer() var bus = new InternalBus(); bus.Enqueue(expectedMessage); - var consumer = new InMemoryMessageConsumer(routingKey, bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer_async.cs index ad941a799d..6f44b8bafb 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_reading_messages_via_a_consumer_async.cs @@ -27,7 +27,7 @@ public async Task When_reading_messages_via_a_consumer() var bus = new InternalBus(); bus.Enqueue(expectedMessage); - var consumer = new InMemoryMessageConsumer(routingKey, bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000)); + var consumer = new InMemoryMessageConsumer(routingKey, bus, new FakeTimeProvider(), ackTimeout: TimeSpan.FromMilliseconds(1000), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel.cs index c52dd4023c..2c1e84e0e2 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel.cs @@ -25,7 +25,7 @@ public void When_rejecting_a_message_with_a_dead_letter_channel() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, deadLetterTopic, ackTimeout: TimeSpan.FromMilliseconds(1000)) as IAmAMessageConsumerSync; + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, deadLetterTopic, ackTimeout: TimeSpan.FromMilliseconds(1000)) as IAmAMessageConsumerSync; //act var receivedMessage = consumer.Receive().Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel_async.cs index 8fa307156d..895e25dfa8 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_rejecting_a_message_with_a_dead_letter_channel_async.cs @@ -26,7 +26,7 @@ public async Task When_rejecting_a_message_with_a_dead_letter_channel_async() bus.Enqueue(expectedMessage); var timeProvider = new FakeTimeProvider(); - var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, deadLetterTopic, ackTimeout: TimeSpan.FromMilliseconds(1000)) as IAmAMessageConsumerAsync; + var consumer = new InMemoryMessageConsumer(routingKey, bus, timeProvider, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, deadLetterTopic, ackTimeout: TimeSpan.FromMilliseconds(1000)) as IAmAMessageConsumerAsync; //act var receivedMessage = (await consumer.ReceiveAsync()).Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again.cs index abc4526cfb..bcbbdb1f91 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again.cs @@ -42,7 +42,7 @@ public InMemoryConsumerRequeueTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -67,10 +67,10 @@ public InMemoryConsumerRequeueTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); - var schedulerFactory = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + var schedulerFactory = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; _processor = new CommandProcessor( subscriberRegistry, @@ -79,8 +79,8 @@ public InMemoryConsumerRequeueTests() new DefaultPolicy(), policyRegistry, outboxBus, - schedulerFactory - ); + schedulerFactory, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = schedulerFactory.Create(_processor); } @@ -96,7 +96,7 @@ public void When_requeueing_a_message_it_should_be_available_again() _internalBus.Enqueue(expectedMessage); var consumer = new InMemoryMessageConsumer(_routingKey, _internalBus, _timeProvider, - ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler); + ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); @@ -119,7 +119,7 @@ public void When_requeueing_a_message_with_a_delay_it_should_not_be_available_im _internalBus.Enqueue(expectedMessage); var consumer = new InMemoryMessageConsumer(_routingKey, _internalBus, _timeProvider, - ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler); + ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = consumer.Receive().Single(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again_async.cs index 31b8cf403e..b33df5e437 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeueing_a_message_it_should_be_available_again_async.cs @@ -53,7 +53,7 @@ public AsyncInMemoryConsumerRequeueTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -78,11 +78,11 @@ public AsyncInMemoryConsumerRequeueTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); - var schedulerFactory = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + var schedulerFactory = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; _processor = new CommandProcessor( subscriberRegistry, @@ -91,8 +91,8 @@ public AsyncInMemoryConsumerRequeueTests() new DefaultPolicy(), new ResiliencePipelineRegistry(), outboxBus, - schedulerFactory - ); + schedulerFactory, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = schedulerFactory.Create(_processor); } @@ -110,7 +110,7 @@ public async Task When_requeueing_a_message_it_should_be_available_again() _internalBus.Enqueue(expectedMessage); var consumer = new InMemoryMessageConsumer(_routingKey, _internalBus, _timeProvider, - ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler); + ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); @@ -132,7 +132,7 @@ public async Task When_requeueing_a_message_with_a_delay_it_should_not_be_availa _internalBus.Enqueue(expectedMessage); var consumer = new InMemoryMessageConsumer(_routingKey, _internalBus, _timeProvider, - ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler:_scheduler); + ackTimeout: TimeSpan.FromMilliseconds(1000), scheduler:_scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //act var receivedMessage = await consumer.ReceiveAsync(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_async_with_delay_should_delegate_to_producer.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_async_with_delay_should_delegate_to_producer.cs index 9c99da8097..9041400825 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_async_with_delay_should_delegate_to_producer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_async_with_delay_should_delegate_to_producer.cs @@ -53,7 +53,7 @@ public AsyncInMemoryConsumerRequeueWithDelayTests() _scheduler = new SpySchedulerAsync(); // Create consumer with scheduler configured - _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler); + _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_delay_should_delegate_to_producer.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_delay_should_delegate_to_producer.cs index 0f6eb77f95..1533bfdb9d 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_delay_should_delegate_to_producer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_delay_should_delegate_to_producer.cs @@ -52,7 +52,7 @@ public InMemoryConsumerRequeueWithDelayProducerTests() _scheduler = new SpyScheduler(); // Create consumer with scheduler configured - _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler); + _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_zero_delay_should_use_direct_bus_enqueue.cs b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_zero_delay_should_use_direct_bus_enqueue.cs index eb3f988bcb..7da53e99b8 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_zero_delay_should_use_direct_bus_enqueue.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Consumer/When_requeuing_with_zero_delay_should_use_direct_bus_enqueue.cs @@ -51,7 +51,7 @@ public InMemoryConsumerRequeueWithZeroDelayTests() _scheduler = new SpyScheduler(); // Create consumer with scheduler configured - _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler); + _consumer = new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), diff --git a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_adding_messages_to_the_producer.cs b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_adding_messages_to_the_producer.cs index 96a5803463..ee2687c7b5 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_adding_messages_to_the_producer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_adding_messages_to_the_producer.cs @@ -15,7 +15,7 @@ public void When_adding_messages_to_the_producer() const string topic = "test_topic"; var message = new Message(new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey(topic), MessageType.MT_DOCUMENT), new MessageBody("test_content")); var bus = new InternalBus(); - var producer = new InMemoryMessageProducer(bus, instrumentationOptions:InstrumentationOptions.All); + var producer = new InMemoryMessageProducer(bus, instrumentationOptions:InstrumentationOptions.All, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // act producer.Send(message); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_async_with_delay_and_scheduler_configured_should_use_scheduler.cs b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_async_with_delay_and_scheduler_configured_should_use_scheduler.cs index 0c8234b675..1530818e46 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_async_with_delay_and_scheduler_configured_should_use_scheduler.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_async_with_delay_and_scheduler_configured_should_use_scheduler.cs @@ -46,7 +46,7 @@ public When_sending_async_with_delay_and_scheduler_configured_should_use_schedul { // Arrange _bus = new InternalBus(); - _producer = new InMemoryMessageProducer(_bus); + _producer = new InMemoryMessageProducer(_bus, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new SpySchedulerAsync(); _producer.Scheduler = _scheduler; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_no_scheduler_should_use_timer_fallback.cs b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_no_scheduler_should_use_timer_fallback.cs index 4d86137887..abe0bb67d9 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_no_scheduler_should_use_timer_fallback.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_no_scheduler_should_use_timer_fallback.cs @@ -42,7 +42,7 @@ public SchedulerNotConfiguredTests() { // Arrange - no scheduler configured var bus = new InternalBus(); - _producer = new InMemoryMessageProducer(bus); + _producer = new InMemoryMessageProducer(bus, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Note: Scheduler is NOT set - testing exception behavior var routingKey = new RoutingKey("test.topic"); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_scheduler_configured_should_use_scheduler.cs b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_scheduler_configured_should_use_scheduler.cs index 1c13982e33..94601188e0 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_scheduler_configured_should_use_scheduler.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_delay_and_scheduler_configured_should_use_scheduler.cs @@ -44,7 +44,7 @@ public When_sending_with_delay_and_scheduler_configured_should_use_scheduler() { // Arrange _bus = new InternalBus(); - _producer = new InMemoryMessageProducer(_bus); + _producer = new InMemoryMessageProducer(_bus, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new SpyScheduler(); _producer.Scheduler = _scheduler; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_zero_delay_should_send_immediately_without_scheduler.cs b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_zero_delay_should_send_immediately_without_scheduler.cs index 6d432dd777..19d1a1ccb0 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_zero_delay_should_send_immediately_without_scheduler.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Producer/When_sending_with_zero_delay_should_send_immediately_without_scheduler.cs @@ -45,7 +45,7 @@ public When_sending_with_zero_delay_should_send_immediately_without_scheduler() { // Arrange _bus = new InternalBus(); - _producer = new InMemoryMessageProducer(_bus); + _producer = new InMemoryMessageProducer(_bus, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new SpyScheduler(); _producer.Scheduler = _scheduler; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message.cs b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message.cs index dc4b568c59..cd29c80857 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message.cs @@ -32,7 +32,7 @@ public InMemorySchedulerMessageTests() _timeProvider = new FakeTimeProvider(); _timeProvider.SetUtcNow(DateTimeOffset.UtcNow); - _scheduler = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + _scheduler = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; var handlerFactory = new SimpleHandlerFactory( _ => new MyEventHandler(new Dictionary()), @@ -51,7 +51,7 @@ public InMemorySchedulerMessageTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -76,7 +76,7 @@ public InMemorySchedulerMessageTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); _processor = new CommandProcessor( @@ -86,8 +86,8 @@ public InMemorySchedulerMessageTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message_async.cs index 4f1f7cd636..f25a4e3b1d 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_message_async.cs @@ -34,7 +34,7 @@ public InMemorySchedulerMessageAsyncTests() _timeProvider = new FakeTimeProvider(); _timeProvider.SetUtcNow(DateTimeOffset.UtcNow); - _scheduler = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + _scheduler = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; var handlerFactory = new SimpleHandlerFactoryAsync( type => @@ -60,7 +60,7 @@ public InMemorySchedulerMessageAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -85,7 +85,7 @@ public InMemorySchedulerMessageAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); _processor = new CommandProcessor( @@ -95,8 +95,8 @@ public InMemorySchedulerMessageAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request.cs b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request.cs index 7c67f3586e..306c75ea79 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request.cs @@ -34,7 +34,7 @@ public InMemorySchedulerRequestTests() _timeProvider = new FakeTimeProvider(); _timeProvider.SetUtcNow(DateTimeOffset.UtcNow); - _scheduler = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + _scheduler = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; var handlerFactory = new SimpleHandlerFactory( _ => new MyEventHandler(_receivedMessages), @@ -53,7 +53,7 @@ public InMemorySchedulerRequestTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -73,7 +73,7 @@ public InMemorySchedulerRequestTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); @@ -84,8 +84,8 @@ public InMemorySchedulerRequestTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } #region Scheduler diff --git a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request_async.cs b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request_async.cs index ff69b5be9c..e4a463af1e 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request_async.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_a_request_async.cs @@ -36,7 +36,7 @@ public InMemorySchedulerRequestAsyncTests() _timeProvider = new FakeTimeProvider(); _timeProvider.SetUtcNow(DateTimeOffset.UtcNow); - _scheduler = new InMemorySchedulerFactory { TimeProvider = _timeProvider }; + _scheduler = new InMemorySchedulerFactory (loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider }; var handlerFactory = new SimpleHandlerFactoryAsync( type => @@ -62,7 +62,7 @@ public InMemorySchedulerRequestAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -82,7 +82,7 @@ public InMemorySchedulerRequestAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); _processor = new CommandProcessor( @@ -92,8 +92,8 @@ public InMemorySchedulerRequestAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } #region Scheduler diff --git a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_message_with_existing_id_should_atomically_replace_timer.cs b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_message_with_existing_id_should_atomically_replace_timer.cs index d7bf79f187..268cffb549 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_message_with_existing_id_should_atomically_replace_timer.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Scheduler/When_scheduling_message_with_existing_id_should_atomically_replace_timer.cs @@ -64,6 +64,7 @@ public When_scheduling_message_with_existing_id_should_atomically_replace_timer( // Configure scheduler to use a fixed ID so multiple Schedule calls target the same entry // and to overwrite (not throw) on conflict _schedulerFactory = new InMemorySchedulerFactory +(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { TimeProvider = _timeProvider, GetOrCreateMessageSchedulerId = _ => FixedSchedulerId, @@ -87,7 +88,7 @@ public When_scheduling_message_with_existing_id_should_atomically_replace_timer( var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -111,7 +112,7 @@ public When_scheduling_message_with_existing_id_should_atomically_replace_timer( new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); _processor = new CommandProcessor( @@ -121,8 +122,8 @@ public When_scheduling_message_with_existing_id_should_atomically_replace_timer( policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _schedulerFactory - ); + _schedulerFactory, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_clearing_outbox_with_missing_messages.cs b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_clearing_outbox_with_missing_messages.cs index 8d2d95049e..076f0357a3 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_clearing_outbox_with_missing_messages.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_clearing_outbox_with_missing_messages.cs @@ -31,7 +31,7 @@ public void When_clearing_outbox_with_missing_messages_should_dispatch_found() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -50,7 +50,7 @@ public void When_clearing_outbox_with_missing_messages_should_dispatch_found() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); var context = new RequestContext(); @@ -99,7 +99,7 @@ public async Task When_clearing_outbox_async_with_missing_messages_should_dispat var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -118,7 +118,7 @@ public async Task When_clearing_outbox_async_with_missing_messages_should_dispat new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); var context = new RequestContext(); diff --git a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox.cs b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox.cs index fe334f78c1..e2b04cca08 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox.cs @@ -34,7 +34,7 @@ public async Task When_outstanding_in_outbox_sweep_clears_them() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -53,7 +53,7 @@ public async Task When_outstanding_in_outbox_sweep_clears_them() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); @@ -62,7 +62,7 @@ public async Task When_outstanding_in_outbox_sweep_clears_them() new PolicyRegistry(), new ResiliencePipelineRegistry(), mediator, - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var sweeper = new OutboxSweeper(timeSinceSent, mediator, new InMemoryRequestContextFactory()); @@ -105,7 +105,7 @@ public async Task When_outstanding_in_outbox_sweep_clears_them_async() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -124,7 +124,7 @@ public async Task When_outstanding_in_outbox_sweep_clears_them_async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); @@ -133,8 +133,8 @@ public async Task When_outstanding_in_outbox_sweep_clears_them_async() new PolicyRegistry(), new ResiliencePipelineRegistry(), mediator, - new InMemorySchedulerFactory()); - + new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var sweeper = new OutboxSweeper(timeSinceSent, mediator, new InMemoryRequestContextFactory()); var events = new[] @@ -175,7 +175,7 @@ public async Task When_too_new_to_sweep_leaves_them() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -194,7 +194,7 @@ public async Task When_too_new_to_sweep_leaves_them() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); @@ -203,8 +203,8 @@ public async Task When_too_new_to_sweep_leaves_them() new PolicyRegistry(), new ResiliencePipelineRegistry(), mediator, - new InMemorySchedulerFactory()); - + new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var sweeper = new OutboxSweeper( timeSinceSent, mediator, @@ -254,7 +254,7 @@ public async Task When_too_new_to_sweep_leaves_them_async() var producerRegistry = new ProducerRegistry(new Dictionary { { - routingKey, new InMemoryMessageProducer(internalBus, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) + routingKey, new InMemoryMessageProducer(internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { RequestType = typeof(MyEvent), Topic = routingKey }) } }); @@ -273,7 +273,7 @@ public async Task When_too_new_to_sweep_leaves_them_async() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, outbox ); @@ -282,8 +282,8 @@ public async Task When_too_new_to_sweep_leaves_them_async() new PolicyRegistry(), new ResiliencePipelineRegistry(), mediator, - new InMemorySchedulerFactory()); - + new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var sweeper = new OutboxSweeper(timeSinceSent, mediator, new InMemoryRequestContextFactory()); var oldEvent = new MyEvent{Value = "old"}; diff --git a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox_with_circuit_breaker.cs b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox_with_circuit_breaker.cs index 2b486070c1..f1a7f9c3be 100644 --- a/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox_with_circuit_breaker.cs +++ b/tests/Paramore.Brighter.InMemory.Tests/Sweeper/When_sweeping_the_outbox_with_circuit_breaker.cs @@ -61,7 +61,7 @@ public SweeperTestsWithCircuitBreaker() // message 1 var myEvent = new MyEvent() { Value = "MyEvent1" }; - InMemoryMessageProducer messageProducer = new(_internalBus, new Publication { Topic = _routingKeyOne, RequestType = typeof(MyEvent) }); + InMemoryMessageProducer messageProducer = new(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKeyOne, RequestType = typeof(MyEvent) }); _messageOne = new Message( new MessageHeader(myEvent.Id, _routingKeyOne, MessageType.MT_EVENT), @@ -70,7 +70,7 @@ public SweeperTestsWithCircuitBreaker() // message 2 var myEvent2 = new MyEvent() { Value = "MyEvent2" }; - InMemoryMessageProducer messageProducerTwo = new(_internalBus, new Publication { Topic = _routingKeyTwo, RequestType = typeof(MyEvent) }); + InMemoryMessageProducer messageProducerTwo = new(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKeyTwo, RequestType = typeof(MyEvent) }); _messageTwo = new Message( new MessageHeader(myEvent2.Id, _routingKeyTwo, MessageType.MT_COMMAND), @@ -104,7 +104,7 @@ public SweeperTestsWithCircuitBreaker() new EmptyMessageTransformerFactoryAsync(), tracer, new FindPublicationByPublicationTopicOrRequestType(), - _outbox, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox, outboxCircuitBreaker: _circuitBreaker ); diff --git a/tests/Paramore.Brighter.Kafka.Tests/Initializer.cs b/tests/Paramore.Brighter.Kafka.Tests/Initializer.cs index c94b601fb5..9f761e5372 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/Initializer.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/Initializer.cs @@ -1,17 +1,19 @@ using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Serilog; namespace Paramore.Brighter.Kafka.Tests { sealed class Initializer { + public static ILoggerFactory TestLoggerFactory { get; private set; } = NullLoggerFactory.Instance; + [ModuleInitializer] public static void InitializeTestLogger() { var logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.TestCorrelator().CreateLogger(); - ApplicationLogging.LoggerFactory = new LoggerFactory().AddSerilog(logger); + TestLoggerFactory = new LoggerFactory().AddSerilog(logger); } } } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaClassicMessageGatewayProvider.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaClassicMessageGatewayProvider.cs index b3a837bea7..8f696b82d4 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaClassicMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaClassicMessageGatewayProvider.cs @@ -117,7 +117,7 @@ static async ValueTask DisposeAsync(object? disposable) public IAmAChannelSync CreateChannel(KafkaSubscription subscription) { var channel = new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateSyncChannel(subscription); return new RetryableChannelSync(channel); @@ -129,7 +129,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateAsyncChannelAsync(subscription, cancellationToken); return new RetryableChannelAsync(channel); @@ -139,8 +139,8 @@ public IAmAMessageProducerSync CreateProducer(KafkaPublication publication) { var producerRegistry = new KafkaProducerRegistryFactory( _configuration, - [publication] - ).Create(); + [publication], + loggerFactory: Initializer.TestLoggerFactory).Create(); _producerRegistries.Add(producerRegistry); @@ -154,8 +154,8 @@ public async Task CreateProducerAsync( { var producerRegistry = await new KafkaProducerRegistryFactory( _configuration, - [publication] - ).CreateAsync(cancellationToken); + [publication], + loggerFactory: Initializer.TestLoggerFactory).CreateAsync(cancellationToken); _producerRegistries.Add(producerRegistry); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaConsumerMessageGatewayProvider.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaConsumerMessageGatewayProvider.cs index cb5a8f7427..d8a1e90125 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaConsumerMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaConsumerMessageGatewayProvider.cs @@ -117,7 +117,7 @@ static async ValueTask DisposeAsync(object? disposable) public IAmAChannelSync CreateChannel(KafkaSubscription subscription) { var channel = new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateSyncChannel(subscription); return new RetryableChannelSync(channel); @@ -129,7 +129,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateAsyncChannelAsync(subscription, cancellationToken); return new RetryableChannelAsync(channel); @@ -139,8 +139,8 @@ public IAmAMessageProducerSync CreateProducer(KafkaPublication publication) { var producerRegistry = new KafkaProducerRegistryFactory( _configuration, - [publication] - ).Create(); + [publication], + loggerFactory: Initializer.TestLoggerFactory).Create(); _producerRegistries.Add(producerRegistry); @@ -154,8 +154,8 @@ public async Task CreateProducerAsync( { var producerRegistry = await new KafkaProducerRegistryFactory( _configuration, - [publication] - ).CreateAsync(cancellationToken); + [publication], + loggerFactory: Initializer.TestLoggerFactory).CreateAsync(cancellationToken); _producerRegistries.Add(producerRegistry); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaPartitionKeyMessageGatewayProvider.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaPartitionKeyMessageGatewayProvider.cs index c87ca210e6..4d4f51d982 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaPartitionKeyMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/KafkaPartitionKeyMessageGatewayProvider.cs @@ -125,7 +125,7 @@ static async ValueTask DisposeAsync(object? disposable) public IAmAChannelSync CreateChannel(KafkaSubscription subscription) { var channel = new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateSyncChannel(subscription); return new RetryableChannelSync(channel); @@ -137,7 +137,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new KafkaMessageConsumerFactory(_configuration) + new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory) ).CreateAsyncChannelAsync(subscription, cancellationToken); return new RetryableChannelAsync(channel); @@ -147,8 +147,8 @@ public IAmAMessageProducerSync CreateProducer(KafkaPublication publication) { var producerRegistry = new KafkaProducerRegistryFactory( _configuration, - [publication] - ).Create(); + [publication], + loggerFactory: Initializer.TestLoggerFactory).Create(); _producerRegistries.Add(producerRegistry); @@ -162,8 +162,8 @@ public async Task CreateProducerAsync( { var producerRegistry = await new KafkaProducerRegistryFactory( _configuration, - [publication] - ).CreateAsync(cancellationToken); + [publication], + loggerFactory: Initializer.TestLoggerFactory).CreateAsync(cancellationToken); _producerRegistries.Add(producerRegistry); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_kafka_confirmation_fires_should_carry_topic_and_link_from_message.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_kafka_confirmation_fires_should_carry_topic_and_link_from_message.cs index 4d9454639b..8347d57ed1 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_kafka_confirmation_fires_should_carry_topic_and_link_from_message.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_kafka_confirmation_fires_should_carry_topic_and_link_from_message.cs @@ -31,7 +31,7 @@ public KafkaConfirmationTopicAndLinkTestsAsync() RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_message_is_acknowledged_update_offset_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_message_is_acknowledged_update_offset_async.cs index a46c7dcfa6..58599ac185 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_message_is_acknowledged_update_offset_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_a_message_is_acknowledged_update_offset_async.cs @@ -37,7 +37,7 @@ public KafkaMessageConsumerUpdateOffsetAsync(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } //[Fact(Skip = "As it has to wait for the messages to flush, only tends to run well in debug")] @@ -156,7 +156,7 @@ async Task ConsumeMessageAsync(IAmAMessageConsumerAsync consumer) private IAmAMessageConsumerAsync CreateConsumer(string groupId) { return new KafkaMessageConsumerFactory( - new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } }) + new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_an_async_produce_throws_should_warn_and_synthesize_not_persisted.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_an_async_produce_throws_should_warn_and_synthesize_not_persisted.cs index 9f702be263..0ee39227c8 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_an_async_produce_throws_should_warn_and_synthesize_not_persisted.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_an_async_produce_throws_should_warn_and_synthesize_not_persisted.cs @@ -33,7 +33,7 @@ public KafkaProducerOversizedMessageTestsAsync() RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_consumer_declares_topic_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_consumer_declares_topic_async.cs index 742426cce7..8b465a27ba 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_consumer_declares_topic_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_consumer_declares_topic_async.cs @@ -40,14 +40,14 @@ public KafkaConsumerDeclareTestsAsync(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Assume } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_kafka_consumer_requeues_async_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_kafka_consumer_requeues_async_with_delay_should_use_producer.cs index e37de730a6..3103385009 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_kafka_consumer_requeues_async_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_kafka_consumer_requeues_async_with_delay_should_use_producer.cs @@ -72,14 +72,14 @@ public KafkaConsumerRequeueAsyncTests(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Requeue Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription( channelName: new ChannelName(_channelName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_nacking_a_message_it_should_be_redelivered_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_nacking_a_message_it_should_be_redelivered_async.cs index 81ba9eb877..8798077c63 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_nacking_a_message_it_should_be_redelivered_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_nacking_a_message_it_should_be_redelivered_async.cs @@ -36,7 +36,7 @@ public KafkaMessageConsumerNackRedeliveryAsync(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } [Fact] @@ -155,7 +155,7 @@ private IAmAMessageConsumerAsync CreateConsumer(string groupId) new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_offsets_awaiting_next_acknowledge_sweep_them_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_offsets_awaiting_next_acknowledge_sweep_them_async.cs index 7a3ef34228..98199ad07d 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_offsets_awaiting_next_acknowledge_sweep_them_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_offsets_awaiting_next_acknowledge_sweep_them_async.cs @@ -41,14 +41,14 @@ public KafkaMessageConsumerSweepOffsetsAsync(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; _consumer = (KafkaMessageConsumer) new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_posting_a_message_with_header_bytes_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_posting_a_message_with_header_bytes_async.cs index 0b73658c15..31ea5998a4 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_posting_a_message_with_header_bytes_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_posting_a_message_with_header_bytes_async.cs @@ -49,14 +49,14 @@ public KafkaMessageProducerHeaderBytesSendTestsAsync(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_publish_results_not_persisted_should_raise_failure_with_id.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_publish_results_not_persisted_should_raise_failure_with_id.cs index 061604327a..14b53983b9 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_publish_results_not_persisted_should_raise_failure_with_id.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_publish_results_not_persisted_should_raise_failure_with_id.cs @@ -30,7 +30,7 @@ public KafkaNotPersistedConfirmationIdTestsAsync() RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_recieving_a_message_without_partition_key_header_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_recieving_a_message_without_partition_key_header_async.cs index 530a1bc340..cabb3abd2b 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_recieving_a_message_without_partition_key_header_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_recieving_a_message_without_partition_key_header_async.cs @@ -60,7 +60,7 @@ public KafkaMessageProducerMissingHeaderTestsAsync(ITestOutputHelper output) new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index cf28488f77..6623fad3fd 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerDLQAsyncTests(ITestOutputHelper output) Name = "Kafka Producer DLQ Async Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -138,7 +138,7 @@ private IAmAMessageConsumerAsync CreateConsumer(string groupId, RoutingKey dlqRo { Name = "Kafka Consumer DLQ Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -161,7 +161,7 @@ private IAmAMessageConsumerAsync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log_async.cs index 929ac270e5..62d753271f 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log_async.cs @@ -62,7 +62,7 @@ public KafkaMessageConsumerNoChannelsAsyncTests(ITestOutputHelper output) Name = "Kafka Producer No Channels Async Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -130,7 +130,7 @@ private IAmAMessageConsumerAsync CreateConsumerWithNoChannels(string groupId) { Name = "Kafka Consumer No Channels Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq_async.cs index e5a00f14f5..13a03912bf 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq_async.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerInvalidMessageFallbackAsyncTests(ITestOutputHelper ou Name = "Kafka Producer Invalid Message Fallback Async Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -139,7 +139,7 @@ private IAmAMessageConsumerAsync CreateConsumerWithDlqOnly(string groupId, Routi { Name = "Kafka Consumer Invalid Message Fallback Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -163,7 +163,7 @@ private IAmAMessageConsumerAsync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel_async.cs index 19bfc78945..3b50f66ed1 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel_async.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerInvalidMessageAsyncTests(ITestOutputHelper output) Name = "Kafka Producer Invalid Message Async Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -139,7 +139,7 @@ private IAmAMessageConsumerAsync CreateConsumer(string groupId, RoutingKey inval { Name = "Kafka Consumer Invalid Message Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -162,7 +162,7 @@ private IAmAMessageConsumerAsync CreateInvalidMessageConsumer(string groupId) { Name = "Kafka Invalid Message Consumer Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.InvalidMessage.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq_async.cs index 78c04ecec7..e45197151d 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq_async.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerUnknownReasonAsyncTests(ITestOutputHelper output) Name = "Kafka Producer Unknown Reason Async Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -139,7 +139,7 @@ private IAmAMessageConsumerAsync CreateConsumerAsync(string groupId, RoutingKey { Name = "Kafka Consumer Unknown Reason Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -162,7 +162,7 @@ private IAmAMessageConsumerAsync CreateDLQConsumerAsync(string groupId) { Name = "Kafka DLQ Consumer Async Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs index 3e652f9df8..98002cb904 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Proactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs @@ -67,7 +67,7 @@ public WhenSweeperTimeoutReachedShouldCommitUncommittedOffsetsAsync(ITestOutputH RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).CreateAsync().Result; + ], loggerFactory: Initializer.TestLoggerFactory).CreateAsync().Result; // Create a fake time provider to control time in the test _fakeTimeProvider = new FakeTimeProvider(); @@ -89,7 +89,7 @@ public WhenSweeperTimeoutReachedShouldCommitUncommittedOffsetsAsync(ITestOutputH { Name = "Kafka Consumer Test", BootStrapServers = ["localhost:9092"] - }) + }, loggerFactory: Initializer.TestLoggerFactory) .CreateAsync(subscription); } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_a_message_is_acknowledged_update_offset.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_a_message_is_acknowledged_update_offset.cs index 80c451aab1..2a0a6ffc7a 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_a_message_is_acknowledged_update_offset.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_a_message_is_acknowledged_update_offset.cs @@ -39,7 +39,7 @@ public KafkaMessageConsumerUpdateOffset(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } //[Fact(Skip = "Fragile as commit thread needs to be scheduled to run")] @@ -143,7 +143,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId) new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_committing_offsets_during_revoke_should_not_race.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_committing_offsets_during_revoke_should_not_race.cs index 1000888f52..489689b6c3 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_committing_offsets_during_revoke_should_not_race.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_committing_offsets_during_revoke_should_not_race.cs @@ -41,7 +41,7 @@ public KafkaMessageConsumerCommitRevokeConcurrency(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } /// @@ -156,7 +156,7 @@ private KafkaMessageConsumer CreateConsumer(int commitBatchSize, { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_consumer_declares_topic.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_consumer_declares_topic.cs index 3010cdf37d..10e3ce4c36 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_consumer_declares_topic.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_consumer_declares_topic.cs @@ -40,14 +40,14 @@ public KafkaConsumerDeclareTests (ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Assume } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_converting_kafkaheader_to_brighterheader.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_converting_kafkaheader_to_brighterheader.cs index f9acebe5ac..9150b4839d 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_converting_kafkaheader_to_brighterheader.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_converting_kafkaheader_to_brighterheader.cs @@ -55,7 +55,7 @@ public void When_converting_kafkaheader_to_brighterheader() }; //act - var readMessage = new KafkaMessageCreator().CreateMessage(result); + var readMessage = new KafkaMessageCreator(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)).CreateMessage(result); //assert Assert.Equal(message.Id, readMessage.Id); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_creating_dlq_producer_with_make_channels_create_should_create_topic.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_creating_dlq_producer_with_make_channels_create_should_create_topic.cs index b8dfb6106a..79ff208853 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_creating_dlq_producer_with_make_channels_create_should_create_topic.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_creating_dlq_producer_with_make_channels_create_should_create_topic.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerMakeChannelsTests(ITestOutputHelper output) Name = "Kafka Producer MakeChannels Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -138,7 +138,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId, RoutingKey dlqRou { Name = "Kafka Consumer MakeChannels Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -161,7 +161,7 @@ private IAmAMessageConsumerSync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_disposes_should_dispose_requeue_producer.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_disposes_should_dispose_requeue_producer.cs index 9b6297c8c3..cdd00dfba0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_disposes_should_dispose_requeue_producer.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_disposes_should_dispose_requeue_producer.cs @@ -66,14 +66,14 @@ public KafkaConsumerDisposesRequeueProducerTests(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Dispose Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_channelName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_producer.cs index 24d4381feb..87d7cff2c0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_producer.cs @@ -72,14 +72,14 @@ public KafkaConsumerRequeueTests(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Requeue Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_channelName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_scheduler.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_scheduler.cs index 347fcfda8e..39eb10a6c0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_scheduler.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_kafka_consumer_requeues_with_delay_should_use_scheduler.cs @@ -72,7 +72,7 @@ public KafkaConsumerRequeueSchedulerTests(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _scheduler = new SpySchedulerSync(); @@ -88,7 +88,7 @@ public KafkaConsumerRequeueSchedulerTests(ITestOutputHelper output) numPartitions: 1, replicationFactor: 1, makeChannels: OnMissingChannel.Create, - scheduler: _scheduler); + scheduler: _scheduler, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_nacking_a_message_it_should_be_redelivered.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_nacking_a_message_it_should_be_redelivered.cs index 3947ceffb3..e8d95f3c89 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_nacking_a_message_it_should_be_redelivered.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_nacking_a_message_it_should_be_redelivered.cs @@ -36,7 +36,7 @@ public KafkaMessageConsumerNackRedelivery(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } [Fact] @@ -155,7 +155,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId) new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_offsets_awaiting_next_acknowledge_sweep_them.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_offsets_awaiting_next_acknowledge_sweep_them.cs index 1d1eaf13af..3bfd3c75c5 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_offsets_awaiting_next_acknowledge_sweep_them.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_offsets_awaiting_next_acknowledge_sweep_them.cs @@ -41,14 +41,14 @@ public KafkaMessageConsumerSweepOffsets(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); _consumer = (KafkaMessageConsumer)new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_posting_a_message_with_header_bytes.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_posting_a_message_with_header_bytes.cs index 319b51c603..55aeaca3a6 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_posting_a_message_with_header_bytes.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_posting_a_message_with_header_bytes.cs @@ -18,7 +18,7 @@ namespace Paramore.Brighter.Kafka.Tests.MessagingGateway.Reactor; public class KafkaMessageProducerHeaderBytesSendTests : IDisposable { private readonly ITestOutputHelper _output; - private readonly string _queueName = Guid.NewGuid().ToString(); + private readonly string _queueName = Guid.NewGuid().ToString(); private readonly string _topic = Guid.NewGuid().ToString(); private readonly IAmAProducerRegistry _producerRegistry; private readonly IAmAMessageConsumerSync _consumer; @@ -35,7 +35,7 @@ public KafkaMessageProducerHeaderBytesSendTests (ITestOutputHelper output) _producerRegistry = new KafkaProducerRegistryFactory( new KafkaMessagingGatewayConfiguration { - Name = "Kafka Producer Send Test", + Name = "Kafka Producer Send Test", BootStrapServers = new[] {"localhost:9092"} }, [ @@ -44,22 +44,22 @@ public KafkaMessageProducerHeaderBytesSendTests (ITestOutputHelper output) Topic = new RoutingKey(_topic), NumPartitions = 1, ReplicationFactor = 1, - //These timeouts support running on a container using the same host as the tests, + //These timeouts support running on a container using the same host as the tests, //your production values ought to be lower MessageTimeoutMs = 2000, RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); - + ], loggerFactory: Initializer.TestLoggerFactory).Create(); + _consumer = new KafkaMessageConsumerFactory( new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = ["localhost:9092"] - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( - channelName: new ChannelName(_queueName), + channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), groupId: groupId, numOfPartitions: 1, @@ -68,10 +68,10 @@ public KafkaMessageProducerHeaderBytesSendTests (ITestOutputHelper output) makeChannels: OnMissingChannel.Create ) ); - + var schemaRegistryConfig = new SchemaRegistryConfig { Url = "http://localhost:8081"}; ISchemaRegistryClient schemaRegistryClient = new CachedSchemaRegistryClient(schemaRegistryConfig); - + _serializer = new JsonSerializer(schemaRegistryClient, ConfluentJsonSerializationConfig.SerdesJsonSerializerConfig(), ConfluentJsonSerializationConfig.NJsonSchemaGeneratorSettings()).AsSyncOverAsync(); _deserializer = new JsonDeserializer().AsSyncOverAsync(); _serializationContext = new SerializationContext(MessageComponentType.Value, _topic); @@ -84,46 +84,46 @@ public KafkaMessageProducerHeaderBytesSendTests (ITestOutputHelper output) [Fact] public async Task When_posting_a_message_via_the_messaging_gateway() { - + await Task.Delay(500); //Let topic propagate in the broker - + //arrange - + var myCommand = new MyKafkaCommand{ Value = "Hello World"}; - + //use the serdes json serializer to write the message to the topic var body = _serializer.Serialize(myCommand, _serializationContext); - + //grab the schema id that was written to the message by the serializer var schemaId = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(body.Skip(1).Take(4).ToArray())); var routingKey = new RoutingKey(_topic); - + var sent = new Message( new MessageHeader(Guid.NewGuid().ToString(), routingKey, MessageType.MT_COMMAND) { PartitionKey = _partitionKey }, new MessageBody(body)); - + //act var producer = ((IAmAMessageProducerSync)_producerRegistry.LookupBy(routingKey)); producer.Send(sent); - + //ensure that the messages are all sent ((KafkaMessageProducer) producer).Flush(); - + await Task.Delay(500); //Let the message propagate in the broker var received = GetMessage(); Assert.True(received.Body.Bytes.Length > 5); - + var receivedSchemaId = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(received.Body.Bytes.Skip(1).Take(4).ToArray())); - + var receivedCommand = _deserializer.Deserialize(received.Body.Bytes, received.Body.Bytes is null, _serializationContext); - + //assert Assert.Equal(MessageType.MT_COMMAND, received.Header.MessageType); Assert.Equal(_partitionKey, received.Header.PartitionKey); @@ -144,13 +144,13 @@ private Message GetMessage() { maxTries++; messages = _consumer.Receive(TimeSpan.FromMilliseconds(1000)); - + if (messages[0].Header.MessageType != MessageType.MT_NONE) { _consumer.Acknowledge(messages[0]); break; } - + } catch (ChannelFailureException cfx) { @@ -160,10 +160,10 @@ private Message GetMessage() } } while (maxTries <= 10); - + if (messages[0].Header.MessageType == MessageType.MT_NONE) throw new Exception($"Failed to read from topic:{_topic} after {maxTries} attempts"); - + return messages[0]; } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_recieving_a_message_without_partition_key_header.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_recieving_a_message_without_partition_key_header.cs index 168956137d..75545edb9b 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_recieving_a_message_without_partition_key_header.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_recieving_a_message_without_partition_key_header.cs @@ -61,7 +61,7 @@ public KafkaMessageProducerMissingHeaderTests(ITestOutputHelper output) new KafkaMessagingGatewayConfiguration { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_should_include_metadata.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_should_include_metadata.cs index 6167c31dc2..986ab636a0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_should_include_metadata.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_should_include_metadata.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerMetadataTests(ITestOutputHelper output) Name = "Kafka Producer Metadata Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -160,7 +160,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId, RoutingKey dlqRou { Name = "Kafka Consumer Metadata Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -183,7 +183,7 @@ private IAmAMessageConsumerSync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index ddfb0e6dc3..dc034f3aa0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerDLQTests(ITestOutputHelper output) Name = "Kafka Producer DLQ Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -135,7 +135,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId, RoutingKey dlqRou { Name = "Kafka Consumer DLQ Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -158,7 +158,7 @@ private IAmAMessageConsumerSync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs index 80e51614c6..68d32073e7 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_acknowledge_and_log.cs @@ -62,7 +62,7 @@ public KafkaMessageConsumerNoChannelsTests(ITestOutputHelper output) Name = "Kafka Producer No Channels Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -127,7 +127,7 @@ private IAmAMessageConsumerSync CreateConsumerWithNoChannels(string groupId) { Name = "Kafka Consumer No Channels Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 6dadd2475a..2e5a97c3ab 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerInvalidMessageFallbackTests(ITestOutputHelper output) Name = "Kafka Producer Invalid Message Fallback Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -136,7 +136,7 @@ private IAmAMessageConsumerSync CreateConsumerWithDlqOnly(string groupId, Routin { Name = "Kafka Consumer Invalid Message Fallback Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -160,7 +160,7 @@ private IAmAMessageConsumerSync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index d7a9ea7078..86231735c6 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerInvalidMessageTests(ITestOutputHelper output) Name = "Kafka Producer Invalid Message Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -136,7 +136,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId, RoutingKey invali { Name = "Kafka Consumer Invalid Message Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -159,7 +159,7 @@ private IAmAMessageConsumerSync CreateInvalidMessageConsumer(string groupId) { Name = "Kafka Invalid Message Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.InvalidMessage.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq.cs index 0a89922330..0f6b8bb00c 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unknown_reason_should_send_to_dlq.cs @@ -64,7 +64,7 @@ public KafkaMessageConsumerUnknownReasonTests(ITestOutputHelper output) Name = "Kafka Producer Unknown Reason Test", BootStrapServers = new[] { "localhost:9092" } }, - publication); + publication, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } @@ -136,7 +136,7 @@ private IAmAMessageConsumerSync CreateConsumer(string groupId, RoutingKey dlqRou { Name = "Kafka Consumer Unknown Reason Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.Tests"), @@ -159,7 +159,7 @@ private IAmAMessageConsumerSync CreateDLQConsumer(string groupId) { Name = "Kafka DLQ Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription ( subscriptionName: new SubscriptionName("Paramore.Brighter.DLQ.Tests"), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_revoked_partitions_offsets_are_committed.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_revoked_partitions_offsets_are_committed.cs index 6591aa748f..cbc1f2d821 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_revoked_partitions_offsets_are_committed.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_revoked_partitions_offsets_are_committed.cs @@ -42,7 +42,7 @@ public KafkaMessageConsumerCommitOnRevoke(ITestOutputHelper output) RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); } /// @@ -188,7 +188,7 @@ private KafkaMessageConsumer CreateConsumer(int commitBatchSize, { Name = "Kafka Consumer Test", BootStrapServers = new[] { "localhost:9092" } - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(new KafkaSubscription( channelName: new ChannelName(_queueName), routingKey: new RoutingKey(_topic), diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs index ef04eea8d2..527cdd370f 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_sweeper_timeout_reached_should_commit_uncommitted_offsets_async.cs @@ -67,7 +67,7 @@ public WhenSweeperTimeoutReachedShouldCommitUncommittedOffsets(ITestOutputHelper RequestTimeoutMs = 2000, MakeChannels = OnMissingChannel.Create } - ]).Create(); + ], loggerFactory: Initializer.TestLoggerFactory).Create(); // Create a fake time provider to control time in the test _fakeTimeProvider = new FakeTimeProvider(); @@ -89,7 +89,7 @@ public WhenSweeperTimeoutReachedShouldCommitUncommittedOffsets(ITestOutputHelper { Name = "Kafka Consumer Test", BootStrapServers = ["localhost:9092"] - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(subscription); } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_using_a_consumer_config_hook.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_using_a_consumer_config_hook.cs index 4520815ea6..bf9175d9f8 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_using_a_consumer_config_hook.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/Reactor/When_using_a_consumer_config_hook.cs @@ -33,7 +33,7 @@ public void When_using_a_consumer_config_hook() { Name = "Kafka Consumer Test", BootStrapServers = ["localhost:9092"] - }) + }, loggerFactory: Initializer.TestLoggerFactory) .Create(subscription ); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_Producing_And_Consuming_Headers_Should_Use_Utf8_Consistently.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_Producing_And_Consuming_Headers_Should_Use_Utf8_Consistently.cs index 4c10c2860c..f8f2ca0010 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_Producing_And_Consuming_Headers_Should_Use_Utf8_Consistently.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_Producing_And_Consuming_Headers_Should_Use_Utf8_Consistently.cs @@ -43,7 +43,7 @@ public void When_header_bag_contains_unicode_should_round_trip_correctly() }; // Act - var readMessage = new KafkaMessageCreator().CreateMessage(consumeResult); + var readMessage = new KafkaMessageCreator(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)).CreateMessage(consumeResult); // Assert — the non-ASCII characters survive the round-trip Assert.Equal(unicodeValue, readMessage.Header.Bag["unicode_key"]); @@ -84,7 +84,7 @@ public void When_standard_headers_round_trip_should_preserve_values() }; // Act - var readMessage = new KafkaMessageCreator().CreateMessage(consumeResult); + var readMessage = new KafkaMessageCreator(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(Initializer.TestLoggerFactory)).CreateMessage(consumeResult); // Assert — standard Brighter headers round-trip correctly Assert.Equal(message.Header.MessageType, readMessage.Header.MessageType); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_consumer_error_is_followed_by_a_non_fatal_should_still_throw.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_consumer_error_is_followed_by_a_non_fatal_should_still_throw.cs index 30a0af2187..9d109460b0 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_consumer_error_is_followed_by_a_non_fatal_should_still_throw.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_consumer_error_is_followed_by_a_non_fatal_should_still_throw.cs @@ -23,8 +23,8 @@ public When_a_fatal_consumer_error_is_followed_by_a_non_fatal_should_still_throw offsetDefault: AutoOffsetReset.Earliest, numPartitions: 1, replicationFactor: 1, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_producer_error_is_followed_by_a_non_fatal_should_still_throw.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_producer_error_is_followed_by_a_non_fatal_should_still_throw.cs index 188601edd2..7038f3a0e8 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_producer_error_is_followed_by_a_non_fatal_should_still_throw.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_fatal_producer_error_is_followed_by_a_non_fatal_should_still_throw.cs @@ -25,7 +25,7 @@ public When_a_fatal_producer_error_is_followed_by_a_non_fatal_should_still_throw // Keep flush-on-dispose fast: the pre-fix (red) path enqueues a message that can never // be delivered without a broker, and Dispose flushes it. A short timeout bounds that wait. MessageTimeoutMs = 500 - }); + }, loggerFactory: Initializer.TestLoggerFactory); _producer.Init(); } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_consumer_error_follows_a_fatal_error_should_log_as_non_fatal.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_consumer_error_follows_a_fatal_error_should_log_as_non_fatal.cs index fdc1490982..e2d36aad9e 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_consumer_error_follows_a_fatal_error_should_log_as_non_fatal.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_consumer_error_follows_a_fatal_error_should_log_as_non_fatal.cs @@ -26,8 +26,8 @@ public When_a_non_fatal_consumer_error_follows_a_fatal_error_should_log_as_non_f offsetDefault: AutoOffsetReset.Earliest, numPartitions: 1, replicationFactor: 1, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_producer_error_follows_a_fatal_error_should_log_as_non_fatal.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_producer_error_follows_a_fatal_error_should_log_as_non_fatal.cs index bdee85f055..5d0e6e8b3f 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_producer_error_follows_a_fatal_error_should_log_as_non_fatal.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_a_non_fatal_producer_error_follows_a_fatal_error_should_log_as_non_fatal.cs @@ -25,7 +25,7 @@ public When_a_non_fatal_producer_error_follows_a_fatal_error_should_log_as_non_f { Topic = new RoutingKey("test.topic"), MakeChannels = OnMissingChannel.Assume - }); + }, loggerFactory: Initializer.TestLoggerFactory); // No Init()/Send() required: HandleError only sets the latch and logs, so the producer never // needs to contact a broker for this test. } diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_creating_channel_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_creating_channel_with_dlq_subscription_should_pass_routing_keys.cs index 9927511040..b48a888706 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_creating_channel_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_creating_channel_with_dlq_subscription_should_pass_routing_keys.cs @@ -43,7 +43,7 @@ public KafkaMessageConsumerFactoryDLQTests() { Name = "Kafka Consumer Factory DLQ Test", BootStrapServers = new[] { "localhost:9092" } - }); + }, loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_downgrades_an_error_code_should_log_at_downgraded_level.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_downgrades_an_error_code_should_log_at_downgraded_level.cs index 732e29224b..b0339c5381 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_downgrades_an_error_code_should_log_at_downgraded_level.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_downgrades_an_error_code_should_log_at_downgraded_level.cs @@ -29,8 +29,8 @@ public When_error_log_level_downgrades_an_error_code_should_log_at_downgraded_le numPartitions: 1, replicationFactor: 1, makeChannels: OnMissingChannel.Assume, - errorLogLevel: error => error.Code == ErrorCode.Local_TimedOut ? LogLevel.Debug : LogLevel.Warning - ); + errorLogLevel: error => error.Code == ErrorCode.Local_TimedOut ? LogLevel.Debug : LogLevel.Warning, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_is_null_should_log_fatal_at_error_and_non_fatal_at_warning.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_is_null_should_log_fatal_at_error_and_non_fatal_at_warning.cs index 6716a38345..b1268b5343 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_is_null_should_log_fatal_at_error_and_non_fatal_at_warning.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_is_null_should_log_fatal_at_error_and_non_fatal_at_warning.cs @@ -27,8 +27,8 @@ public When_error_log_level_is_null_should_log_fatal_at_error_and_non_fatal_at_w offsetDefault: AutoOffsetReset.Earliest, numPartitions: 1, replicationFactor: 1, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_returns_none_should_suppress_logging.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_returns_none_should_suppress_logging.cs index fb6158d7e8..fc38966014 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_returns_none_should_suppress_logging.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_returns_none_should_suppress_logging.cs @@ -28,8 +28,8 @@ public When_error_log_level_returns_none_should_suppress_logging() numPartitions: 1, replicationFactor: 1, makeChannels: OnMissingChannel.Assume, - errorLogLevel: error => error.Code == ErrorCode.Local_TimedOut ? LogLevel.None : LogLevel.Warning - ); + errorLogLevel: error => error.Code == ErrorCode.Local_TimedOut ? LogLevel.None : LogLevel.Warning, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_suppresses_logs_should_still_latch_fatal_error.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_suppresses_logs_should_still_latch_fatal_error.cs index 324984478c..bc5661b58b 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_suppresses_logs_should_still_latch_fatal_error.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_error_log_level_suppresses_logs_should_still_latch_fatal_error.cs @@ -26,8 +26,8 @@ public When_error_log_level_suppresses_logs_should_still_latch_fatal_error() numPartitions: 1, replicationFactor: 1, makeChannels: OnMissingChannel.Assume, - errorLogLevel: _ => LogLevel.None - ); + errorLogLevel: _ => LogLevel.None, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_forwards_scheduler_to_consumers.cs index 3e8da1b7d5..706bbad798 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_forwards_scheduler_to_consumers.cs @@ -37,7 +37,7 @@ public class When_kafka_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange — channel factory wrapping a consumer factory, no scheduler initially - var consumerFactory = new KafkaMessageConsumerFactory(_configuration); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var channelFactory = new ChannelFactory(consumerFactory); var scheduler = new StubMessageScheduler(); @@ -53,7 +53,7 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new KafkaMessageConsumerFactory(_configuration, scheduler); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, Initializer.TestLoggerFactory, scheduler); var channelFactory = new ChannelFactory(consumerFactory); // Assert — channel factory reads from the consumer factory diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_has_scheduler_should_pass_to_consumers.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_has_scheduler_should_pass_to_consumers.cs index 8eb853f168..5ebe6937a6 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_has_scheduler_should_pass_to_consumers.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_channel_factory_has_scheduler_should_pass_to_consumers.cs @@ -25,7 +25,7 @@ public class When_kafka_channel_factory_has_scheduler_should_pass_to_consumers public void Should_implement_channel_factory_with_scheduler() { // Arrange - var consumerFactory = new KafkaMessageConsumerFactory(_configuration); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var channelFactory = new ChannelFactory(consumerFactory); // Assert @@ -37,7 +37,7 @@ public void Should_create_sync_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new KafkaMessageConsumerFactory(_configuration); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -54,7 +54,7 @@ public void Should_create_async_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new KafkaMessageConsumerFactory(_configuration); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -70,7 +70,7 @@ public void Should_create_async_channel_when_scheduler_set() public void Should_create_channel_without_scheduler_for_backward_compat() { // Arrange — no scheduler set - var consumerFactory = new KafkaMessageConsumerFactory(_configuration); + var consumerFactory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var channelFactory = new ChannelFactory(consumerFactory); // Act diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_creates_consumer_should_pass_scheduler.cs index 82fed7d829..ab1d826b7d 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -48,7 +48,7 @@ public void Should_create_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new KafkaMessageConsumerFactory(_configuration, scheduler); + var factory = new KafkaMessageConsumerFactory(_configuration, Initializer.TestLoggerFactory, scheduler); // Act var consumer = factory.Create(_subscription); @@ -63,7 +63,7 @@ public void Should_create_async_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new KafkaMessageConsumerFactory(_configuration, scheduler); + var factory = new KafkaMessageConsumerFactory(_configuration, Initializer.TestLoggerFactory, scheduler); // Act var consumer = factory.CreateAsync(_subscription); @@ -77,7 +77,7 @@ public void Should_create_async_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange — factory constructed without a scheduler (backward compat) - var factory = new KafkaMessageConsumerFactory(_configuration); + var factory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); // Act var consumer = factory.Create(_subscription); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_scheduler_set_after_construction.cs index 3b8590c5ba..7b2c836287 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_kafka_consumer_factory_scheduler_set_after_construction.cs @@ -37,7 +37,7 @@ public class When_kafka_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new KafkaMessageConsumerFactory(_configuration); + var factory = new KafkaMessageConsumerFactory(_configuration, loggerFactory: Initializer.TestLoggerFactory); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -52,7 +52,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new KafkaMessageConsumerFactory(_configuration, scheduler); + var factory = new KafkaMessageConsumerFactory(_configuration, Initializer.TestLoggerFactory, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -63,7 +63,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new KafkaMessageConsumerFactory(_configuration, originalScheduler); + var factory = new KafkaMessageConsumerFactory(_configuration, Initializer.TestLoggerFactory, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_nacking_a_message_without_offset_should_not_throw.cs b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_nacking_a_message_without_offset_should_not_throw.cs index dd6daa5f79..b8082cdade 100644 --- a/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_nacking_a_message_without_offset_should_not_throw.cs +++ b/tests/Paramore.Brighter.Kafka.Tests/MessagingGateway/When_nacking_a_message_without_offset_should_not_throw.cs @@ -23,8 +23,8 @@ public When_nacking_a_message_without_offset_should_not_throw() offsetDefault: AutoOffsetReset.Earliest, numPartitions: 1, replicationFactor: 1, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: Initializer.TestLoggerFactory); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Helpers/Base/MqttTestClassBase.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Helpers/Base/MqttTestClassBase.cs index 08c80a4668..a7d4bb27e6 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Helpers/Base/MqttTestClassBase.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Helpers/Base/MqttTestClassBase.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using MQTTnet; -using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.MQTT; using Paramore.Brighter.MQTT.Tests.MessagingGateway.Helpers.Server; using Paramore.Test.Helpers.Base; @@ -44,7 +43,7 @@ public abstract class MqttTestClassBase : TestClassBase protected MqttTestClassBase(string clientID, string topicPrefix, ITestOutputHelper testOutputHelper) : base(testOutputHelper) { - ApplicationLogging.LoggerFactory = LoggerFactory.Create(configure => + var loggerFactory = LoggerFactory.Create(configure => { configure.Services.AddSingleton(TestOutputHelper); configure.Services.AddSingleton(); @@ -56,7 +55,7 @@ protected MqttTestClassBase(string clientID, string topicPrefix, ITestOutputHelp IPAddress serverIPAddress = IPAddress.Any; int serverPort = MqttTestServer.GetRandomServerPort(); - MqttTestServer = MqttTestServer.CreateTestMqttServer(s_mqttFactory, true, ApplicationLogging.CreateLogger(), serverIPAddress, serverPort, null, TestDisplayName); + MqttTestServer = MqttTestServer.CreateTestMqttServer(s_mqttFactory, true, loggerFactory.CreateLogger(), serverIPAddress, serverPort, null, TestDisplayName); var mqttProducerConfig = new MqttMessagingGatewayProducerConfiguration { @@ -65,7 +64,7 @@ protected MqttTestClassBase(string clientID, string topicPrefix, ITestOutputHelp TopicPrefix = topicPrefix }; - MqttMessagePublisher mqttMessagePublisher = new(mqttProducerConfig); + MqttMessagePublisher mqttMessagePublisher = new(mqttProducerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); MessageProducerAsync = new MqttMessageProducer(mqttMessagePublisher, new Publication()); MqttMessagingGatewayConsumerConfiguration mqttConsumerConfig = new() @@ -76,7 +75,7 @@ protected MqttTestClassBase(string clientID, string topicPrefix, ITestOutputHelp ClientID = clientID }; - MessageConsumerAsync = new MqttMessageConsumer(mqttConsumerConfig); + MessageConsumerAsync = new MqttMessageConsumer(mqttConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } /// diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index 3ea1e18e9f..b38a8bc536 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -61,7 +61,7 @@ public MqttMessageConsumerRejectDeliveryErrorDlqAsyncTests(ITestOutputHelper out TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-DlqAsync-Producer" }; - var publisher = new MqttMessagePublisher(producerConfig); + var publisher = new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _sourceProducer = new MqttMessageProducer(publisher, new Publication()); //Arrange — source consumer with DLQ routing key @@ -74,8 +74,8 @@ public MqttMessageConsumerRejectDeliveryErrorDlqAsyncTests(ITestOutputHelper out }; _sourceConsumer = new MqttMessageConsumer( consumerConfig, - deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX) - ); + deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Arrange — DLQ consumer var dlqConsumerConfig = new MqttMessagingGatewayConsumerConfiguration @@ -85,7 +85,7 @@ public MqttMessageConsumerRejectDeliveryErrorDlqAsyncTests(ITestOutputHelper out TopicPrefix = DLQ_TOPIC_PREFIX, ClientID = "BrighterTests-DlqAsyncTarget-Consumer" }; - _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig); + _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_mqtt_consumer_creates_producer_should_configure_and_dispose_correctly.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_mqtt_consumer_creates_producer_should_configure_and_dispose_correctly.cs index 64bb684a9f..b3bc876862 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_mqtt_consumer_creates_producer_should_configure_and_dispose_correctly.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_mqtt_consumer_creates_producer_should_configure_and_dispose_correctly.cs @@ -63,7 +63,7 @@ public MqttConsumerProducerConfigAndDisposeTests(ITestOutputHelper testOutputHel TopicPrefix = topicPrefix }; - _producer = new MqttMessageProducer(new MqttMessagePublisher(producerConfig), new Publication()); + _producer = new MqttMessageProducer(new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), new Publication()); _scheduler = new SpySchedulerSync(); @@ -76,7 +76,7 @@ public MqttConsumerProducerConfigAndDisposeTests(ITestOutputHelper testOutputHel }; // Create consumer WITH scheduler - this is the constructor parameter being tested - _consumer = new MqttMessageConsumer(consumerConfig, _scheduler); + _consumer = new MqttMessageConsumer(consumerConfig, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index 0306c73588..b603812fc6 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -61,7 +61,7 @@ public MqttMessageConsumerRejectDeliveryErrorDlqTests(ITestOutputHelper outputHe TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-DlqSource-Producer" }; - var publisher = new MqttMessagePublisher(producerConfig); + var publisher = new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _sourceProducer = new MqttMessageProducer(publisher, new Publication()); //Arrange — source consumer with DLQ routing key @@ -74,8 +74,8 @@ public MqttMessageConsumerRejectDeliveryErrorDlqTests(ITestOutputHelper outputHe }; _sourceConsumer = new MqttMessageConsumer( consumerConfig, - deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX) - ); + deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Arrange — DLQ consumer to verify rejected messages arrive var dlqConsumerConfig = new MqttMessagingGatewayConsumerConfiguration @@ -85,7 +85,7 @@ public MqttMessageConsumerRejectDeliveryErrorDlqTests(ITestOutputHelper outputHe TopicPrefix = DLQ_TOPIC_PREFIX, ClientID = "BrighterTests-DlqTarget-Consumer" }; - _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig); + _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_return_true.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_return_true.cs index b7608b33bd..8b5ff105b5 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_return_true.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_return_true.cs @@ -59,7 +59,7 @@ public MqttMessageConsumerRejectNoChannelsTests(ITestOutputHelper outputHelper) TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-NoChannels-Producer" }; - var publisher = new MqttMessagePublisher(producerConfig); + var publisher = new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _sourceProducer = new MqttMessageProducer(publisher, new Publication()); //Arrange — source consumer with NO DLQ or invalid message routing keys @@ -70,7 +70,7 @@ public MqttMessageConsumerRejectNoChannelsTests(ITestOutputHelper outputHelper) TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-NoChannels-Consumer" }; - _sourceConsumer = new MqttMessageConsumer(consumerConfig); + _sourceConsumer = new MqttMessageConsumer(consumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 99c01d2aa8..25ec9e235c 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -61,7 +61,7 @@ public MqttMessageConsumerRejectUnacceptableFallbackToDlqTests(ITestOutputHelper TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-Fallback-Producer" }; - var publisher = new MqttMessagePublisher(producerConfig); + var publisher = new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _sourceProducer = new MqttMessageProducer(publisher, new Publication()); //Arrange — source consumer with DLQ only (no invalid message routing key) @@ -74,8 +74,8 @@ public MqttMessageConsumerRejectUnacceptableFallbackToDlqTests(ITestOutputHelper }; _sourceConsumer = new MqttMessageConsumer( consumerConfig, - deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX) - ); + deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Arrange — DLQ consumer (should receive the fallback) var dlqConsumerConfig = new MqttMessagingGatewayConsumerConfiguration @@ -85,7 +85,7 @@ public MqttMessageConsumerRejectUnacceptableFallbackToDlqTests(ITestOutputHelper TopicPrefix = DLQ_TOPIC_PREFIX, ClientID = "BrighterTests-FallbackDlq-Consumer" }; - _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig); + _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index c9805c6503..4065faa80d 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -63,7 +63,7 @@ public MqttMessageConsumerRejectUnacceptableInvalidChannelTests(ITestOutputHelpe TopicPrefix = SOURCE_TOPIC_PREFIX, ClientID = "BrighterTests-Invalid-Producer" }; - var publisher = new MqttMessagePublisher(producerConfig); + var publisher = new MqttMessagePublisher(producerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _sourceProducer = new MqttMessageProducer(publisher, new Publication()); //Arrange — source consumer with both DLQ and invalid message routing keys @@ -77,8 +77,8 @@ public MqttMessageConsumerRejectUnacceptableInvalidChannelTests(ITestOutputHelpe _sourceConsumer = new MqttMessageConsumer( consumerConfig, deadLetterRoutingKey: new RoutingKey(DLQ_TOPIC_PREFIX), - invalidMessageRoutingKey: new RoutingKey(INVALID_TOPIC_PREFIX) - ); + invalidMessageRoutingKey: new RoutingKey(INVALID_TOPIC_PREFIX), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Arrange — invalid message consumer var invalidConsumerConfig = new MqttMessagingGatewayConsumerConfiguration @@ -88,7 +88,7 @@ public MqttMessageConsumerRejectUnacceptableInvalidChannelTests(ITestOutputHelpe TopicPrefix = INVALID_TOPIC_PREFIX, ClientID = "BrighterTests-InvalidTarget-Consumer" }; - _invalidConsumer = new MqttMessageConsumer(invalidConsumerConfig); + _invalidConsumer = new MqttMessageConsumer(invalidConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Arrange — DLQ consumer (should NOT receive the message) var dlqConsumerConfig = new MqttMessagingGatewayConsumerConfiguration @@ -98,7 +98,7 @@ public MqttMessageConsumerRejectUnacceptableInvalidChannelTests(ITestOutputHelpe TopicPrefix = DLQ_TOPIC_PREFIX, ClientID = "BrighterTests-InvalidDlq-Consumer" }; - _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig); + _dlqConsumer = new MqttMessageConsumer(dlqConsumerConfig, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_creates_channel_should_use_consumer_factory.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_creates_channel_should_use_consumer_factory.cs index d263baa018..c3741a2655 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_creates_channel_should_use_consumer_factory.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_creates_channel_should_use_consumer_factory.cs @@ -27,7 +27,7 @@ public When_mqtt_channel_factory_creates_channel_should_use_consumer_factory() ClientID = "test-client" }; - _consumerFactory = new MqttMessageConsumerFactory(configuration); + _consumerFactory = new MqttMessageConsumerFactory(configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _channelFactory = new ChannelFactory(_consumerFactory); } diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_forwards_scheduler_to_consumers.cs index e528877fcd..48f02782ba 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_channel_factory_forwards_scheduler_to_consumers.cs @@ -39,7 +39,7 @@ public class When_mqtt_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange - var consumerFactory = new MqttMessageConsumerFactory(_configuration); + var consumerFactory = new MqttMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); var scheduler = new StubMessageScheduler(); @@ -55,7 +55,7 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new MqttMessageConsumerFactory(_configuration, scheduler); + var consumerFactory = new MqttMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var channelFactory = new ChannelFactory(consumerFactory); // Assert — channel factory reads from the consumer factory diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_creates_consumer_should_pass_scheduler.cs index 67cc1b86c3..703a52ef87 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -18,7 +18,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() { // Arrange var scheduler = new StubMessageScheduler(); - var factory = new MqttMessageConsumerFactory(_configuration, scheduler); + var factory = new MqttMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.Create(new Subscription( @@ -39,7 +39,7 @@ public void Should_create_async_consumer_when_scheduler_provided() { // Arrange var scheduler = new StubMessageScheduler(); - var factory = new MqttMessageConsumerFactory(_configuration, scheduler); + var factory = new MqttMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.CreateAsync(new Subscription( @@ -59,7 +59,7 @@ public void Should_create_async_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange - var factory = new MqttMessageConsumerFactory(_configuration); + var factory = new MqttMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act var consumer = factory.Create(new Subscription( diff --git a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_scheduler_set_after_construction.cs index b0daacaad0..55603bbd5d 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/MessagingGateway/When_mqtt_consumer_factory_scheduler_set_after_construction.cs @@ -39,7 +39,7 @@ public class When_mqtt_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new MqttMessageConsumerFactory(_configuration); + var factory = new MqttMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -54,7 +54,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new MqttMessageConsumerFactory(_configuration, scheduler); + var factory = new MqttMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -65,7 +65,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new MqttMessageConsumerFactory(_configuration, originalScheduler); + var factory = new MqttMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.MQTT.Tests/When_creating_mqtt_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.MQTT.Tests/When_creating_mqtt_consumer_with_dlq_subscription_should_pass_routing_keys.cs index d41e4f0332..c0b428c21d 100644 --- a/tests/Paramore.Brighter.MQTT.Tests/When_creating_mqtt_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.MQTT.Tests/When_creating_mqtt_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -57,7 +57,7 @@ public MqttMessageConsumerFactoryDlqTests() ClientID = "BrighterTests-FactoryDlq" }; - _factory = new MqttMessageConsumerFactory(configuration); + _factory = new MqttMessageConsumerFactory(configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/Legacy/When_mssql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/Legacy/When_mssql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs index ed7f4f9cf7..3461cdbe7c 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/Legacy/When_mssql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/Legacy/When_mssql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs @@ -197,10 +197,10 @@ private MsSqlOutbox OutboxFor(string tableName) _connectionString, databaseName: "brightertests", outBoxTableName: tableName, - binaryMessagePayload: false)); + binaryMessagePayload: false), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private IAmAnInboxSync InboxFor(string tableName) - => new MsSqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName)); + => new MsSqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private static Message CreateMessage() => new( diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_mssql_history_should_remain_in_dbo.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_mssql_history_should_remain_in_dbo.cs index 9950493276..081a76dc5c 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_mssql_history_should_remain_in_dbo.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_mssql_history_should_remain_in_dbo.cs @@ -52,13 +52,13 @@ public MsSqlGlobalScopeHistoryPlacementTests() schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.Global); + scope: MigrationHistoryScope.Global, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_dbo_schema_runner_should_still_create_it_in_dbo.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_dbo_schema_runner_should_still_create_it_in_dbo.cs index 855d689c94..8220f1a1a0 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_dbo_schema_runner_should_still_create_it_in_dbo.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_dbo_schema_runner_should_still_create_it_in_dbo.cs @@ -62,13 +62,13 @@ public class MsSqlHistoryTableNonDboSchemaTests : IAsyncLifetime public MsSqlHistoryTableNonDboSchemaTests() { var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_during_begin_async_runner_should_not_call_commit_or_rollback.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_during_begin_async_runner_should_not_call_commit_or_rollback.cs index c101295a9c..d359760a44 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_during_begin_async_runner_should_not_call_commit_or_rollback.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_during_begin_async_runner_should_not_call_commit_or_rollback.cs @@ -103,7 +103,7 @@ public async Task When_mssql_advisory_lock_acquire_throws_during_begin_async_run // resource, proving the failed acquire left no lingering server-side state. If the // partial transaction had been left undisposed, the next BeginTransaction on the same // connection-pool slot would block or error. - var freshRunner = new MsSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5)); + var freshRunner = new MsSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await freshRunner.MigrateAsync( _tableName, schemaName: null, BoxType.Outbox, freshHint, CancellationToken.None); @@ -159,7 +159,8 @@ public SpyingMsSqlBoxMigrationRunner( IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout, IMsSqlAdvisoryLock advisoryLock) - : base(catalog, configuration, lockTimeout, advisoryLock) + : base(catalog, configuration, lockTimeout, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, advisoryLock) { } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_runner_should_propagate_distinguishable_exception_types.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_runner_should_propagate_distinguishable_exception_types.cs index 7592784f29..514923a385 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_runner_should_propagate_distinguishable_exception_types.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_advisory_lock_acquire_throws_runner_should_propagate_distinguishable_exception_types.cs @@ -99,7 +99,7 @@ public async Task When_acquire_succeeds_it_should_complete_migration() var fakeLock = new FakeMsSqlAdvisoryLock(throwOnAcquire: null); var runner = new MsSqlBoxMigrationRunner( - catalog, config, TimeSpan.FromSeconds(30), fakeLock); + catalog, config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act @@ -125,7 +125,7 @@ private async Task AssertRunnerPropagatesAcquireException(Exception toThrow) var fakeLock = new FakeMsSqlAdvisoryLock(throwOnAcquire: toThrow); var runner = new MsSqlBoxMigrationRunner( - catalog, config, TimeSpan.FromSeconds(30), fakeLock); + catalog, config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert — runner surfaces the same exception type without wrapping. diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_bootstraps_legacy_v1_outbox_to_v7_it_should_complete_within_migration_lock_timeout.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_bootstraps_legacy_v1_outbox_to_v7_it_should_complete_within_migration_lock_timeout.cs index 0f513e1b78..78f5c1bcfa 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_bootstraps_legacy_v1_outbox_to_v7_it_should_complete_within_migration_lock_timeout.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_bootstraps_legacy_v1_outbox_to_v7_it_should_complete_within_migration_lock_timeout.cs @@ -49,13 +49,13 @@ public async Task When_mssql_bootstraps_legacy_v1_outbox_to_v7_it_should_complet MsSqlOutboxLegacySeeder.SeedAtV(SeedVersion, _connectionString, _tableName); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, MigrationLockTimeout); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, MigrationLockTimeout, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — measure the wall-clock time of the public ProvisionAsync entry point. var stopwatch = Stopwatch.StartNew(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_commit_throws_rollback_should_be_best_effort_without_throwing.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_commit_throws_rollback_should_be_best_effort_without_throwing.cs index a88b310c22..e4827e2053 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_commit_throws_rollback_should_be_best_effort_without_throwing.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_commit_throws_rollback_should_be_best_effort_without_throwing.cs @@ -161,7 +161,9 @@ public CommitThrowingMsSqlBoxMigrationRunner( TimeSpan lockTimeout, ILogger logger, Exception commitFailure) - : base(catalog, configuration, lockTimeout, advisoryLock: null, logger: logger) + : base(catalog, configuration, lockTimeout, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, + advisoryLock: null, logger: logger) { _commitFailure = commitFailure; } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs index fe143730db..1c7fffcf9c 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs @@ -119,13 +119,13 @@ private MsSqlOutboxProvisioner BuildOutboxProvisioner(MigrationHistoryScope scop schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private void EnsureSchemaExists(string schemaName) => diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs index e7f312c0b5..399ce5dd5b 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs @@ -38,13 +38,13 @@ public async Task When_mssql_inbox_provisioner_detects_payload_mode_mismatch_it_ _connectionString, inboxTableName: _tableName, binaryMessagePayload: true); - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync( diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index 225b095a73..08cf29b497 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -26,13 +26,13 @@ public MsSqlInboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs index 112dc8ae8a..bc62b07571 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs @@ -25,13 +25,13 @@ public MsSqlInboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index d5b7869cb7..06f6af9278 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -46,13 +46,13 @@ public MsSqlInboxNonDefaultSchemaTests() _connectionString, inboxTableName: _tableName, schemaName: NonDefaultSchema); - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs index 4a498ff4dd..1221e22f3f 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs @@ -52,13 +52,13 @@ public async Task When_mssql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, inboxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_migration_is_cancelled_mid_flight_it_should_rollback_with_cancellation_token_none.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_migration_is_cancelled_mid_flight_it_should_rollback_with_cancellation_token_none.cs index 622077f462..2f9c6ae450 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_migration_is_cancelled_mid_flight_it_should_rollback_with_cancellation_token_none.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_migration_is_cancelled_mid_flight_it_should_rollback_with_cancellation_token_none.cs @@ -84,7 +84,7 @@ public async Task When_mssql_migration_is_cancelled_mid_flight_it_should_rollbac // short-circuited by a signalled CT the sp_getapplock would still be held by the // zombied transaction and the second BeginAsync would block until the 5s timeout // elapsed and throw MigrationLockDeadlockException. - var freshRunner = new MsSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5)); + var freshRunner = new MsSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await freshRunner.MigrateAsync( _tableName, schemaName: null, BoxType.Outbox, staleHint, CancellationToken.None); @@ -139,7 +139,8 @@ public CancellingMsSqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout) - : base(catalog, configuration, lockTimeout) + : base(catalog, configuration, lockTimeout, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs index 560d2c2bac..fcaa22ac65 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs @@ -142,13 +142,13 @@ private MsSqlOutboxProvisioner BuildOutboxProvisioner(MigrationHistoryScope scop schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private MsSqlInboxProvisioner BuildInboxProvisioner(MigrationHistoryScope scope) @@ -159,13 +159,13 @@ private MsSqlInboxProvisioner BuildInboxProvisioner(MigrationHistoryScope scope) schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private void EnsureSchemaExists(string schemaName) => diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_detects_table_missing_headerbag_discriminator_it_should_return_negative_one.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_detects_table_missing_headerbag_discriminator_it_should_return_negative_one.cs index 596f65e8b4..e53e924091 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_detects_table_missing_headerbag_discriminator_it_should_return_negative_one.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_detects_table_missing_headerbag_discriminator_it_should_return_negative_one.cs @@ -62,13 +62,13 @@ public async Task When_mssql_outbox_detects_table_missing_headerbag_discriminato Assert.Equal(-1, detected); //Act — provisioner end-to-end - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter outbox and names the discriminator @@ -101,13 +101,13 @@ public async Task When_mssql_inbox_detects_table_missing_commandbody_discriminat Assert.Equal(-1, detected); //Act — provisioner end-to-end - var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter inbox and names the discriminator @@ -141,13 +141,13 @@ public async Task When_mssql_outbox_detects_headerbag_present_but_no_v1_columns_ Assert.Equal(0, detected); //Act — provisioner end-to-end - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies the table as not matching any known schema version diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs index 9d56080ee1..2ede5268d6 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_detects_payload_mode_mismatch_it_should_throw.cs @@ -38,13 +38,13 @@ public async Task When_mssql_outbox_provisioner_detects_payload_mode_mismatch_it _connectionString, outBoxTableName: _tableName, binaryMessagePayload: true); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync( diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index 6ea92bb35a..d471f7cd6e 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -26,13 +26,13 @@ public MsSqlOutboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs index d3a25616ac..67529fae41 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs @@ -25,13 +25,13 @@ public MsSqlOutboxProvisionerIdempotencyTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs index 3b662be439..27703f3621 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs @@ -25,13 +25,13 @@ public MsSqlOutboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index a1f88d0ac5..295b0e3c63 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -59,13 +59,13 @@ public MsSqlOutboxNonDefaultSchemaTests() _connectionString, outBoxTableName: _tableName, schemaName: NonDefaultSchema); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8_with_history_advanced.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8_with_history_advanced.cs index acbc7524dc..d1de6e3f77 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8_with_history_advanced.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8_with_history_advanced.cs @@ -57,13 +57,13 @@ public async Task When_mssql_outbox_table_is_bootstrapped_at_vk_it_should_upgrad SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs index 25641fdeb1..1cce6b7f94 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs @@ -52,13 +52,13 @@ public MsSqlPerSchemaIdempotencyTests() schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs index 290de2cacc..fc3d66e014 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs @@ -51,13 +51,13 @@ public MsSqlOutboxProvisionerSchemaTests() schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs index 0be928f05a..1971f3e092 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs @@ -49,7 +49,7 @@ public MsSqlPerSchemaNullSchemaNameTests() schemaName: null); _runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_acquires_lock_resource_should_be_qualified_by_schema.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_acquires_lock_resource_should_be_qualified_by_schema.cs index 8aafdd52ad..90a1c7ba71 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_acquires_lock_resource_should_be_qualified_by_schema.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_acquires_lock_resource_should_be_qualified_by_schema.cs @@ -66,7 +66,7 @@ public async Task When_mssql_runner_acquires_lock_resource_should_be_qualified_b throwOnAcquire: new InvalidOperationException("acquire-then-stop probe for lock-resource assertion")); var runner = new MsSqlBoxMigrationRunner( - new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), fakeLock); + new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs index 17fad3fa13..423348c49e 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs @@ -58,7 +58,7 @@ public async Task When_mssql_runner_fails_mid_chain_it_should_roll_back_all_migr realMigrations, BrokenVersion, BrokenUpScript); var brokenCatalog = new BrokenChainCatalog(brokenMigrations, realCatalog.FreshInstallDdl(config)); - var brokenRunner = new MsSqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30)); + var brokenRunner = new MsSqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var staleHint = new BoxTableState(TableExists: true, HistoryExists: false, CurrentVersion: SeedVersion); //Act + Assert (1) — broken V6 in chain: runner throws and rolls back everything. @@ -78,13 +78,13 @@ await Assert.ThrowsAsync(() => brokenRunner.MigrateAsync( Assert.Equal(1, GetMarkerRowCount()); //Act + Assert (2) — retry with the real migration list: bootstrap path completes V4..V7. - var realRunner = new MsSqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30)); + var realRunner = new MsSqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - realRunner); + realRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await provisioner.ProvisionAsync(); //Assert — exactly one synthetic V3 + one applied per V4..V7 (no duplicates). diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs index 7bd65b9b69..a1ee555cd8 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs @@ -41,7 +41,7 @@ public class MsSqlRunnerFreshPathRecheckTests : IAsyncLifetime public MsSqlRunnerFreshPathRecheckTests() { _config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - _runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30)); + _runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs index df3f5b8e09..60d2de9d48 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs @@ -72,7 +72,7 @@ private async Task AssertMigrationListRejected(IReadOnlyList m var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); var malformedCatalog = new MalformedListCatalog(malformed); - var runner = new MsSqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert — runner refuses to begin migration when the version sequence is malformed. diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs index cc7c5d78b5..be66e87c00 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs @@ -59,7 +59,7 @@ public async Task When_mssql_runner_is_constructed_without_lock_timeout_default_ // Detection-helper ctor is the ONLY one that exposes `lockTimeout` as optional. The // backward-compat ctor (MsSqlBoxMigrationRunner.cs:76) takes it as required, so it // cannot exercise the default path. - var runner = new MsSqlBoxMigrationRunner(new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock); + var runner = new MsSqlBoxMigrationRunner(new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs index d0e6b4c677..7433b89ba4 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_mssql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs @@ -49,13 +49,13 @@ public async Task When_mssql_table_has_spec_0023_era_history_at_v1_it_should_tra var columnsBefore = GetTableColumns(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_multiple_mssql_provisioners_run_concurrently_they_should_not_corrupt_state.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_multiple_mssql_provisioners_run_concurrently_they_should_not_corrupt_state.cs index 2758d118db..c7742ff9a4 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_multiple_mssql_provisioners_run_concurrently_they_should_not_corrupt_state.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_multiple_mssql_provisioners_run_concurrently_they_should_not_corrupt_state.cs @@ -37,13 +37,13 @@ public async Task When_multiple_mssql_provisioners_run_concurrently_they_should_ new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner2 = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await Task.WhenAll( diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_mssql_runner_should_throw_clear_error.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_mssql_runner_should_throw_clear_error.cs index 14f10903ca..7095ef13fc 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_mssql_runner_should_throw_clear_error.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_mssql_runner_should_throw_clear_error.cs @@ -122,13 +122,13 @@ private MsSqlOutboxProvisioner BuildOutboxProvisioner(string connectionString, M schemaName: _schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } // Builds a least-privilege login/user (see file-header note for the rationale) and returns a diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_mssql_runner_should_throw.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_mssql_runner_should_throw.cs index 93a7545b2f..3a71def105 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_mssql_runner_should_throw.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_mssql_runner_should_throw.cs @@ -61,13 +61,13 @@ public async Task When_per_schema_scope_is_selected_with_an_unsafe_schema_name_m schemaName: UnsafeSchemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act var thrown = await Record.ExceptionAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_provisioning_runs_mssql_runner_should_log_resolved_history_schema_and_scope.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_provisioning_runs_mssql_runner_should_log_resolved_history_schema_and_scope.cs index a3371b5caa..b7813d36e4 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_provisioning_runs_mssql_runner_should_log_resolved_history_schema_and_scope.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_provisioning_runs_mssql_runner_should_log_resolved_history_schema_and_scope.cs @@ -71,6 +71,7 @@ public async Task When_provisioning_runs_mssql_runner_should_log_resolved_histor var capturingLogger = new StructuredCapturingLogger(); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, logger: capturingLogger, scope: MigrationHistoryScope.PerSchema); var provisioner = new MsSqlOutboxProvisioner( @@ -78,7 +79,7 @@ public async Task When_provisioning_runs_mssql_runner_should_log_resolved_histor new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); @@ -123,13 +124,13 @@ public async Task When_seed_runs_during_global_to_per_schema_flip_runner_should_ schemaName: _schemaName); var globalRunner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), globalConfig, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.Global); + scope: MigrationHistoryScope.Global, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var globalProvisioner = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), globalConfig, - globalRunner); + globalRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await globalProvisioner.ProvisionAsync(); // Sanity-check the arranged precondition so a regression in the Global path can't masquerade @@ -154,6 +155,7 @@ public async Task When_seed_runs_during_global_to_per_schema_flip_runner_should_ schemaName: _schemaName); var perSchemaRunner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), perSchemaConfig, TimeSpan.FromSeconds(30), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, logger: capturingLogger, tracer: tracer, scope: MigrationHistoryScope.PerSchema); @@ -162,7 +164,7 @@ public async Task When_seed_runs_during_global_to_per_schema_flip_runner_should_ new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), perSchemaConfig, - perSchemaRunner); + perSchemaRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await perSchemaProvisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs index 75466d23b7..f47af25788 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs @@ -55,13 +55,13 @@ public async Task When_two_outbox_provisioners_race_on_legacy_table_they_should_ new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); @@ -101,13 +101,13 @@ public async Task When_two_inbox_provisioners_race_on_legacy_table_they_should_p new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new MsSqlInboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlInboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MsSqlBoxMigrationRunner(new MsSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_tenants_use_per_schema_scope_each_should_get_independent_history.cs b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_tenants_use_per_schema_scope_each_should_get_independent_history.cs index 0b216dd584..4b3055bd50 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_tenants_use_per_schema_scope_each_should_get_independent_history.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/BoxProvisioning/When_two_mssql_tenants_use_per_schema_scope_each_should_get_independent_history.cs @@ -101,13 +101,13 @@ private MsSqlOutboxProvisioner BuildPerSchemaProvisioner(string schemaName) schemaName: schemaName); var runner = new MsSqlBoxMigrationRunner( new MsSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MsSqlOutboxProvisioner( new MsSqlBoxDetectionHelper(), new MsSqlOutboxMigrationCatalog(), new MsSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private void EnsureSchemaExists(string schemaName) => diff --git a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlCausationTrackingInboxTest.cs b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlCausationTrackingInboxTest.cs index 06181a3863..a46151572d 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlCausationTrackingInboxTest.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlCausationTrackingInboxTest.cs @@ -17,7 +17,7 @@ protected override void BeforeEachTest() _configuration = new RelationalDatabaseConfiguration( Tests.Configuration.DefaultConnectingString, inboxTableName: $"{Tests.Configuration.TablePrefix}{Uuid.New():N}"); - _inbox = new MsSqlInbox(_configuration); + _inbox = new MsSqlInbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); base.BeforeEachTest(); } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxAsyncTest.cs b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxAsyncTest.cs index 74259be521..4060c35949 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxAsyncTest.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxAsyncTest.cs @@ -14,7 +14,7 @@ public class MsSqlTextInboxAsyncTest : RelationalDatabaseInboxAsyncTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new MsSqlInbox(configuration); + return new MsSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override async Task CreateInboxTableAsync(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxTest.cs b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxTest.cs index d16c30d82d..e7a7768aea 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxTest.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/Inbox/MsSqlTextInboxTest.cs @@ -13,7 +13,7 @@ public class MsSqlTextInboxTest : RelationalDatabaseInboxTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new MsSqlInbox(configuration); + return new MsSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override void CreateInboxTable(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.MSSQL.Tests/LockingProvider/MsSqlLockingTest.cs b/tests/Paramore.Brighter.MSSQL.Tests/LockingProvider/MsSqlLockingTest.cs index 0af3d2bc62..1d48841f29 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/LockingProvider/MsSqlLockingTest.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/LockingProvider/MsSqlLockingTest.cs @@ -10,6 +10,6 @@ public class MsSqlLockingTest : RelationalDatabaseDistributedLockingAsyncTest protected override IDistributedLock CreateDistributedLock() { Tests.Configuration.EnsureDatabaseExists(Configuration.ConnectionString); - return new MsSqlLockingProvider(new MsSqlConnectionProvider(Configuration)); + return new MsSqlLockingProvider(new MsSqlConnectionProvider(Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/MsSqlMessageGatewayProvider.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/MsSqlMessageGatewayProvider.cs index 44c7f0d5c8..1fd2530d30 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/MsSqlMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/MsSqlMessageGatewayProvider.cs @@ -69,8 +69,8 @@ public IAmAChannelSync CreateChannel(MsSqlSubscription subscription) _configuration = testHelper.QueueConfiguration; } - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channel = new ChannelFactory(consumerFactory).CreateSyncChannel(subscription); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channel = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).CreateSyncChannel(subscription); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) { @@ -92,8 +92,8 @@ public Task CreateChannelAsync( _configuration = testHelper.QueueConfiguration; } - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channel = new ChannelFactory(consumerFactory).CreateAsyncChannel(subscription); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channel = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).CreateAsyncChannel(subscription); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) { @@ -112,7 +112,7 @@ public IAmAMessageProducerSync CreateProducer(Publication publication) _configuration = testHelper.QueueConfiguration; } - var producers = new MsSqlMessageProducerFactory(_configuration, [publication]).Create(); + var producers = new MsSqlMessageProducerFactory(_configuration, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); var producer = producers.First().Value; return (IAmAMessageProducerSync)producer; } @@ -129,7 +129,7 @@ public async Task CreateProducerAsync( _configuration = testHelper.QueueConfiguration; } - var producers = await new MsSqlMessageProducerFactory(_configuration, [publication]) + var producers = await new MsSqlMessageProducerFactory(_configuration, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsync(); var producer = producers.First().Value; return (IAmAMessageProducerAsync)producer; @@ -199,8 +199,8 @@ public Message GetMessageFromDeadLetterQueue(MsSqlSubscription subscription) var dlqConsumer = new MsSqlMessageConsumer( _configuration, - dlqSubscription.RoutingKey.Value - ); + dlqSubscription.RoutingKey.Value, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { @@ -239,8 +239,8 @@ public async Task GetMessageFromDeadLetterQueueAsync( var dlqConsumer = new MsSqlMessageConsumer( _configuration, - dlqSubscription.RoutingKey.Value - ); + dlqSubscription.RoutingKey.Value, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent.cs index 9ce00b5208..6a5e69f189 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent.cs @@ -32,9 +32,9 @@ public PostMessageTest() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() { Topic = routingKey }] - ).Create(); - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + [new() { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_async.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_async.cs index d34eb2e660..84855ec724 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_async.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_async.cs @@ -32,9 +32,9 @@ public PostMessageTestAsync() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() { Topic = routingKey }] - ).CreateAsync().Result; - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).CreateAsync(sub); + [new() { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().Result; + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs index a67a58ae78..8ab787885d 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs @@ -30,9 +30,9 @@ public OrderTest() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() { Topic = routingKey }] - ).Create(); - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + [new() { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs index c721c383e9..347b582fab 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs @@ -30,9 +30,9 @@ public OrderTestAsync() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() { Topic = routingKey }] - ).CreateAsync().Result; - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).CreateAsync(sub); + [new() { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().Result; + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_creating_mssql_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_creating_mssql_consumer_with_dlq_subscription_should_pass_routing_keys.cs index 3929052e85..8a2db1b072 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_creating_mssql_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_creating_mssql_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -40,7 +40,7 @@ public MsSqlMessageConsumerFactoryDlqTests() { //Arrange var configuration = new RelationalDatabaseConfiguration("Server=127.0.0.1,11433;Database=BrighterTests;User Id=sa;Password=Password1!;TrustServerCertificate=true"); - _factory = new MsSqlMessageConsumerFactory(configuration); + _factory = new MsSqlMessageConsumerFactory(configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_forwards_scheduler_to_consumers.cs index 8479186667..acea7b7c6d 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_forwards_scheduler_to_consumers.cs @@ -33,8 +33,8 @@ public class When_mssql_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var scheduler = new StubMessageScheduler(); // Act — set scheduler on the channel factory @@ -49,8 +49,8 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, scheduler); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); // Assert — channel factory reads from the consumer factory Assert.Same(scheduler, ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_has_scheduler_should_pass_to_consumers.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_has_scheduler_should_pass_to_consumers.cs index 3b20f296ba..6e307245eb 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_has_scheduler_should_pass_to_consumers.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_channel_factory_has_scheduler_should_pass_to_consumers.cs @@ -24,8 +24,8 @@ public class When_mssql_channel_factory_has_scheduler_should_pass_to_consumers public void Should_implement_channel_factory_with_scheduler() { // Arrange - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); // Assert Assert.IsAssignableFrom(channelFactory); @@ -36,8 +36,8 @@ public void Should_create_sync_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; // Act @@ -53,8 +53,8 @@ public void Should_create_async_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; // Act @@ -69,8 +69,8 @@ public void Should_create_async_channel_when_scheduler_set() public void Should_create_channel_without_scheduler_for_backward_compat() { // Arrange — no scheduler set - var consumerFactory = new MsSqlMessageConsumerFactory(_configuration); - var channelFactory = new ChannelFactory(consumerFactory); + var consumerFactory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + var channelFactory = new ChannelFactory(consumerFactory, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); // Act var channel = channelFactory.CreateSyncChannel(_subscription); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_creates_producer_should_configure_and_dispose_correctly.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_creates_producer_should_configure_and_dispose_correctly.cs index dbbe67064f..8019ee1c12 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_creates_producer_should_configure_and_dispose_correctly.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_creates_producer_should_configure_and_dispose_correctly.cs @@ -54,7 +54,7 @@ public void When_requeuing_with_delay_should_wire_scheduler_to_producer() var consumer = new MsSqlMessageConsumer( _testHelper.QueueConfiguration, _topicName, - scheduler); + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var topic = new RoutingKey(_topicName); var message = new Message( @@ -81,7 +81,7 @@ public void When_disposing_after_requeue_should_not_throw() var consumer = new MsSqlMessageConsumer( _testHelper.QueueConfiguration, _topicName, - scheduler); + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var topic = new RoutingKey(_topicName); var message = new Message( @@ -103,7 +103,7 @@ public void When_disposing_without_requeue_should_not_throw() var consumer = new MsSqlMessageConsumer( _testHelper.QueueConfiguration, _topicName, - scheduler); + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act & Assert - dispose without producer creation should not throw var exception = Record.Exception(() => consumer.Dispose()); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_creates_consumer_should_pass_scheduler.cs index 3bc7b464e2..e115c7f7b4 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -46,7 +46,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new MsSqlMessageConsumerFactory(_configuration, scheduler); + var factory = new MsSqlMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.Create(_subscription); @@ -61,7 +61,7 @@ public void Should_create_async_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new MsSqlMessageConsumerFactory(_configuration, scheduler); + var factory = new MsSqlMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.CreateAsync(_subscription); @@ -75,7 +75,7 @@ public void Should_create_async_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange — factory constructed without a scheduler (backward compat) - var factory = new MsSqlMessageConsumerFactory(_configuration); + var factory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act var consumer = factory.Create(_subscription); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_scheduler_set_after_construction.cs index 6bc7ec6335..840add2b7a 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_factory_scheduler_set_after_construction.cs @@ -33,7 +33,7 @@ public class When_mssql_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new MsSqlMessageConsumerFactory(_configuration); + var factory = new MsSqlMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -48,7 +48,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new MsSqlMessageConsumerFactory(_configuration, scheduler); + var factory = new MsSqlMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -59,7 +59,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new MsSqlMessageConsumerFactory(_configuration, originalScheduler); + var factory = new MsSqlMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_async_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_async_with_delay_should_use_producer.cs index 99ca636c76..a592d571da 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_async_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_async_with_delay_should_use_producer.cs @@ -55,7 +55,7 @@ public MssqlConsumerRequeueTestsAsync() _consumer = new MsSqlMessageConsumer( testHelper.QueueConfiguration, topicName, - _scheduler); + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_delay_should_use_producer.cs index 85e5a9e0da..fe4efb9740 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_delay_should_use_producer.cs @@ -53,7 +53,7 @@ public When_mssql_consumer_requeues_with_delay_should_use_producer() _consumer = new MsSqlMessageConsumer( testHelper.QueueConfiguration, topicName, - _scheduler); + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_zero_delay_should_use_direct_queue.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_zero_delay_should_use_direct_queue.cs index 82a65a60c4..633e763fd9 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_zero_delay_should_use_direct_queue.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_mssql_consumer_requeues_with_zero_delay_should_use_direct_queue.cs @@ -59,8 +59,8 @@ public When_mssql_consumer_requeues_with_zero_delay_should_use_direct_queue() new MessageHeader(myCommand.Id, topic, MessageType.MT_COMMAND), new MessageBody(JsonSerializer.Serialize(myCommand, JsonSerialisationOptions.Options))); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); - _consumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, _topicName); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _consumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, _topicName, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged.cs index 3997909354..feade1fbf0 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged.cs @@ -30,9 +30,9 @@ public PurgeTest() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() {Topic = _routingKey}] - ).Create(); - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + [new() {Topic = _routingKey}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs index 2fc78cf8cf..de1f717901 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs @@ -30,10 +30,10 @@ public PurgeTestAsync() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new() { Topic = _routingKey }] - ).CreateAsync().Result; + [new() { Topic = _routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().Result; - _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).CreateAsync(sub); + _consumer = new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index e59ce0e6bc..34b9c34bd0 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -53,11 +53,11 @@ public MsSqlMessageConsumerDeliveryErrorDlqTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Reactor); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); - _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic); + _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index f7e2899eb3..45c1640e8a 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -54,11 +54,11 @@ public MsSqlMessageConsumerDeliveryErrorDlqAsyncTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Proactor); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); - _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic); + _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_log_warning.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_log_warning.cs index 68f398b08c..3d0699298a 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_log_warning.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_log_warning.cs @@ -51,9 +51,9 @@ public MsSqlMessageConsumerNoChannelsConfiguredTests() _topic, messagePumpType: MessagePumpType.Reactor); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 9ee6fff434..ddea83e0a6 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -54,11 +54,11 @@ public MsSqlMessageConsumerUnacceptableFallbackToDlqTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Reactor); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); - _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic); + _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index cea32294d7..79ac416fcc 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -56,12 +56,12 @@ public MsSqlMessageConsumerUnacceptableInvalidChannelTests() invalidMessageRoutingKey: invalidTopic, messagePumpType: MessagePumpType.Reactor); - _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration); + _producer = new MsSqlMessageProducer(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration).Create(sub); + _consumer = (MsSqlMessageConsumer)new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); - _invalidConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, invalidTopic); - _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic); + _invalidConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, invalidTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _dlqConsumer = new MsSqlMessageConsumer(testHelper.QueueConfiguration, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message.cs index 30be88361a..229ea68043 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message.cs @@ -42,9 +42,9 @@ public MsSqlMessageConsumerRequeueTests() _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new Publication {Topic = new RoutingKey(_topic)}] - ).Create(); - _channelFactory = new ChannelFactory(new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration)); + [new Publication {Topic = new RoutingKey(_topic)}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); + _channelFactory = new ChannelFactory(new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs index 2adcb6ab48..c41f9ff64a 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs @@ -40,9 +40,9 @@ public MsSqlMessageConsumerRequeueTestsAsync() new ChannelName(_topic), new RoutingKey(_topic)); _producerRegistry = new MsSqlProducerRegistryFactory( testHelper.QueueConfiguration, - [new Publication {Topic = new RoutingKey(_topic)}] - ).CreateAsync().Result; - _channelFactory = new ChannelFactory(new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration)); + [new Publication {Topic = new RoutingKey(_topic)}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().Result; + _channelFactory = new ChannelFactory(new MsSqlMessageConsumerFactory(testHelper.QueueConfiguration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } [Fact] diff --git a/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Binary/MSSQLBinaryOutboxProvider.cs b/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Binary/MSSQLBinaryOutboxProvider.cs index b0949248c1..1dce971d14 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Binary/MSSQLBinaryOutboxProvider.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Binary/MSSQLBinaryOutboxProvider.cs @@ -20,12 +20,12 @@ public class MSSQLBinaryOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxPro public IAmAnOutboxSync CreateOutbox() { - return new MsSqlOutbox(_configuration); + return new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new MsSqlOutbox(_configuration); + return new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -75,13 +75,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new MsSqlOutbox(_configuration); + var outbox = new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new MsSqlOutbox(_configuration); + var outbox = new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Text/MSSQLTextOutboxProvider.cs b/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Text/MSSQLTextOutboxProvider.cs index e5c6816897..a7bd7ddcaa 100644 --- a/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Text/MSSQLTextOutboxProvider.cs +++ b/tests/Paramore.Brighter.MSSQL.Tests/Outbox/Text/MSSQLTextOutboxProvider.cs @@ -18,12 +18,12 @@ public class MSSQLTextOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxProvi public IAmAnOutboxSync CreateOutbox() { - return new MsSqlOutbox(_configuration); + return new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new MsSqlOutbox(_configuration); + return new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -73,13 +73,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new MsSqlOutbox(_configuration); + var outbox = new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new MsSqlOutbox(_configuration); + var outbox = new MsSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message.cs b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message.cs index 4b9427cce1..4de7c8767e 100644 --- a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message.cs @@ -36,7 +36,7 @@ public LargeMessagePayloadUnwrapTests() var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, messageTransformerFactory, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message_async.cs b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message_async.cs index dba3d3bc56..6a3b382f87 100644 --- a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_unwrapping_a_large_message_async.cs @@ -37,7 +37,7 @@ public LargeMessagePayloadAsyncUnwrapTests() var messageTransformerFactory = new SimpleMessageTransformerFactoryAsync(_ => new ClaimCheckTransformer(_luggageStore, _luggageStore)); - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, messageTransformerFactory, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message.cs b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message.cs index 9873718c3b..c675121b0d 100644 --- a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message.cs +++ b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message.cs @@ -41,7 +41,7 @@ public LargeMessagePayloadWrapTests () _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactoryAsync); + _pipelineBuilder = new TransformPipelineBuilder(mapperRegistry, transformerFactoryAsync, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message_async.cs b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message_async.cs index 6e54fc1495..006e0328f2 100644 --- a/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message_async.cs +++ b/tests/Paramore.Brighter.MongoDb.Tests/Transformers/When_wrapping_a_large_message_async.cs @@ -43,7 +43,7 @@ public LargeMessagePayloadAsyncWrapTests () _publication = new Publication { Topic = new RoutingKey("MyLargeCommand"), RequestType = typeof(MyLargeCommand) }; - _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, InstrumentationOptions.All); + _pipelineBuilder = new TransformPipelineBuilderAsync(mapperRegistry, transformerFactoryAsync, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, InstrumentationOptions.All); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/Legacy/When_mysql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/Legacy/When_mysql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs index 060d26230f..9b2bee399f 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/Legacy/When_mysql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/Legacy/When_mysql_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs @@ -193,10 +193,10 @@ private MySqlOutbox OutboxFor(string tableName) _connectionString, databaseName: "brightertests", outBoxTableName: tableName, - binaryMessagePayload: false)); + binaryMessagePayload: false), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private IAmAnInboxSync InboxFor(string tableName) - => new MySqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName)); + => new MySqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private void ExecuteDdl(string ddl) { diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_multiple_mysql_provisioners_run_concurrently_they_should_not_corrupt_state.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_multiple_mysql_provisioners_run_concurrently_they_should_not_corrupt_state.cs index 0c2071230a..ab258a6a24 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_multiple_mysql_provisioners_run_concurrently_they_should_not_corrupt_state.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_multiple_mysql_provisioners_run_concurrently_they_should_not_corrupt_state.cs @@ -29,13 +29,13 @@ public async Task When_multiple_mysql_provisioners_run_concurrently_they_should_ new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner2 = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act await Task.WhenAll( diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_advisory_release_lock_returns_non_true_runner_should_log_warning_and_complete_normally.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_advisory_release_lock_returns_non_true_runner_should_log_warning_and_complete_normally.cs index d426c76d83..645832d1af 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_advisory_release_lock_returns_non_true_runner_should_log_warning_and_complete_normally.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_advisory_release_lock_returns_non_true_runner_should_log_warning_and_complete_normally.cs @@ -74,7 +74,7 @@ public async Task When_release_returns_true_it_should_complete_migration_with_no var capturingLogger = new CapturingLogger(); var runner = new MySqlBoxMigrationRunner( - new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), fakeLock, capturingLogger); + new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock, capturingLogger); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act @@ -97,7 +97,7 @@ private async Task AssertSingleWarningAndMigrationCompletes(bool? releaseResult, var capturingLogger = new CapturingLogger(); var runner = new MySqlBoxMigrationRunner( - new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), fakeLock, capturingLogger); + new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock, capturingLogger); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act — runner must not throw despite the non-true release result. diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs index d24bfaf813..da54290e1e 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs @@ -26,13 +26,13 @@ public async Task When_inbox_provisioner_runs_on_fresh_database_it_should_create var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _freshTableName); - var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act await provisioner.ProvisionAsync(); @@ -74,13 +74,13 @@ public async Task When_inbox_provisioner_runs_against_existing_table_without_his var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _existingTableName); - var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index cb295f3236..d734bec95c 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -50,13 +50,13 @@ public async Task InitializeAsync() _baseConnectionString, inboxTableName: _tableName, schemaName: _nonDefaultDatabase); - var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs index d0b2b8a1d6..64c247c962 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs @@ -51,13 +51,13 @@ public async Task When_mysql_inbox_table_is_bootstrapped_at_v1_it_should_upgrade await SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, inboxTableName: _tableName); - var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_migration_is_cancelled_mid_flight_it_should_release_get_lock.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_migration_is_cancelled_mid_flight_it_should_release_get_lock.cs index 6448870591..89ce7f46b5 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_migration_is_cancelled_mid_flight_it_should_release_get_lock.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_migration_is_cancelled_mid_flight_it_should_release_get_lock.cs @@ -81,7 +81,7 @@ public async Task When_mysql_migration_is_cancelled_mid_flight_it_should_release // BeginAsync calls GET_LOCK on the same per-table lock resource completes the migration // normally; the 5s lock timeout would expire and surface as MigrationLockDeadlockException // if the lock were still held. - var freshRunner = new MySqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5)); + var freshRunner = new MySqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await freshRunner.MigrateAsync( _tableName, schemaName: null, BoxType.Outbox, staleHint, CancellationToken.None); @@ -136,7 +136,8 @@ public CancellingMySqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout) - : base(catalog, configuration, lockTimeout) + : base(catalog, configuration, lockTimeout, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs index e26c414211..275ebcae94 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs @@ -61,13 +61,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter outbox and names the discriminator. @@ -99,13 +99,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter inbox and names the discriminator. @@ -138,13 +138,13 @@ await ExecuteDdl( Assert.Equal(0, detected); //Act — provisioner end-to-end. - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies the table as not matching any known schema version. diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index 1ceba8664e..30dd82afa3 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -20,13 +20,13 @@ public MySqlOutboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs index 5bcd1de282..0b6edacac9 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs @@ -19,13 +19,13 @@ public OutboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index f6812fe9e6..11aa1d1b9f 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -63,13 +63,13 @@ public async Task InitializeAsync() _connectionInDefaultDb, outBoxTableName: _tableName, schemaName: _nonDefaultDatabase); - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs index 8c2404a7fd..46c36367f8 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs @@ -58,13 +58,13 @@ public async Task When_mysql_outbox_table_is_bootstrapped_at_vk_it_should_upgrad await SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_per_schema_scope_is_selected_it_should_keep_history_in_connection_database_and_not_throw.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_per_schema_scope_is_selected_it_should_keep_history_in_connection_database_and_not_throw.cs index e112cd8e7a..6a40cad68c 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_per_schema_scope_is_selected_it_should_keep_history_in_connection_database_and_not_throw.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_per_schema_scope_is_selected_it_should_keep_history_in_connection_database_and_not_throw.cs @@ -113,13 +113,13 @@ private MySqlOutboxProvisioner BuildProvisioner(RelationalDatabaseConfiguration // Evident data: PerSchema is the scope under test. var runner = new MySqlBoxMigrationRunner( new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private async Task EnsureDatabaseExistsAsync(string databaseName) diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_pre_lock_detects_negative_version_it_should_clamp_to_zero.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_pre_lock_detects_negative_version_it_should_clamp_to_zero.cs index 460b877f14..2412d3fc7a 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_pre_lock_detects_negative_version_it_should_clamp_to_zero.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_pre_lock_detects_negative_version_it_should_clamp_to_zero.cs @@ -67,7 +67,7 @@ public async Task When_mysql_outbox_provisioner_pre_lock_detection_returns_negat new MySqlOutboxMigrationCatalog(), new NoOpPayloadValidator(), config, - migrationRunner); + migrationRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); @@ -91,7 +91,7 @@ public async Task When_mysql_inbox_provisioner_pre_lock_detection_returns_negati new MySqlInboxMigrationCatalog(), new NoOpPayloadValidator(), config, - migrationRunner); + migrationRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs index f43d893b97..1401382353 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs @@ -50,7 +50,7 @@ public async Task When_existing_outbox_body_is_text_and_provisioner_is_configure new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -72,7 +72,7 @@ public async Task When_existing_outbox_body_is_binary_and_provisioner_is_configu new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fails_mid_chain_it_should_resume_from_max_applied_version_on_next_invocation.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fails_mid_chain_it_should_resume_from_max_applied_version_on_next_invocation.cs index fe12edd90a..b740720601 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fails_mid_chain_it_should_resume_from_max_applied_version_on_next_invocation.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fails_mid_chain_it_should_resume_from_max_applied_version_on_next_invocation.cs @@ -58,7 +58,7 @@ public async Task When_mysql_runner_fails_mid_chain_it_should_resume_from_max_ap realMigrations, BrokenVersion, BrokenUpScript); var brokenCatalog = new BrokenChainCatalog(brokenMigrations, realCatalog.FreshInstallDdl(config)); - var brokenRunner = new MySqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30)); + var brokenRunner = new MySqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var staleHint = new BoxTableState(TableExists: true, HistoryExists: false, CurrentVersion: SeedVersion); //Act + Assert (1) — broken V6 in chain: runner throws, but per ADR §5a MySQL implicit-DDL @@ -92,13 +92,13 @@ await Assert.ThrowsAsync(() => brokenRunner.MigrateAsync( Assert.Equal(1, await GetMarkerRowCount()); //Act + Assert (2) — retry with the real migration list via the provisioner. - var realRunner = new MySqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30)); + var realRunner = new MySqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - realRunner); + realRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await provisioner.ProvisionAsync(); //Assert — V6..V8 now applied; total exactly 6 history rows (V3 synthetic + V4..V8 applied). diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs index 14fd89dac5..2330791d6d 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_fresh_path_acquires_lock_it_should_re_check_table_existence_before_creating.cs @@ -43,7 +43,7 @@ public class MySqlRunnerFreshPathRecheckTests : IAsyncLifetime public MySqlRunnerFreshPathRecheckTests() { _config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - _runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30)); + _runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs index 3add0b1d43..9ff6b39a29 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs @@ -70,7 +70,7 @@ private async Task AssertMigrationListRejected(IReadOnlyList m //Arrange — do NOT create the box table (so fresh path is selected). var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); var malformedCatalog = new MalformedListCatalog(malformed); - var runner = new MySqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert — runner refuses to begin migration when the version sequence is malformed. diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs index 80338253ec..368fa5bfcb 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs @@ -58,7 +58,7 @@ public async Task When_mysql_runner_is_constructed_without_lock_timeout_default_ // Detection-helper ctor is the ONLY one that exposes `lockTimeout` as optional. The // backward-compat ctor (MySqlBoxMigrationRunner.cs:84) takes it as required, so it // cannot exercise the default path. - var runner = new MySqlBoxMigrationRunner(new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock); + var runner = new MySqlBoxMigrationRunner(new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs index 638df1825f..b9f306a07f 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs @@ -67,13 +67,13 @@ public async Task When_mysql_runner_runs_two_provisioners_in_distinct_schemas_th new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), configA, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), configA, TimeSpan.FromSeconds(30), holdingLock)); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), configA, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, holdingLock), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), configB, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), configB, TimeSpan.FromSeconds(1))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), configB, TimeSpan.FromSeconds(1), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act var taskA = Task.Run(() => provisionerA.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs index 9176e5e8ed..0bb9e4d993 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_mysql_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs @@ -49,13 +49,13 @@ public async Task When_mysql_table_has_spec_0023_era_history_at_v1_it_should_tra var columnsBefore = await GetTableColumns(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_two_mysql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_two_mysql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs index 7fc101aaae..399ac007ad 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_two_mysql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/BoxProvisioning/When_two_mysql_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs @@ -54,13 +54,13 @@ public async Task When_two_outbox_provisioners_race_on_legacy_table_they_should_ new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new MySqlOutboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlOutboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); @@ -99,13 +99,13 @@ public async Task When_two_inbox_provisioners_race_on_legacy_table_they_should_p new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new MySqlInboxProvisioner( new MySqlBoxDetectionHelper(), new MySqlInboxMigrationCatalog(), new MySqlPayloadModeValidator(), config, - new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new MySqlBoxMigrationRunner(new MySqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlCausationTrackingInboxTest.cs b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlCausationTrackingInboxTest.cs index 4d1b703e3d..d8226fcb21 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlCausationTrackingInboxTest.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlCausationTrackingInboxTest.cs @@ -16,7 +16,7 @@ protected override void BeforeEachTest() _configuration = new RelationalDatabaseConfiguration( Const.DefaultConnectingString, inboxTableName: $"{Const.TablePrefix}{Uuid.New():N}"); - _inbox = new MySqlInbox(_configuration); + _inbox = new MySqlInbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); base.BeforeEachTest(); } diff --git a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxAsyncTest.cs b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxAsyncTest.cs index 3ae2289e12..8b4dde05a9 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxAsyncTest.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxAsyncTest.cs @@ -13,7 +13,7 @@ public class MySqlTextInboxAsyncTest : RelationalDatabaseInboxAsyncTests protected override bool JsonMessagePayload => false; protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) - => new MySqlInbox(configuration); + => new MySqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); protected override async Task CreateInboxTableAsync(RelationalDatabaseConfiguration configuration) { diff --git a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxTest.cs b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxTest.cs index 9b85db1cbf..5cfaaeb526 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxTest.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Inbox/MySqlTextInboxTest.cs @@ -12,7 +12,7 @@ public class MySqlTextInboxTest : RelationalDatabaseInboxTests protected override bool JsonMessagePayload => false; protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) - => new MySqlInbox(configuration); + => new MySqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); protected override void CreateInboxTable(RelationalDatabaseConfiguration configuration) { diff --git a/tests/Paramore.Brighter.MySQL.Tests/Locking/MySqlLockingTest.cs b/tests/Paramore.Brighter.MySQL.Tests/Locking/MySqlLockingTest.cs index d1cde0153c..c256e7a2ef 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Locking/MySqlLockingTest.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Locking/MySqlLockingTest.cs @@ -9,6 +9,6 @@ public class MySqlLockingTest : RelationalDatabaseDistributedLockingAsyncTest protected override string DefaultConnectingString => Const.DefaultConnectingString; protected override IDistributedLock CreateDistributedLock() { - return new MySqlLockingProvider(new MySqlConnectionProvider(Configuration)); + return new MySqlLockingProvider(new MySqlConnectionProvider(Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } } diff --git a/tests/Paramore.Brighter.MySQL.Tests/Outbox/Binary/MySQLBinaryOutboxProvider.cs b/tests/Paramore.Brighter.MySQL.Tests/Outbox/Binary/MySQLBinaryOutboxProvider.cs index 4e4a09fc77..990a447669 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Outbox/Binary/MySQLBinaryOutboxProvider.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Outbox/Binary/MySQLBinaryOutboxProvider.cs @@ -19,12 +19,12 @@ public class MySQLBinaryOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxPro public IAmAnOutboxSync CreateOutbox() { - return new MySqlOutbox(_configuration); + return new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new MySqlOutbox(_configuration); + return new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -70,13 +70,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new MySqlOutbox(_configuration); + var outbox = new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new MySqlOutbox(_configuration); + var outbox = new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.MySQL.Tests/Outbox/Text/MySQLTextOutboxProvider.cs b/tests/Paramore.Brighter.MySQL.Tests/Outbox/Text/MySQLTextOutboxProvider.cs index c9c1ced297..61e4f7c25e 100644 --- a/tests/Paramore.Brighter.MySQL.Tests/Outbox/Text/MySQLTextOutboxProvider.cs +++ b/tests/Paramore.Brighter.MySQL.Tests/Outbox/Text/MySQLTextOutboxProvider.cs @@ -19,12 +19,12 @@ public class MySQLTextOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxProvi public IAmAnOutboxSync CreateOutbox() { - return new MySqlOutbox(_configuration); + return new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new MySqlOutbox(_configuration); + return new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -70,13 +70,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new MySqlOutbox(_configuration); + var outbox = new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new MySqlOutbox(_configuration); + var outbox = new MySqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/Legacy/When_postgres_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/Legacy/When_postgres_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs index 8dd3916594..e79db14e4d 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/Legacy/When_postgres_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/Legacy/When_postgres_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs @@ -200,10 +200,10 @@ private PostgreSqlOutbox OutboxFor(string tableName) _connectionString, databaseName: "brightertests", outBoxTableName: tableName, - binaryMessagePayload: false)); + binaryMessagePayload: false), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private IAmAnInboxSync InboxFor(string tableName) - => new PostgreSqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName)); + => new PostgreSqlInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private void ExecuteDdl(string ddl) { diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_postgres_history_should_remain_in_public.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_postgres_history_should_remain_in_public.cs index 434f4238f2..8937c137c5 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_postgres_history_should_remain_in_public.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_global_scope_is_used_with_a_non_default_schema_postgres_history_should_remain_in_public.cs @@ -60,13 +60,13 @@ public PostgreSqlGlobalScopeHistoryPlacementTests() schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.Global); + scope: MigrationHistoryScope.Global, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_public_schema_runner_should_still_create_it_in_public.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_public_schema_runner_should_still_create_it_in_public.cs index f819e376e4..95ac468008 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_public_schema_runner_should_still_create_it_in_public.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_history_table_exists_in_a_non_public_schema_runner_should_still_create_it_in_public.cs @@ -50,13 +50,13 @@ public PostgreSqlHistoryTableNonPublicSchemaTests() // first on search_path that has (or can hold) the relation. _runnerConnectionString = _setupConnectionString.TrimEnd(';') + $";Search Path={CollidingSchema},public"; var config = new RelationalDatabaseConfiguration(_runnerConnectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_many_postgres_provisioners_race_to_create_history_table_they_should_all_complete.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_many_postgres_provisioners_race_to_create_history_table_they_should_all_complete.cs index 3cbc8d3e27..5e7eb89156 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_many_postgres_provisioners_race_to_create_history_table_they_should_all_complete.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_many_postgres_provisioners_race_to_create_history_table_they_should_all_complete.cs @@ -95,13 +95,13 @@ public async Task When_many_postgres_provisioners_race_to_create_history_table_t var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: tableName); var runner = new PostgreSqlBoxMigrationRunner( - new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), tracer: tracer); + new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), tracer: tracer, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await provisioner.ProvisionAsync(); })).ToArray(); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_multiple_postgresql_provisioners_run_concurrently_they_should_not_corrupt_state.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_multiple_postgresql_provisioners_run_concurrently_they_should_not_corrupt_state.cs index 1d9cc15d8a..5f1b5e122e 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_multiple_postgresql_provisioners_run_concurrently_they_should_not_corrupt_state.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_multiple_postgresql_provisioners_run_concurrently_they_should_not_corrupt_state.cs @@ -27,17 +27,17 @@ public async Task When_multiple_postgresql_provisioners_run_concurrently_they_sh outBoxTableName: _tableName); var provisioner1 = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner2 = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await Task.WhenAll( diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_postgres_runner_should_throw_clear_error.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_postgres_runner_should_throw_clear_error.cs index e0b9d8b789..ab7007479a 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_postgres_runner_should_throw_clear_error.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_flip_cannot_read_legacy_history_table_postgres_runner_should_throw_clear_error.cs @@ -131,13 +131,13 @@ private PostgreSqlOutboxProvisioner BuildOutboxProvisioner(string connectionStri schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } // Builds a least-privilege role (see file-header note for the rationale) and returns a connection diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_postgres_runner_should_throw.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_postgres_runner_should_throw.cs index 6b8479d4a6..28931da084 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_postgres_runner_should_throw.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_per_schema_scope_is_selected_with_an_unsafe_schema_name_postgres_runner_should_throw.cs @@ -63,13 +63,13 @@ public async Task When_per_schema_scope_is_selected_with_an_unsafe_schema_name_p schemaName: UnsafeSchemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act var thrown = await Record.ExceptionAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_advisory_unlock_returns_false_runner_should_log_warning_and_complete_normally.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_advisory_unlock_returns_false_runner_should_log_warning_and_complete_normally.cs index cb9bd05c58..436ae4e9f9 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_advisory_unlock_returns_false_runner_should_log_warning_and_complete_normally.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_advisory_unlock_returns_false_runner_should_log_warning_and_complete_normally.cs @@ -61,7 +61,7 @@ public async Task When_postgres_advisory_unlock_returns_false_runner_should_log_ var capturingLogger = new CapturingLogger(); var runner = new PostgreSqlBoxMigrationRunner( - new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), fakeLock, capturingLogger); + new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, fakeLock, capturingLogger); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act — runner must not throw despite the false release result. diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs index 7c9748b998..d7ccfabcb7 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_deployment_flips_from_global_to_per_schema_it_should_not_re_run_applied_migrations.cs @@ -129,13 +129,13 @@ private PostgreSqlOutboxProvisioner BuildOutboxProvisioner(MigrationHistoryScope schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private async Task EnsureSchemaExistsAsync(string schemaName) diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_detection_helper_receives_null_schema_name_it_should_substitute_public.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_detection_helper_receives_null_schema_name_it_should_substitute_public.cs index f686127f26..ab8f79a854 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_detection_helper_receives_null_schema_name_it_should_substitute_public.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_detection_helper_receives_null_schema_name_it_should_substitute_public.cs @@ -49,7 +49,7 @@ await ExecuteDdl( await EnsureHistoryTable(); await SeedHistoryRow(tableName, schemaName: "public", migrationVersion: 3); - var helper = new PostgreSqlBoxDetectionHelper(); + var helper = new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); await using var connection = new NpgsqlConnection(_connectionString); await connection.OpenAsync(); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_migration_is_cancelled_mid_flight_it_should_rollback_and_release_session_lock.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_migration_is_cancelled_mid_flight_it_should_rollback_and_release_session_lock.cs index 6aeead1989..acfdf0f802 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_migration_is_cancelled_mid_flight_it_should_rollback_and_release_session_lock.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_migration_is_cancelled_mid_flight_it_should_rollback_and_release_session_lock.cs @@ -83,7 +83,7 @@ public async Task When_postgres_migration_is_cancelled_mid_flight_it_should_roll // BeginAsync calls pg_advisory_lock on the same per-table lock resource completes the // migration normally; the 5s lock timeout would expire and surface as // MigrationLockDeadlockException if the lock were still held. - var freshRunner = new PostgreSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5)); + var freshRunner = new PostgreSqlBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await freshRunner.MigrateAsync( _tableName, schemaName: null, BoxType.Outbox, staleHint, CancellationToken.None); @@ -137,7 +137,8 @@ public CancellingPostgreSqlBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration, TimeSpan lockTimeout) - : base(catalog, configuration, lockTimeout) + : base(catalog, configuration, lockTimeout, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs index 7f65067e96..216d17a429 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_and_inbox_both_flip_from_global_to_per_schema_seed_should_run_for_both.cs @@ -146,13 +146,13 @@ private PostgreSqlOutboxProvisioner BuildOutboxProvisioner(MigrationHistoryScope schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private PostgreSqlInboxProvisioner BuildInboxProvisioner(MigrationHistoryScope scope) @@ -163,13 +163,13 @@ private PostgreSqlInboxProvisioner BuildInboxProvisioner(MigrationHistoryScope s schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: scope); + scope: scope, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private async Task EnsureSchemaExistsAsync(string schemaName) diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_detects_table_missing_headerbag_it_should_return_negative_one_and_inbox_should_handle_single_version_list.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_detects_table_missing_headerbag_it_should_return_negative_one_and_inbox_should_handle_single_version_list.cs index b2990adb40..06ff3c9202 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_detects_table_missing_headerbag_it_should_return_negative_one_and_inbox_should_handle_single_version_list.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_detects_table_missing_headerbag_it_should_return_negative_one_and_inbox_should_handle_single_version_list.cs @@ -54,7 +54,7 @@ await ExecuteDdl( await using (var connection = new NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); - detected = await new PostgreSqlBoxDetectionHelper().DetectCurrentVersionAsync( + detected = await new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).DetectCurrentVersionAsync( connection, tableName, "public", BoxType.Outbox, migrations, default); } @@ -62,13 +62,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter outbox and names the discriminator. @@ -93,7 +93,7 @@ await ExecuteDdl( await using (var connection = new NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); - detected = await new PostgreSqlBoxDetectionHelper().DetectCurrentVersionAsync( + detected = await new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).DetectCurrentVersionAsync( connection, tableName, "public", BoxType.Inbox, migrations, default); } @@ -101,13 +101,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter inbox and names the discriminator. @@ -133,7 +133,7 @@ await ExecuteDdl( await using (var connection = new NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); - detected = await new PostgreSqlBoxDetectionHelper().DetectCurrentVersionAsync( + detected = await new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).DetectCurrentVersionAsync( connection, tableName, "public", BoxType.Outbox, migrations, default); } @@ -141,13 +141,13 @@ await ExecuteDdl( Assert.Equal(0, detected); //Act — provisioner end-to-end. - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies the table as not matching any known schema version. @@ -184,7 +184,7 @@ contenttype varchar(128) NULL await using (var connection = new NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); - detected = await new PostgreSqlBoxDetectionHelper().DetectCurrentVersionAsync( + detected = await new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).DetectCurrentVersionAsync( connection, tableName, "public", BoxType.Outbox, migrations, default); } @@ -217,7 +217,7 @@ PRIMARY KEY (commandid, contextkey) await using (var connection = new NpgsqlConnection(_connectionString)) { await connection.OpenAsync(); - detected = await new PostgreSqlBoxDetectionHelper().DetectCurrentVersionAsync( + detected = await new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).DetectCurrentVersionAsync( connection, tableName, "public", BoxType.Inbox, migrations, default); } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_provisioner_runs_with_reserved_keyword_table_name_it_should_create_and_populate_table.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_provisioner_runs_with_reserved_keyword_table_name_it_should_create_and_populate_table.cs index 0b1524e60e..5efda1f241 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_provisioner_runs_with_reserved_keyword_table_name_it_should_create_and_populate_table.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_provisioner_runs_with_reserved_keyword_table_name_it_should_create_and_populate_table.cs @@ -35,13 +35,13 @@ public PostgreSqlReservedKeywordTableNameTests() _connectionString, outBoxTableName: ReservedKeywordTableName); _runner = new PostgreSqlBoxMigrationRunner( - new PostgreSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30)); + new PostgreSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), _config, - _runner); + _runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] @@ -96,7 +96,7 @@ SELECT COUNT(1) FROM ""__BrighterMigrationHistory"" // Act + Assert: runtime DML — write a message via the PG outbox and read it back. // Exercises GenerateSqlText override that lowercases-quotes the table name; with the // legacy unquoted form this would emit `INSERT INTO Order ...` and fail at parse. - var outbox = new PostgreSqlOutbox(_config); + var outbox = new PostgreSqlOutbox(_config, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), new RoutingKey("test.topic"), MessageType.MT_COMMAND), new MessageBody("hello reserved keyword")); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs index 8f751c2a06..79b9b4a9e8 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v8.cs @@ -57,13 +57,13 @@ public async Task When_postgres_outbox_table_is_bootstrapped_at_vk_it_should_upg SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs index 21ba43fb89..5d41e0ccad 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_provisioning_runs_twice_it_should_be_idempotent.cs @@ -58,13 +58,13 @@ public PostgreSqlPerSchemaIdempotencyTests() schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs index c378ccbb50..bfebba170a 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_it_should_create_history_table_in_configured_schema.cs @@ -69,13 +69,13 @@ public PostgreSqlOutboxProvisionerSchemaTests() schemaName: _schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs index 8b8fc96212..0b8a792020 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_per_schema_scope_is_selected_with_null_schema_name_it_should_throw_configuration_exception.cs @@ -51,7 +51,7 @@ public PostgreSqlPerSchemaNullSchemaNameTests() schemaName: null); _runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_provisioner_runs_against_existing_table_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_provisioner_runs_against_existing_table_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs index 28a987114f..bc0aeef3ce 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_provisioner_runs_against_existing_table_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_provisioner_runs_against_existing_table_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs @@ -49,11 +49,11 @@ public async Task When_existing_outbox_body_is_text_and_provisioner_is_configure outBoxTableName: _outboxTableName, binaryMessagePayload: true); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -72,11 +72,11 @@ public async Task When_existing_outbox_body_is_bytea_and_provisioner_is_configur outBoxTableName: _outboxTableName, binaryMessagePayload: false); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -95,11 +95,11 @@ public async Task When_existing_inbox_commandbody_is_text_and_provisioner_is_con inboxTableName: _inboxTableName, binaryMessagePayload: true); var provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -118,11 +118,11 @@ public async Task When_existing_inbox_commandbody_is_bytea_and_provisioner_is_co inboxTableName: _inboxTableName, binaryMessagePayload: false); var provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs index 3ec104d28a..62d597c954 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs @@ -59,7 +59,7 @@ public async Task When_postgres_runner_fails_mid_chain_it_should_roll_back_all_m realMigrations, BrokenVersion, BrokenUpScript); var brokenCatalog = new BrokenChainCatalog(brokenMigrations, realCatalog.FreshInstallDdl(config)); - var brokenRunner = new PostgreSqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30)); + var brokenRunner = new PostgreSqlBoxMigrationRunner(brokenCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var staleHint = new BoxTableState(TableExists: true, HistoryExists: false, CurrentVersion: SeedVersion); //Act + Assert (1) — broken V6 in chain: runner throws and rolls back everything. @@ -79,13 +79,13 @@ await Assert.ThrowsAsync(() => brokenRunner.MigrateAsync( Assert.Equal(1, await GetMarkerRowCount()); //Act + Assert (2) — retry with the real migration list: bootstrap path completes V4..V7. - var realRunner = new PostgreSqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30)); + var realRunner = new PostgreSqlBoxMigrationRunner(realCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - realRunner); + realRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await provisioner.ProvisionAsync(); //Assert — exactly one synthetic V3 + one applied per V4..V7 (no duplicates). diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fresh_path_acquires_advisory_lock_it_should_re_check_table_existence_before_creating.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fresh_path_acquires_advisory_lock_it_should_re_check_table_existence_before_creating.cs index 52b55a3c6e..245488417b 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fresh_path_acquires_advisory_lock_it_should_re_check_table_existence_before_creating.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_fresh_path_acquires_advisory_lock_it_should_re_check_table_existence_before_creating.cs @@ -43,7 +43,7 @@ public class PostgreSqlRunnerFreshPathRecheckTests : IAsyncLifetime public PostgreSqlRunnerFreshPathRecheckTests() { _config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - _runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30)); + _runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), _config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs index e00df55d24..3342152090 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs @@ -72,7 +72,7 @@ private async Task AssertMigrationListRejected(IReadOnlyList m var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); var malformedCatalog = new MalformedListCatalog(malformed); - var runner = new PostgreSqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(malformedCatalog, config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert — runner refuses to begin migration when the version sequence is malformed. diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs index 4c9cdb71bc..c4861a438e 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs @@ -58,7 +58,7 @@ public async Task When_postgres_runner_is_constructed_without_lock_timeout_defau // Detection-helper ctor is the ONLY one that exposes `lockTimeout` as optional. The // backward-compat ctor (PostgreSqlBoxMigrationRunner.cs:76) takes it as required, so it // cannot exercise the default path. - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlBoxDetectionHelper(), new PostgreSqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), config, advisoryLock: fakeLock, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs index 30def5fc95..72d2a741ff 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_runner_runs_two_provisioners_in_distinct_schemas_they_should_not_block_each_other.cs @@ -62,17 +62,17 @@ public async Task When_postgres_runner_runs_two_provisioners_in_distinct_schemas _connectionString, outBoxTableName: _tableName, schemaName: _billingSchema); var provisionerA = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), configA, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), configA, TimeSpan.FromSeconds(30), holdingLock)); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), configA, TimeSpan.FromSeconds(30), global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, holdingLock), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), configB, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), configB, TimeSpan.FromSeconds(1))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), configB, TimeSpan.FromSeconds(1), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act var taskA = Task.Run(() => provisionerA.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs index c538a5e048..7878af0e17 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgres_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v7.cs @@ -49,13 +49,13 @@ public async Task When_postgres_table_has_spec_0023_era_history_at_v1_it_should_ var columnsBefore = await GetTableColumns(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index d6b2362ec4..b7b18f30a5 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -20,13 +20,13 @@ public PostgreSqlInboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs index 76b1ede16d..9d0f5e965d 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_it_should_create_inbox_table.cs @@ -19,13 +19,13 @@ public PostgreSqlInboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index 34f4d934b6..4357555f2b 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_inbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -48,13 +48,13 @@ public PostgreSqlInboxNonDefaultSchemaTests() _connectionString, inboxTableName: _tableName, schemaName: _nonDefaultSchema); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index 00cc30e0be..40b95fe3b5 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -20,13 +20,13 @@ public PostgreSqlOutboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs index 4a712eaf7f..cc09bd3eac 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_already_provisioned_database_it_should_be_idempotent.cs @@ -19,13 +19,13 @@ public PostgreSqlOutboxProvisionerIdempotencyTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs index a41fdfbe36..3efd6cda4b 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs @@ -19,13 +19,13 @@ public PostgreSqlOutboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs index bbbd1ccc73..81c4d1a526 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_postgresql_outbox_provisioner_runs_on_fresh_database_with_non_default_schema_it_should_create_in_configured_schema.cs @@ -54,13 +54,13 @@ public PostgreSqlOutboxNonDefaultSchemaTests() _connectionString, outBoxTableName: _tableName, schemaName: _nonDefaultSchema); - var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30)); + var runner = new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs index 8e9cc95d3b..a7e659f0c1 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs @@ -52,17 +52,17 @@ public async Task When_two_outbox_provisioners_race_on_legacy_table_they_should_ var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _outboxTableName); var provisionerA = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); @@ -99,17 +99,17 @@ public async Task When_two_inbox_provisioners_race_on_legacy_table_they_should_p var config = new RelationalDatabaseConfiguration(_connectionString, inboxTableName: _inboxTableName); var provisionerA = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new PostgreSqlInboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlInboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30))); + new PostgreSqlBoxMigrationRunner(new PostgreSqlInboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_tenants_use_per_schema_scope_each_should_get_independent_history.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_tenants_use_per_schema_scope_each_should_get_independent_history.cs index ee925554a4..92f519f5c1 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_tenants_use_per_schema_scope_each_should_get_independent_history.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/BoxProvisioning/When_two_postgres_tenants_use_per_schema_scope_each_should_get_independent_history.cs @@ -109,13 +109,13 @@ private PostgreSqlOutboxProvisioner BuildPerSchemaProvisioner(string schemaName) schemaName: schemaName); var runner = new PostgreSqlBoxMigrationRunner( new PostgreSqlOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new PostgreSqlOutboxProvisioner( - new PostgreSqlBoxDetectionHelper(), + new PostgreSqlBoxDetectionHelper(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)), new PostgreSqlOutboxMigrationCatalog(), new PostgreSqlPayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private async Task EnsureSchemaExistsAsync(string schemaName) diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresCausationTrackingInboxTest.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresCausationTrackingInboxTest.cs index b0ea1b15e7..707a20e485 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresCausationTrackingInboxTest.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresCausationTrackingInboxTest.cs @@ -16,7 +16,7 @@ protected override void BeforeEachTest() _configuration = new RelationalDatabaseConfiguration( Const.ConnectionString, inboxTableName: $"{Const.TablePrefix}{Uuid.New():N}"); - _inbox = new PostgreSqlInbox(_configuration); + _inbox = new PostgreSqlInbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); base.BeforeEachTest(); } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxAsyncTest.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxAsyncTest.cs index 2073ecff0c..7f57588d7e 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxAsyncTest.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxAsyncTest.cs @@ -14,7 +14,7 @@ public class PostgresTextInboxAsyncTest : RelationalDatabaseInboxAsyncTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new PostgreSqlInbox(configuration); + return new PostgreSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override async Task CreateInboxTableAsync(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxTest.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxTest.cs index 677fc937dc..50d45a009b 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxTest.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/Inbox/PostgresTextInboxTest.cs @@ -13,7 +13,7 @@ public class PostgresTextInboxTest : RelationalDatabaseInboxTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new PostgreSqlInbox(configuration); + return new PostgreSqlInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override void CreateInboxTable(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/PostgresMessageGatewayProvider.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/PostgresMessageGatewayProvider.cs index 3f07776770..24d869e6ab 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/PostgresMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/PostgresMessageGatewayProvider.cs @@ -67,7 +67,7 @@ IEnumerable messages public IAmAChannelSync CreateChannel(PostgresSubscription subscription) { - var channel = new PostgresChannelFactory(_connection).CreateSyncChannel(subscription); + var channel = new PostgresChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateSyncChannel(subscription); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) { @@ -82,7 +82,7 @@ public async Task CreateChannelAsync( CancellationToken cancellationToken = default ) { - var channel = await new PostgresChannelFactory(_connection) + var channel = await new PostgresChannelFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) @@ -95,7 +95,7 @@ public async Task CreateChannelAsync( public IAmAMessageProducerSync CreateProducer(PostgresPublication publication) { - var producers = new PostgresMessageProducerFactory(_connection, [publication]).Create(); + var producers = new PostgresMessageProducerFactory(_connection, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); var producer = producers.First().Value; return (IAmAMessageProducerSync)producer; } @@ -105,7 +105,7 @@ public async Task CreateProducerAsync( CancellationToken cancellationToken = default ) { - var producers = await new PostgresMessageProducerFactory(_connection, [publication]) + var producers = await new PostgresMessageProducerFactory(_connection, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .CreateAsync(); var producer = producers.First().Value; return (IAmAMessageProducerAsync)producer; @@ -175,8 +175,8 @@ public Message GetMessageFromDeadLetterQueue(PostgresSubscription subscription) var dlqConsumer = new PostgresMessageConsumer( _configuration, - dlqSubscription - ); + dlqSubscription, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { @@ -215,8 +215,8 @@ public async Task GetMessageFromDeadLetterQueueAsync( var dlqConsumer = new PostgresMessageConsumer( _configuration, - dlqSubscription - ); + dlqSubscription, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs index 6a9e02d4c2..8de046b071 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order.cs @@ -30,10 +30,10 @@ public OrderTest() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication { Topic = routingKey }] - ).Create(); + [new PostgresPublication { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); - _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)).Create(sub); + _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs index fe93ae34e0..712f640e00 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_a_message_is_sent_keep_order_async.cs @@ -30,10 +30,10 @@ public OrderTestAsync() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication { Topic = routingKey }] - ).CreateAsync().GetAwaiter().GetResult(); + [new PostgresPublication { Topic = routingKey }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().GetAwaiter().GetResult(); - _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)).CreateAsync(sub); + _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(sub); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_creating_postgres_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_creating_postgres_consumer_with_dlq_subscription_should_pass_routing_keys.cs index 1492ae23f7..8f17494a16 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_creating_postgres_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_creating_postgres_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -41,7 +41,7 @@ public PostgresMessageConsumerFactoryDlqTests() var configuration = new RelationalDatabaseConfiguration( "Host=localhost;Port=5432;Database=BrighterTests;Username=brighteruser;Password=Password1!"); var connection = new PostgresMessagingGatewayConnection(configuration); - _factory = new PostgresConsumerFactory(connection); + _factory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_postgres_consumer_requeues_with_delay_should_use_native_sql.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_postgres_consumer_requeues_with_delay_should_use_native_sql.cs index 0a577b3cd6..93b39c5f17 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_postgres_consumer_requeues_with_delay_should_use_native_sql.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_postgres_consumer_requeues_with_delay_should_use_native_sql.cs @@ -43,10 +43,10 @@ public PostgreSqlMessageConsumerNativeDelayTests() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication { Topic = new RoutingKey(_topic) }] - ).Create(); + [new PostgresPublication { Topic = new RoutingKey(_topic) }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); - _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)); + _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged.cs index 8b6a8df9dc..2d3475015a 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged.cs @@ -30,10 +30,10 @@ public PurgeTest() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication {Topic = _routingKey}] - ).Create(); + [new PostgresPublication {Topic = _routingKey}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); - _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)).Create(sub); + _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(sub); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs index d92372f26f..4aaa72a986 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_queue_is_purged_async.cs @@ -30,10 +30,10 @@ public PurgeTestAsync() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication { Topic = _routingKey } ] - ).CreateAsync().GetAwaiter().GetResult(); + [new PostgresPublication { Topic = _routingKey } ], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().GetAwaiter().GetResult(); - _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)).CreateAsync(sub); + _consumer = new PostgresConsumerFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(sub); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index f4adf3f4a2..e062de6a22 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -64,13 +64,13 @@ public PostgresMessageConsumerDeliveryErrorDlqTests() // Producer registry factory ensures queue table exists var producerRegistry = new PostgresProducerRegistryFactory( connection, - [new PostgresPublication { Topic = topic }] - ).Create(); + [new PostgresPublication { Topic = topic }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); _producer = (IAmAMessageProducerSync)producerRegistry.LookupBy(topic); // Consumer factory creates consumers; table already exists from producer registry - var consumerFactory = new PostgresConsumerFactory(connection); + var consumerFactory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sub); _dlqConsumer = consumerFactory.Create(dlqSub); diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index 8a3a7e8efe..312a9d82db 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -58,12 +58,12 @@ public PostgresMessageConsumerDeliveryErrorDlqAsyncTests() var producerRegistry = new PostgresProducerRegistryFactory( connection, - [new PostgresPublication { Topic = topic }] - ).Create(); + [new PostgresPublication { Topic = topic }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); _producer = (IAmAMessageProducerAsync)producerRegistry.LookupBy(topic); - var consumerFactory = new PostgresConsumerFactory(connection); + var consumerFactory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.CreateAsync(sub); var dlqSub = new PostgresSubscription( diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_delete_and_log_warning.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_delete_and_log_warning.cs index 095bb86fdb..ecea4c3dd8 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_delete_and_log_warning.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_no_channels_configured_should_delete_and_log_warning.cs @@ -55,12 +55,12 @@ public PostgresMessageConsumerNoChannelsConfiguredTests() var producerRegistry = new PostgresProducerRegistryFactory( connection, - [new PostgresPublication { Topic = _topic }] - ).Create(); + [new PostgresPublication { Topic = _topic }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); _producer = (IAmAMessageProducerSync)producerRegistry.LookupBy(_topic); - var consumerFactory = new PostgresConsumerFactory(connection); + var consumerFactory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sub); } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 23c6b1620d..78232e4c2b 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -58,12 +58,12 @@ public PostgresMessageConsumerUnacceptableFallbackDlqTests() var producerRegistry = new PostgresProducerRegistryFactory( connection, - [new PostgresPublication { Topic = topic }] - ).Create(); + [new PostgresPublication { Topic = topic }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); _producer = (IAmAMessageProducerSync)producerRegistry.LookupBy(topic); - var consumerFactory = new PostgresConsumerFactory(connection); + var consumerFactory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sub); var dlqSub = new PostgresSubscription( diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index dd50db3275..3f1c52856a 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -60,12 +60,12 @@ public PostgresMessageConsumerUnacceptableInvalidChannelTests() var producerRegistry = new PostgresProducerRegistryFactory( connection, - [new PostgresPublication { Topic = topic }] - ).Create(); + [new PostgresPublication { Topic = topic }], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); _producer = (IAmAMessageProducerSync)producerRegistry.LookupBy(topic); - var consumerFactory = new PostgresConsumerFactory(connection); + var consumerFactory = new PostgresConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sub); var dlqSub = new PostgresSubscription( diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message.cs index 72335903bb..56f14b4093 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message.cs @@ -43,10 +43,10 @@ public PostgreSqlMessageConsumerRequeueTests() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication {Topic = new RoutingKey(_topic)}] - ).Create(); + [new PostgresPublication {Topic = new RoutingKey(_topic)}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); - _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)); + _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs index 2a9f8c6f58..1abe677390 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/MessagingGateway/When_requeueing_a_message_aync.cs @@ -43,9 +43,9 @@ public PostgreSqlMessageConsumerRequeueTestsAsync() _producerRegistry = new PostgresProducerRegistryFactory( new PostgresMessagingGatewayConnection(testHelper.Configuration), - [new PostgresPublication {Topic = new RoutingKey(_topic)}] - ).CreateAsync().Result; - _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration)); + [new PostgresPublication {Topic = new RoutingKey(_topic)}], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync().Result; + _channelFactory = new PostgresChannelFactory(new PostgresMessagingGatewayConnection(testHelper.Configuration), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Binary/PostgresBinaryOutboxProvider.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Binary/PostgresBinaryOutboxProvider.cs index e9a839e0f5..fd8f6c2b87 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Binary/PostgresBinaryOutboxProvider.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Binary/PostgresBinaryOutboxProvider.cs @@ -36,18 +36,18 @@ public void DeleteStore(IEnumerable messages) public IAmAnOutboxSync CreateOutbox() { - return new PostgreSqlOutbox(_configuration); + return new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IEnumerable GetAllMessages() { - var outbox = new PostgreSqlOutbox(_configuration); + var outbox = new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new PostgreSqlOutbox(_configuration); + var outbox = new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } @@ -76,6 +76,6 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IAmAnOutboxAsync CreateOutboxAsync() { - return new PostgreSqlOutbox(_configuration); + return new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } } diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Text/PostgresTextOutboxProvider.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Text/PostgresTextOutboxProvider.cs index fe9b74810a..146cb24213 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Text/PostgresTextOutboxProvider.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/Outbox/Text/PostgresTextOutboxProvider.cs @@ -36,18 +36,18 @@ public void DeleteStore(IEnumerable messages) public IAmAnOutboxSync CreateOutbox() { - return new PostgreSqlOutbox(_configuration); + return new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IEnumerable GetAllMessages() { - var outbox = new PostgreSqlOutbox(_configuration); + var outbox = new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new PostgreSqlOutbox(_configuration); + var outbox = new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } @@ -58,7 +58,7 @@ public IAmABoxTransactionProvider CreateTransactionProvider() public IAmAnOutboxAsync CreateOutboxAsync() { - return new PostgreSqlOutbox(_configuration); + return new PostgreSqlOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public async Task CreateStoreAsync() diff --git a/tests/Paramore.Brighter.PostgresSQL.Tests/PostgresSqlTestHelper.cs b/tests/Paramore.Brighter.PostgresSQL.Tests/PostgresSqlTestHelper.cs index f790922bd5..7d6cdb51ef 100644 --- a/tests/Paramore.Brighter.PostgresSQL.Tests/PostgresSqlTestHelper.cs +++ b/tests/Paramore.Brighter.PostgresSQL.Tests/PostgresSqlTestHelper.cs @@ -1,15 +1,15 @@ using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Npgsql; -using Paramore.Brighter.Logging; namespace Paramore.Brighter.PostgresSQL.Tests { internal sealed class PostgresSqlTestHelper { private readonly bool _binaryMessagePayload; - private static readonly ILogger s_logger = ApplicationLogging.CreateLogger(); + private static readonly ILogger s_logger = NullLogger.Instance; private readonly PostgreSqlSettings _postgreSqlSettings; private readonly string _tableName; private readonly object _syncObject = new(); diff --git a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message.cs b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message.cs index 3b40c6bfc9..aa4d32c6db 100644 --- a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message.cs +++ b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message.cs @@ -47,7 +47,7 @@ public QuartzSchedulerMessageTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication{ Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -67,7 +67,7 @@ public QuartzSchedulerMessageTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); var schedulerFactory = SchedulerBuilder.Create(new NameValueCollection()) @@ -87,8 +87,8 @@ public QuartzSchedulerMessageTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterResolver.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message_async.cs b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message_async.cs index 10614537ff..6cbb613f32 100644 --- a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message_async.cs +++ b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_message_async.cs @@ -54,7 +54,7 @@ public QuartzSchedulerMessageAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) } ) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) } ) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -74,7 +74,7 @@ public QuartzSchedulerMessageAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); var schedulerFactory = SchedulerBuilder.Create(new NameValueCollection()) @@ -94,8 +94,8 @@ public QuartzSchedulerMessageAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterResolver.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request.cs b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request.cs index 3d0682ece6..79fe703ef5 100644 --- a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request.cs +++ b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request.cs @@ -48,7 +48,7 @@ public QuartzSchedulerRequestTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) } ) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) } ) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -68,7 +68,7 @@ public QuartzSchedulerRequestTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); var schedulerFactory = SchedulerBuilder.Create(new NameValueCollection()) @@ -88,8 +88,8 @@ public QuartzSchedulerRequestTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterResolver.Processor = _processor; } diff --git a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request_async.cs b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request_async.cs index ec2b0737b7..d72a08224b 100644 --- a/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request_async.cs +++ b/tests/Paramore.Brighter.Quartz.Tests/When_scheduling_a_request_async.cs @@ -57,7 +57,7 @@ public QuartzSchedulerRequestAsyncTests() var producerRegistry = new ProducerRegistry(new Dictionary { - [_routingKey] = new InMemoryMessageProducer(_internalBus, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) + [_routingKey] = new InMemoryMessageProducer(_internalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = _routingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = new MessageMapperRegistry( @@ -77,7 +77,7 @@ public QuartzSchedulerRequestAsyncTests() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - _outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _outbox ); var schedulerFactory = SchedulerBuilder.Create(new NameValueCollection()) @@ -97,8 +97,8 @@ public QuartzSchedulerRequestAsyncTests() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - _scheduler - ); + _scheduler, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); BrighterResolver.Processor = _processor; } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher.cs index 704d98dfe3..7abd9bb16e 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher.cs @@ -31,7 +31,7 @@ public DispatchBuilderTests() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -43,7 +43,8 @@ public DispatchBuilderTests() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -67,7 +68,8 @@ public DispatchBuilderTests() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_async.cs index ca7b9edb62..ecb80251fd 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_async.cs @@ -40,7 +40,7 @@ public DispatchBuilderTestsAsync() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -52,7 +52,8 @@ public DispatchBuilderTestsAsync() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -76,7 +77,8 @@ public DispatchBuilderTestsAsync() messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact(Skip = "Breaks due to fault in Task Scheduler running after context has closed")] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs index 94b65b674e..4900613a3d 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs @@ -43,7 +43,7 @@ public DispatchBuilderWithNamedGateway() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -55,7 +55,8 @@ public DispatchBuilderWithNamedGateway() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -79,7 +80,8 @@ public DispatchBuilderWithNamedGateway() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs index 6464804e57..80e62ec011 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs @@ -44,7 +44,7 @@ public DispatchBuilderWithNamedGatewayAsync() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -56,7 +56,8 @@ public DispatchBuilderWithNamedGatewayAsync() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -80,7 +81,8 @@ public DispatchBuilderWithNamedGatewayAsync() messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs index c25e0df635..333c7b3963 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs @@ -57,7 +57,7 @@ public async Task When_connecting_with_client_certificate_can_publish_message_as }; // Act - var producer = new RmqMessageProducer(connection); + var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var message = new Message( new MessageHeader(Id.Random(), "test.mtls.topic.async", MessageType.MT_EVENT), new MessageBody("Test message over mTLS (async)") @@ -99,11 +99,11 @@ public async Task When_connecting_with_mtls_can_publish_and_receive_message_asyn }; // Act - Create consumer first to ensure queue exists and is bound - var consumer = new RmqMessageConsumer(connection, queueName, routingKey, false); + var consumer = new RmqMessageConsumer(connection, queueName, routingKey, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); // Ensure queue is created and bound before publishing // Act - Publish - var producer = new RmqMessageProducer(connection); + var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var sentMessage = new Message( new MessageHeader(Id.Random(), routingKey, MessageType.MT_EVENT), new MessageBody("Round-trip test over mTLS (async)") diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs index 1606dfdea1..fab19f38e1 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs @@ -112,7 +112,7 @@ public async Task When_publishing_with_traceparent_over_mtls_header_is_preserved new MessageBody("Test message with trace context over mTLS (async)") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -172,7 +172,7 @@ public async Task When_publishing_with_tracestate_and_baggage_over_mtls_headers_ new MessageBody("Test message with full trace context over mTLS (async)") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -242,7 +242,7 @@ public async Task When_publishing_with_mtls_brighter_tracer_write_producer_event new MessageBody("Test BrighterTracer instrumentation over mTLS (async)") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -311,7 +311,7 @@ public async Task When_publishing_cloudevents_trace_context_survives_mtls_serial new MessageBody("Test CloudEvents trace context over mTLS (async)") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -382,7 +382,7 @@ public async Task When_publishing_with_certificate_from_file_path_trace_context_ new MessageBody("Test trace context with certificate from file path (async)") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs index fef4d81b5a..d40b504b63 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs @@ -99,11 +99,11 @@ public async Task When_publishing_with_mtls_and_quorum_trace_context_is_preserve var traceParent = activity?.Id; // Act - Create consumer first to ensure queue exists - using var consumer = new RmqMessageConsumer(connection, queueName.Value, routingKey.Value, false); + using var consumer = new RmqMessageConsumer(connection, queueName.Value, routingKey.Value, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); // Publish message with trace context - using var producer = new RmqMessageProducer(connection) + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = activity }; @@ -161,10 +161,10 @@ public async Task When_publishing_with_mtls_quorum_and_baggage_context_survives_ try { // Act - using var consumer = new RmqMessageConsumer(connection, queueName.Value, routingKey.Value, false); + using var consumer = new RmqMessageConsumer(connection, queueName.Value, routingKey.Value, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); - using var producer = new RmqMessageProducer(connection) + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = activity }; diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs index 24aa99a600..6b43ab98ad 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs @@ -68,7 +68,7 @@ public RmqConfirmationCarriesIdTopicAndContextAsyncTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageProducer.OnMessagePublished += result => _confirmation.TrySetResult(result); //we need a queue to avoid a discard diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting_async.cs index f04daf5f60..dea4857669 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting_async.cs @@ -30,10 +30,10 @@ public AsyncRmqMessageConsumerConnectionClosedTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, false); + _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new AlreadyClosedRmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, 1, false); } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting_async.cs index 9c72524030..c42698cce7 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting_async.cs @@ -51,7 +51,7 @@ public AsyncRmqMessageConsumerChannelFailureTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _badReceiver = new NotSupportedRmqMessageConsumer(rmqConnection,queueName, sentMessage.Header.Topic, false, 1, false); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting_async.cs index 4b368367e5..6ab281ced1 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting_async.cs @@ -52,8 +52,8 @@ public AsyncRmqMessageConsumerOperationInterruptedTestsAsync() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); - _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, false); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new OperationInterruptedRmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, 1, false); _sender.SendAsync(sentMessage).GetAwaiter().GetResult(); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_binding_a_channel_to_multiple_topics_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_binding_a_channel_to_multiple_topics_async.cs index 0d7eb02fbf..bf41e34edb 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_binding_a_channel_to_multiple_topics_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_binding_a_channel_to_multiple_topics_async.cs @@ -37,8 +37,8 @@ public AsyncRmqMessageConsumerMultipleTopicTests() ]); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageProducer = new RmqMessageProducer(rmqConnection); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, false); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); new QueueFactory(rmqConnection, queueName, topics).CreateAsync().GetAwaiter().GetResult(); } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_confirming_multiple_messages_via_the_messaging_gateway_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_confirming_multiple_messages_via_the_messaging_gateway_async.cs index 8a1d9b5b21..dbd45e240b 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_confirming_multiple_messages_via_the_messaging_gateway_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_confirming_multiple_messages_via_the_messaging_gateway_async.cs @@ -57,7 +57,7 @@ public RmqMessageProducerConfirmationsMultipleMessagesAsyncTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), new RoutingKeys(routingKey)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_creating_quorum_queue_validation.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_creating_quorum_queue_validation.cs index 73a9b44d03..c35fffd023 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_creating_quorum_queue_validation.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_creating_quorum_queue_validation.cs @@ -49,7 +49,7 @@ public void When_creating_quorum_consumer_without_durability_should_throw() new RmqMessageConsumer(rmqConnection, queueName, routingKey, isDurable: false, // This should cause the exception highAvailability: false, - queueType: QueueType.Quorum)); + queueType: QueueType.Quorum, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.Contains("Quorum queues require durability to be enabled", exception.Message); } @@ -70,7 +70,7 @@ public void When_creating_quorum_consumer_with_high_availability_should_throw() new RmqMessageConsumer(rmqConnection, queueName, routingKey, isDurable: true, highAvailability: true, // This should cause the exception - queueType: QueueType.Quorum)); + queueType: QueueType.Quorum, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); Assert.Contains("Quorum queues do not support high availability mirroring", exception.Message); } @@ -91,7 +91,7 @@ public void When_creating_quorum_consumer_with_correct_settings_should_succeed() using var consumer = new RmqMessageConsumer(rmqConnection, queueName, routingKey, isDurable: true, // Required for quorum highAvailability: false, // Must be false for quorum - queueType: QueueType.Quorum); + queueType: QueueType.Quorum, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys(routingKey), isDurable: true, queueType: QueueType.Quorum) .CreateAsync() @@ -117,7 +117,7 @@ public async Task When_creating_classic_consumer_with_default_settings_should_su using var consumer = new RmqMessageConsumer(rmqConnection, queueName, routingKey, isDurable: false, highAvailability: true, - queueType: QueueType.Classic); + queueType: QueueType.Classic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var message = await consumer.ReceiveAsync(TimeSpan.FromMilliseconds(100)); Assert.Equal(MessageType.MT_NONE, message.Single().Header.MessageType); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_after_sending_should_publish_confirmation.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_after_sending_should_publish_confirmation.cs index ad789c653d..231eb446cf 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_after_sending_should_publish_confirmation.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_after_sending_should_publish_confirmation.cs @@ -62,7 +62,7 @@ public RmqMessageProducerDisposeConfirmationTests() { MakeChannels = OnMissingChannel.Create, WaitForConfirmsTimeOutInMilliseconds = 2000 - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageProducer.OnMessagePublished += result => { diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_async_after_sending_should_publish_confirmation.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_async_after_sending_should_publish_confirmation.cs index c91c99bf76..f3aa84f8f2 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_async_after_sending_should_publish_confirmation.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_disposing_async_after_sending_should_publish_confirmation.cs @@ -62,7 +62,7 @@ public RmqMessageProducerDisposeAsyncConfirmationTests() { MakeChannels = OnMissingChannel.Create, WaitForConfirmsTimeOutInMilliseconds = 2000 - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageProducer.OnMessagePublished += result => { diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_assert_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_assert_async.cs index 15711ceb21..77ba253a74 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_assert_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_assert_async.cs @@ -24,7 +24,7 @@ public RmqAssumeExistingInfrastructureTestsAsync() Exchange = new Exchange(Guid.NewGuid().ToString()) }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _messageConsumer = new RmqMessageConsumer( @@ -33,7 +33,7 @@ public RmqAssumeExistingInfrastructureTestsAsync() routingKey:_message.Header.Topic, isDurable: false, highAvailability:false, - makeChannels: OnMissingChannel.Assume); + makeChannels: OnMissingChannel.Assume, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_validate_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_validate_async.cs index 093785c2ff..1034e58508 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_validate_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_infrastructure_exists_can_validate_async.cs @@ -26,14 +26,14 @@ public RmqValidateExistingInfrastructureTestsAsync() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: queueName, routingKey: routingKey, isDurable: false, highAvailability: false, - makeChannels: OnMissingChannel.Validate); + makeChannels: OnMissingChannel.Validate, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys(routingKey)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_posting_a_message_to_persist_via_the_messaging_gateway_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_posting_a_message_to_persist_via_the_messaging_gateway_async.cs index 0624430bb9..6eb859a154 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_posting_a_message_to_persist_via_the_messaging_gateway_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_posting_a_message_to_persist_via_the_messaging_gateway_async.cs @@ -27,10 +27,10 @@ public RmqMessageProducerSendPersistentMessageTestsAsync() PersistMessages = true }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_queue_length_causes_a_message_to_be_rejected_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_queue_length_causes_a_message_to_be_rejected_async.cs index 5bc7a9790d..630f7d1a23 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_queue_length_causes_a_message_to_be_rejected_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_queue_length_causes_a_message_to_be_rejected_async.cs @@ -59,7 +59,7 @@ public RmqMessageProducerQueueLengthTestsAsync() Exchange = new Exchange("paramore.brighter.exchange"), }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -69,8 +69,8 @@ public RmqMessageProducerQueueLengthTestsAsync() highAvailability: false, batchSize: 5, maxQueueLength: 1, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rejecting_a_message_to_a_dead_letter_queue_async.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rejecting_a_message_to_a_dead_letter_queue_async.cs index c2f9f69c55..b551437b12 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rejecting_a_message_to_a_dead_letter_queue_async.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rejecting_a_message_to_a_dead_letter_queue_async.cs @@ -62,7 +62,7 @@ public RmqMessageProducerDLQTestsAsync() DeadLetterExchange = new Exchange("paramore.brighter.exchange.dlq") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -72,16 +72,16 @@ public RmqMessageProducerDLQTestsAsync() highAvailability: false, deadLetterQueueName: deadLetterQueueName, deadLetterRoutingKey: deadLetterRoutingKey, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _deadLetterConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: deadLetterQueueName, routingKey: deadLetterRoutingKey, isDurable:false, - makeChannels:OnMissingChannel.Assume - ); + makeChannels:OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_resetting_a_connection_that_exists.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_resetting_a_connection_that_exists.cs index 3b7be680ea..9625748edb 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_resetting_a_connection_that_exists.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_resetting_a_connection_that_exists.cs @@ -37,7 +37,7 @@ public class RMQMessageGatewayConnectionPoolResetConnectionExists public RMQMessageGatewayConnectionPoolResetConnectionExists() { - _connectionPool = new RmqMessageGatewayConnectionPool("MyConnectionName", 7); + _connectionPool = new RmqMessageGatewayConnectionPool("MyConnectionName", 7, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var connectionFactory = new ConnectionFactory { HostName = "localhost" }; diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_creates_producer_should_use_message_topic_and_scheduler.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_creates_producer_should_use_message_topic_and_scheduler.cs index 5f8840739d..954483ee04 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_creates_producer_should_use_message_topic_and_scheduler.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_creates_producer_should_use_message_topic_and_scheduler.cs @@ -61,7 +61,7 @@ public RMQMessageConsumerProducerTopicSchedulerTestsAsync() new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), new MessageBody("test content for scheduler injection")); - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _scheduler = new SpySchedulerAsync(); @@ -71,7 +71,7 @@ public RMQMessageConsumerProducerTopicSchedulerTestsAsync() queueName, topic, isDurable: false, - scheduler: _scheduler); + scheduler: _scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys(topic)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_disposes_should_dispose_producer.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_disposes_should_dispose_producer.cs index d57457879d..02e3d952ae 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_disposes_should_dispose_producer.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_disposes_should_dispose_producer.cs @@ -57,7 +57,7 @@ public void When_disposing_without_producer_created_should_not_throw() _rmqConnection, new ChannelName(Guid.NewGuid().ToString()), new RoutingKey(Guid.NewGuid().ToString()), - isDurable: false); + isDurable: false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act & Assert - should not throw var exception = Record.Exception(() => consumer.Dispose()); @@ -77,9 +77,9 @@ public async Task When_disposing_after_delayed_requeue_should_not_throw() queueName, topic, isDurable: false, - scheduler: scheduler); + scheduler: scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - var sendProducer = new RmqMessageProducer(_rmqConnection); + var sendProducer = new RmqMessageProducer(_rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(_rmqConnection, queueName, new RoutingKeys(topic)) .CreateAsync() @@ -116,9 +116,9 @@ public async Task When_disposing_async_after_delayed_requeue_should_not_throw() queueName, topic, isDurable: false, - scheduler: scheduler); + scheduler: scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - var sendProducer = new RmqMessageProducer(_rmqConnection); + var sendProducer = new RmqMessageProducer(_rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(_rmqConnection, queueName, new RoutingKeys(topic)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs index 9cf5d4e683..0c98effc5a 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs @@ -60,7 +60,7 @@ public RmqMesageConsumerDelayTestsAsync () new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), new MessageBody("test content for delay requeue")); - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscription = new RmqSubscription( subscriptionName: new SubscriptionName("rmq-delay-producer-test"), @@ -69,7 +69,7 @@ public RmqMesageConsumerDelayTestsAsync () requestType: typeof(MyCommand), messagePumpType: MessagePumpType.Proactor); - _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)) + _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .CreateAsyncChannel(subscription); new QueueFactory(rmqConnection, queueName, new RoutingKeys(topic)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_sending_after_dispose_should_throw_object_disposed_exception.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_sending_after_dispose_should_throw_object_disposed_exception.cs index dadfc3847d..3af944cca5 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_sending_after_dispose_should_throw_object_disposed_exception.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_sending_after_dispose_should_throw_object_disposed_exception.cs @@ -68,7 +68,7 @@ private static RmqMessageProducer CreateMessageProducer() Exchange = new Exchange("paramore.brighter.exchange") }; - return new RmqMessageProducer(rmqConnection); + return new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private static Message CreateMessage() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_ttl_causes_a_message_to_expire.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_ttl_causes_a_message_to_expire.cs index 27272990a5..815fcf0920 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_ttl_causes_a_message_to_expire.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Proactor/When_ttl_causes_a_message_to_expire.cs @@ -56,7 +56,7 @@ public RmqMessageProducerTTLTests () Exchange = new Exchange("paramore.brighter.exchange"), }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -65,8 +65,8 @@ public RmqMessageProducerTTLTests () isDurable: false, highAvailability: false, ttl: TimeSpan.FromMilliseconds(10000), - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //create the infrastructure _messageConsumer.ReceiveAsync(TimeSpan.Zero).GetAwaiter().GetResult(); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs index 396746cd60..5615198651 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs @@ -30,10 +30,10 @@ public RmqMessageConsumerConnectionClosedTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, false); + _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new AlreadyClosedRmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, 1, false); } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs index 98d52930d7..a9f15066b2 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs @@ -50,7 +50,7 @@ public RmqMessageConsumerChannelFailureTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _badReceiver = new NotSupportedRmqMessageConsumer(rmqConnection,queueName, sentMessage.Header.Topic, false, 1, false); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs index 35e977b297..dc53090a41 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs @@ -52,8 +52,8 @@ public RmqMessageConsumerOperationInterruptedTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); - _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, false); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new OperationInterruptedRmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, 1, false); _sender.Send(sentMessage); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs index 9021d7d0cc..c2e7cfd2b8 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs @@ -38,8 +38,8 @@ public RmqMessageConsumerMultipleTopicTests() ]); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageProducer = new RmqMessageProducer(rmqConnection); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, false); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); new QueueFactory(rmqConnection, queueName, topics).CreateAsync().GetAwaiter().GetResult(); } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_confirming_multiple_messages_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_confirming_multiple_messages_via_the_messaging_gateway.cs index 66a4d482ef..cf96ef1925 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_confirming_multiple_messages_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_confirming_multiple_messages_via_the_messaging_gateway.cs @@ -58,7 +58,7 @@ public RmqMessageProducerConfirmationsMultipleMessagesTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), new RoutingKeys(routingKey)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs index b0ded5ad20..762284d245 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs @@ -24,7 +24,7 @@ public RmqAssumeExistingInfrastructureTests() Exchange = new Exchange(Guid.NewGuid().ToString()) }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _messageConsumer = new RmqMessageConsumer( @@ -33,7 +33,7 @@ public RmqAssumeExistingInfrastructureTests() routingKey:_message.Header.Topic, isDurable: false, highAvailability:false, - makeChannels: OnMissingChannel.Assume); + makeChannels: OnMissingChannel.Assume, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs index 64ee624cd0..57b5fb59cc 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs @@ -26,14 +26,14 @@ public RmqValidateExistingInfrastructureTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: queueName, routingKey: routingKey, isDurable: false, highAvailability: false, - makeChannels: OnMissingChannel.Validate); + makeChannels: OnMissingChannel.Validate, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys(routingKey)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs index a067c4016c..32ce3aa8f4 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs @@ -27,10 +27,10 @@ public RmqMessageProducerSendPersistentMessageTests() PersistMessages = true }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)) .CreateAsync() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs index 634d1a2911..30459d1076 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs @@ -59,7 +59,7 @@ public RmqMessageProducerQueueLengthTests() Exchange = new Exchange("paramore.brighter.exchange"), }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -69,8 +69,8 @@ public RmqMessageProducerQueueLengthTests() highAvailability: false, batchSize: 5, maxQueueLength: 1, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs index 2970615863..dc13125339 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs @@ -58,7 +58,7 @@ public RmqMessageProducerDLQTests() DeadLetterExchange = new Exchange("paramore.brighter.exchange.dlq") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -68,16 +68,16 @@ public RmqMessageProducerDLQTests() highAvailability: false, deadLetterQueueName: deadLetterQueueName, deadLetterRoutingKey: deadLetterRoutingKey, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _deadLetterConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: deadLetterQueueName, routingKey: deadLetterRoutingKey, isDurable:false, - makeChannels:OnMissingChannel.Assume - ); + makeChannels:OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact(Skip = "Breaks due to fault in Task Scheduler running after context has closed")] diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs index 3c49f1442b..70df49e51a 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs @@ -34,7 +34,7 @@ namespace Paramore.Brighter.RMQ.Async.Tests.MessagingGateway.Reactor; [Collection("RMQ")] public class RmqMessageGatewayConnectionPoolResetConnectionDoesNotExist { - private readonly RmqMessageGatewayConnectionPool _connectionPool = new("MyConnectionName", 7); + private readonly RmqMessageGatewayConnectionPool _connectionPool = new("MyConnectionName", 7, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); [Fact] public async Task When_resetting_a_connection_that_does_not_exist() diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs index 33ca512e9d..77cb23bf76 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/Reactor/When_rmq_async_consumer_requeues_without_native_delay_should_use_producer.cs @@ -60,7 +60,7 @@ public RmqMessageConsumerDelayTests() new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), new MessageBody("test content for delay requeue")); - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscription = new RmqSubscription( subscriptionName: new SubscriptionName("rmq-delay-producer-test"), @@ -69,7 +69,7 @@ public RmqMessageConsumerDelayTests() requestType: typeof(MyCommand), messagePumpType: MessagePumpType.Reactor); - _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)) + _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .CreateSyncChannel(subscription); new QueueFactory(rmqConnection, queueName, new RoutingKeys(topic)) diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqClassicMessageGatewayProvider.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqClassicMessageGatewayProvider.cs index 2bce707527..6125b6ee76 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqClassicMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqClassicMessageGatewayProvider.cs @@ -94,7 +94,7 @@ IEnumerable messages public IAmAChannelSync CreateChannel(RmqSubscription subscription) { var channel = new ChannelFactory( - new RmqMessageConsumerFactory(_connection) + new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -117,7 +117,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new RmqMessageConsumerFactory(_connection) + new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -148,7 +148,7 @@ public IAmAMessageProducerSync CreateProducer(RmqPublication publication) }; } - var produces = new RmqMessageProducerFactory(connection, [publication]).Create(); + var produces = new RmqMessageProducerFactory(connection, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); var producer = produces.First().Value; return (IAmAMessageProducerSync)producer; @@ -173,8 +173,8 @@ public async Task CreateProducerAsync( var produces = await new RmqMessageProducerFactory( connection, - [publication] - ).CreateAsync(); + [publication], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(); var producer = produces.First().Value; return (IAmAMessageProducerAsync)producer; @@ -239,8 +239,8 @@ public async Task GetMessageFromDeadLetterQueueAsync( queueName: subscription.DeadLetterChannelName!, routingKey: subscription.DeadLetterRoutingKey!, isDurable: false, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { @@ -271,8 +271,8 @@ public Message GetMessageFromDeadLetterQueue(RmqSubscription subscription) queueName: subscription.DeadLetterChannelName!, routingKey: subscription.DeadLetterRoutingKey!, isDurable: false, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqQuorumMessageGatewayProvider.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqQuorumMessageGatewayProvider.cs index 5c51b783a0..75426c0878 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqQuorumMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/RmqQuorumMessageGatewayProvider.cs @@ -65,7 +65,7 @@ IEnumerable messages public IAmAChannelSync CreateChannel(RmqSubscription subscription) { var channel = new ChannelFactory( - new RmqMessageConsumerFactory(_connection) + new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateSyncChannel(subscription); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -87,7 +87,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new RmqMessageConsumerFactory(_connection) + new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.MakeChannels == OnMissingChannel.Create) @@ -116,7 +116,7 @@ public IAmAMessageProducerSync CreateProducer(RmqPublication publication) }; } - var produces = new RmqMessageProducerFactory(connection, [publication]).Create(); + var produces = new RmqMessageProducerFactory(connection, [publication], loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).Create(); var producer = produces.First().Value; return (IAmAMessageProducerSync)producer; @@ -140,8 +140,8 @@ public async Task CreateProducerAsync( var produces = await new RmqMessageProducerFactory( connection, - [publication] - ).CreateAsync(); + [publication], + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance).CreateAsync(); var producer = produces.First().Value; return (IAmAMessageProducerAsync)producer; @@ -211,8 +211,8 @@ public async Task GetMessageFromDeadLetterQueueAsync( routingKey: subscription.DeadLetterRoutingKey!, isDurable: true, makeChannels: OnMissingChannel.Assume, - queueType: QueueType.Quorum - ); + queueType: QueueType.Quorum, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { @@ -244,8 +244,8 @@ public Message GetMessageFromDeadLetterQueue(RmqSubscription subscription) routingKey: subscription.DeadLetterRoutingKey!, isDurable: true, makeChannels: OnMissingChannel.Assume, - queueType: QueueType.Quorum - ); + queueType: QueueType.Quorum, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs index 0593a2fd4a..f125dbbc1e 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs @@ -194,7 +194,7 @@ public void When_certificate_configuration_is_optional_backwards_compatibility_i private sealed class TestableRmqMessageConsumer : RmqMessageGateway { public TestableRmqMessageConsumer(RmqMessagingGatewayConnection connection) - : base(connection) + : base(connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_forwards_scheduler_to_consumers.cs index d461ade7f6..8fd01dba78 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_forwards_scheduler_to_consumers.cs @@ -38,7 +38,7 @@ public class When_rmq_async_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); var scheduler = new StubMessageScheduler(); @@ -54,7 +54,7 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new RmqMessageConsumerFactory(_connection, scheduler); + var consumerFactory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var channelFactory = new ChannelFactory(consumerFactory); // Assert — channel factory reads from the consumer factory diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_has_scheduler_should_pass_to_consumers.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_has_scheduler_should_pass_to_consumers.cs index f500928f8f..5d5443321c 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_has_scheduler_should_pass_to_consumers.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_channel_factory_has_scheduler_should_pass_to_consumers.cs @@ -25,7 +25,7 @@ public class When_rmq_async_channel_factory_has_scheduler_should_pass_to_consume public void Should_implement_channel_factory_with_scheduler() { // Arrange - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Assert @@ -37,7 +37,7 @@ public void Should_create_sync_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -54,7 +54,7 @@ public void Should_create_async_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -70,7 +70,7 @@ public void Should_create_async_channel_when_scheduler_set() public void Should_create_channel_without_scheduler_for_backward_compat() { // Arrange — no scheduler set - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Act diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_creates_consumer_should_pass_scheduler.cs index cf238dadd3..8938cb7f0b 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -48,7 +48,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, scheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.Create(_subscription); @@ -63,7 +63,7 @@ public void Should_create_async_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, scheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.CreateAsync(_subscription); @@ -77,7 +77,7 @@ public void Should_create_async_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange — factory constructed without a scheduler (backward compat) - var factory = new RmqMessageConsumerFactory(_connection); + var factory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act var consumer = factory.Create(_subscription); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_scheduler_set_after_construction.cs index 9e8559e77b..6d897520ec 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/MessagingGateway/When_rmq_async_consumer_factory_scheduler_set_after_construction.cs @@ -38,7 +38,7 @@ public class When_rmq_async_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new RmqMessageConsumerFactory(_connection); + var factory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -53,7 +53,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, scheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -64,7 +64,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, originalScheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.RMQ.Async.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs b/tests/Paramore.Brighter.RMQ.Async.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs index 10ff8d9e44..bd17a4564a 100644 --- a/tests/Paramore.Brighter.RMQ.Async.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs +++ b/tests/Paramore.Brighter.RMQ.Async.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs @@ -38,7 +38,8 @@ namespace Paramore.Brighter.RMQ.Async.Tests.TestDoubles; internal sealed class BrokerUnreachableRmqMessageConsumer : RmqMessageConsumer { public BrokerUnreachableRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override Task EnsureChannelAsync(CancellationToken ct = default) { @@ -49,7 +50,8 @@ protected override Task EnsureChannelAsync(CancellationToken ct = default) internal sealed class AlreadyClosedRmqMessageConsumer : RmqMessageConsumer { public AlreadyClosedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override Task EnsureChannelAsync(CancellationToken ct = default) { @@ -60,7 +62,8 @@ protected override Task EnsureChannelAsync(CancellationToken ct = default) internal sealed class OperationInterruptedRmqMessageConsumer : RmqMessageConsumer { public OperationInterruptedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable,isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override Task EnsureChannelAsync(CancellationToken ct = default) { @@ -71,7 +74,8 @@ protected override Task EnsureChannelAsync(CancellationToken ct = default) internal sealed class NotSupportedRmqMessageConsumer : RmqMessageConsumer { public NotSupportedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override Task EnsureChannelAsync(CancellationToken ct = default) { diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher.cs index b22a2d796d..fbd114e1e0 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher.cs @@ -31,7 +31,7 @@ public DispatchBuilderTests() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -43,7 +43,8 @@ public DispatchBuilderTests() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -67,7 +68,8 @@ public DispatchBuilderTests() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs index 457093deec..d634cc12fd 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs @@ -43,7 +43,7 @@ public DispatchBuilderWithNamedGateway() Exchange = new Exchange("paramore.brighter.exchange") }; - var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection); + var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -55,7 +55,8 @@ public DispatchBuilderWithNamedGateway() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -79,7 +80,8 @@ public DispatchBuilderWithNamedGateway() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs index 858881b993..b337bc4ebb 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_and_receiving_with_mtls.cs @@ -56,7 +56,7 @@ public void When_connecting_with_client_certificate_can_publish_message_sync() }; // Act - using var producer = new RmqMessageProducer(connection); + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var message = new Message( new MessageHeader(Id.Random(), "test.mtls.topic", MessageType.MT_EVENT), new MessageBody("Test message over mTLS (sync)") @@ -95,11 +95,11 @@ public void When_connecting_with_mtls_can_publish_and_receive_message_sync() }; // Act - Create consumer first to ensure queue exists and is bound - using var consumer = new RmqMessageConsumer(connection, queueName, routingKey, false); + using var consumer = new RmqMessageConsumer(connection, queueName, routingKey, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); // Ensure queue is created and bound before publishing // Act - Publish - using var producer = new RmqMessageProducer(connection); + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var sentMessage = new Message( new MessageHeader(Id.Random(), routingKey, MessageType.MT_EVENT), new MessageBody("Round-trip test over mTLS (sync)") diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs index 3af988aed2..7fb6705cf6 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_publishing_with_trace_context_over_mtls.cs @@ -108,7 +108,7 @@ public void When_publishing_with_traceparent_over_mtls_header_is_preserved_sync( new MessageBody("Test message with trace context over mTLS") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -167,7 +167,7 @@ public void When_publishing_with_tracestate_and_baggage_over_mtls_headers_are_pr new MessageBody("Test message with full trace context over mTLS") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -236,7 +236,7 @@ public void When_publishing_with_mtls_brighter_tracer_write_producer_event_is_ca new MessageBody("Test BrighterTracer instrumentation over mTLS") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -304,7 +304,7 @@ public void When_publishing_cloudevents_trace_context_survives_mtls_serializatio new MessageBody("Test CloudEvents trace context over mTLS") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; @@ -374,7 +374,7 @@ public void When_publishing_with_certificate_from_file_path_trace_context_is_pre new MessageBody("Test trace context with certificate from file path") ); - var messageProducer = new RmqMessageProducer(connection) + var messageProducer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs index db37b7e543..d754ad1bfd 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Acceptance/When_using_mtls_with_quorum_queues.cs @@ -88,11 +88,11 @@ public void When_publishing_with_mtls_and_quorum_trace_context_is_preserved() var traceParent = activity?.Id; // Act - Create consumer first to ensure queue exists - using var consumer = new RmqMessageConsumer(connection, queueName, routingKey.Value, false); + using var consumer = new RmqMessageConsumer(connection, queueName, routingKey.Value, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); // Publish message with trace context - using var producer = new RmqMessageProducer(connection) + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = activity }; @@ -150,10 +150,10 @@ public void When_publishing_with_mtls_quorum_and_baggage_context_survives() try { // Act - using var consumer = new RmqMessageConsumer(connection, queueName, routingKey.Value, false); + using var consumer = new RmqMessageConsumer(connection, queueName, routingKey.Value, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); consumer.Purge(); - using var producer = new RmqMessageProducer(connection) + using var producer = new RmqMessageProducer(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = activity }; diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs index cc4f4b847f..147c39896d 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_confirmation_is_received_should_carry_id_topic_and_context.cs @@ -69,7 +69,7 @@ public RmqConfirmationCarriesIdTopicAndContextTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageProducer.OnMessagePublished += result => _confirmation.TrySetResult(result); //we need a queue to avoid a discard diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_reads_multiple_messages.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_reads_multiple_messages.cs index 3635c9237f..d583648a5a 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_reads_multiple_messages.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_reads_multiple_messages.cs @@ -23,8 +23,8 @@ public RMQBufferedConsumerTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); - _messageConsumer = new RmqMessageConsumer(connection:rmqConnection, queueName:_channelName, routingKey:_routingKey, isDurable:false, highAvailability:false, batchSize:BatchSize); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _messageConsumer = new RmqMessageConsumer(connection:rmqConnection, queueName:_channelName, routingKey:_routingKey, isDurable:false, highAvailability:false, batchSize:BatchSize, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //create the queue, so that we can receive messages posted to it new QueueFactory(rmqConnection, _channelName, new RoutingKeys(_routingKey)).Create(TimeSpan.FromMilliseconds(1000)); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs index 762310d890..7a03e08234 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_already_closed_exception_when_connecting.cs @@ -30,10 +30,10 @@ public RmqMessageConsumerConnectionClosedTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, false); + _receiver = new RmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new AlreadyClosedRmqMessageConsumer(rmqConnection, queueName, _sentMessage.Header.Topic, false, 1, false); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs index 04c11d2561..355485086b 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_not_supported_exception_when_connecting.cs @@ -50,7 +50,7 @@ public RmqMessageConsumerChannelFailureTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _badReceiver = new NotSupportedRmqMessageConsumer(rmqConnection,queueName, sentMessage.Header.Topic, false, 1, false); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs index 9e227c4f16..d8ba4583f4 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_a_message_consumer_throws_an_operation_interrupted_exception_when_connecting.cs @@ -52,8 +52,8 @@ public RmqMessageConsumerOperationInterruptedTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _sender = new RmqMessageProducer(rmqConnection); - _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, false); + _sender = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _receiver = new RmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); _badReceiver = new OperationInterruptedRmqMessageConsumer(rmqConnection, new ChannelName(Guid.NewGuid().ToString()), sentMessage.Header.Topic, false, 1, false); _sender.Send(sentMessage); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs index e548fd25f1..29865157a1 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_binding_a_channel_to_multiple_topics.cs @@ -38,8 +38,8 @@ public RmqMessageConsumerMultipleTopicTests() ]); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageProducer = new RmqMessageProducer(rmqConnection); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, false); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName , topics, false, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, false); new QueueFactory(rmqConnection, queueName, topics).Create(TimeSpan.FromMilliseconds(1000)); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_confirming_posting_a_message_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_confirming_posting_a_message_via_the_messaging_gateway.cs index 8ae82a7423..8223f934de 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_confirming_posting_a_message_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_confirming_posting_a_message_via_the_messaging_gateway.cs @@ -51,7 +51,7 @@ public RmqMessageProducerConfirmationsSendMessageTests () Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageProducer.OnMessagePublished += result => { if (result.Success) diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_disposing_a_producer_asynchronously_should_complete.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_disposing_a_producer_asynchronously_should_complete.cs index 0afd8ad0a9..53cdd71c1a 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_disposing_a_producer_asynchronously_should_complete.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_disposing_a_producer_asynchronously_should_complete.cs @@ -41,7 +41,7 @@ public async Task When_disposing_a_producer_asynchronously_should_complete() AmpqUri = new AmqpUriSpecification(new Uri("amqp://guest:guest@localhost:5672/%2f")), Exchange = new Exchange("paramore.brighter.exchange") }; - var producer = new RmqMessageProducer(rmqConnection); + var producer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await producer.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5)); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs index 823a7b4b76..cd5c28df48 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_assert.cs @@ -25,7 +25,7 @@ public RmqAssumeExistingInfrastructureTests() Exchange = new Exchange(Guid.NewGuid().ToString()) }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Assume}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); _messageConsumer = new RmqMessageConsumer( @@ -34,7 +34,7 @@ public RmqAssumeExistingInfrastructureTests() routingKey:_message.Header.Topic, isDurable: false, highAvailability:false, - makeChannels: OnMissingChannel.Assume); + makeChannels: OnMissingChannel.Assume, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)).Create(TimeSpan.FromMilliseconds(1000)); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs index 661ca42cbf..d199e8fd20 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_infrastructure_exists_can_validate.cs @@ -27,14 +27,14 @@ public RmqValidateExistingInfrastructureTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: queueName, routingKey: routingKey, isDurable: false, highAvailability: false, - makeChannels: OnMissingChannel.Validate); + makeChannels: OnMissingChannel.Validate, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //This creates the infrastructure we want new QueueFactory(rmqConnection, queueName, new RoutingKeys(routingKey)).Create(TimeSpan.FromMilliseconds(1000)); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_multiple_threads_try_to_post_a_message_at_the_same_time.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_multiple_threads_try_to_post_a_message_at_the_same_time.cs index f73a62c9f0..e67c4cd21f 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_multiple_threads_try_to_post_a_message_at_the_same_time.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_multiple_threads_try_to_post_a_message_at_the_same_time.cs @@ -26,7 +26,7 @@ public RmqMessageProducerSupportsMultipleThreadsTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_but_no_broker_created.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_but_no_broker_created.cs index dfc3c5a89b..069beacdb0 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_but_no_broker_created.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_but_no_broker_created.cs @@ -24,7 +24,7 @@ public RmqBrokerNotPreCreatedTests() Exchange = new Exchange(Guid.NewGuid().ToString()) }; - _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}); + _messageProducer = new RmqMessageProducer(rmqConnection, new RmqPublication{MakeChannels = OnMissingChannel.Validate}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs index 5cf764422b..82ae2c4128 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_to_persist_via_the_messaging_gateway.cs @@ -27,10 +27,10 @@ public RmqMessageProducerSendPersistentMessageTests() PersistMessages = true }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys( _message.Header.Topic)).Create(TimeSpan.FromMilliseconds(1000)); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_via_the_messaging_gateway.cs index 609085263f..82ec0c7038 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_posting_a_message_via_the_messaging_gateway.cs @@ -85,10 +85,10 @@ public RmqMessageProducerSendMessageTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, _message.Header.Topic, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys(_message.Header.Topic)).Create(TimeSpan.FromMilliseconds(1000)); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs index 6461fb0c44..19e6693cad 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_queue_length_causes_a_message_to_be_rejected.cs @@ -59,7 +59,7 @@ public RmqMessageProducerQueueLengthTests() Exchange = new Exchange("paramore.brighter.exchange"), }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -69,8 +69,8 @@ public RmqMessageProducerQueueLengthTests() highAvailability: false, batchSize: 5, maxQueueLength: 1, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_reading_a_delayed_message_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_reading_a_delayed_message_via_the_messaging_gateway.cs index 14d9f5021b..a8b0bd0b54 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_reading_a_delayed_message_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_reading_a_delayed_message_via_the_messaging_gateway.cs @@ -52,11 +52,11 @@ public RmqMessageProducerDelayedMessageTests() Exchange = new Exchange("paramore.delay.brighter.exchange", supportDelay: true) }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var queueName = new ChannelName(Guid.NewGuid().ToString()); - _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, routingKey, false); + _messageConsumer = new RmqMessageConsumer(rmqConnection, queueName, routingKey, false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); new QueueFactory(rmqConnection, queueName, new RoutingKeys([routingKey])).Create(TimeSpan.FromMilliseconds(1000)); } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs index e18e983471..d1130a06ba 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rejecting_a_message_to_a_dead_letter_queue.cs @@ -58,7 +58,7 @@ public RmqMessageProducerDLQTests() DeadLetterExchange = new Exchange("paramore.brighter.exchange.dlq") }; - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _messageConsumer = new RmqMessageConsumer( connection: rmqConnection, @@ -68,16 +68,16 @@ public RmqMessageProducerDLQTests() highAvailability: false, deadLetterQueueName: deadLetterQueueName, deadLetterRoutingKey: deadLetterRoutingKey, - makeChannels:OnMissingChannel.Create - ); + makeChannels:OnMissingChannel.Create, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _deadLetterConsumer = new RmqMessageConsumer( connection: rmqConnection, queueName: deadLetterQueueName, routingKey: deadLetterRoutingKey, isDurable:false, - makeChannels:OnMissingChannel.Assume - ); + makeChannels:OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } //[Fact(Skip = "Breaks due to fault in Task Scheduler running after context has closed")] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_requeuing_a_message_via_the_messaging_gateway.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_requeuing_a_message_via_the_messaging_gateway.cs index f8b5a299f6..6ac717d14c 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_requeuing_a_message_via_the_messaging_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_requeuing_a_message_via_the_messaging_gateway.cs @@ -94,9 +94,9 @@ public RmqMessageProducerRequeuingMessageTests() requestType: typeof(MyCommand), messagePumpType: MessagePumpType.Reactor); - _messageProducer = new RmqMessageProducer(rmqConnection); + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)) + _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .CreateSyncChannel(subscription); new QueueFactory(rmqConnection, queueName, new RoutingKeys(_message.Header.Topic)) diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs index 56020818e5..a7b9e8d544 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_resetting_a_connection_that_does_not_exist.cs @@ -34,7 +34,7 @@ namespace Paramore.Brighter.RMQ.Sync.Tests.MessagingGateway.Reactor; [Collection("RMQ")] public class RmqMessageGatewayConnectionPoolResetConnectionDoesNotExist { - private readonly RmqMessageGatewayConnectionPool _connectionPool = new("MyConnectionName", 7); + private readonly RmqMessageGatewayConnectionPool _connectionPool = new("MyConnectionName", 7, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); [Fact] public async Task When_resetting_a_connection_that_does_not_exist() diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_retry_limits_force_a_message_onto_the_DLQ.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_retry_limits_force_a_message_onto_the_DLQ.cs index 1317580867..a9b75951d3 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_retry_limits_force_a_message_onto_the_DLQ.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_retry_limits_force_a_message_onto_the_DLQ.cs @@ -70,10 +70,10 @@ public RMQMessageConsumerRetryDLQTests() { Topic = routingKey, RequestType = typeof(MyDeferredCommand) - }); + }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //set up our receiver - ChannelFactory channelFactory = new(new RmqMessageConsumerFactory(rmqConnection)); + ChannelFactory channelFactory = new(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); _channel = channelFactory.CreateSyncChannel(_subscription); //how do we handle a command @@ -90,8 +90,8 @@ public RMQMessageConsumerRetryDLQTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry(), resilienceResiliencePipelineRegistry: new ResiliencePipelineRegistry(), - requestSchedulerFactory: new InMemorySchedulerFactory() - ); + requestSchedulerFactory: new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test var messageMapperRegistry = new MessageMapperRegistry( @@ -102,7 +102,7 @@ public RMQMessageConsumerRetryDLQTests() messageMapperRegistry.Register(); _messagePump = new ServiceActivator.Reactor(commandProcessor, (message) => typeof(MyDeferredCommand), messageMapperRegistry, - new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 0 }; @@ -112,8 +112,8 @@ public RMQMessageConsumerRetryDLQTests() queueName: deadLetterQueueName, routingKey: deadLetterRoutingKey, isDurable: false, - makeChannels: OnMissingChannel.Assume - ); + makeChannels: OnMissingChannel.Assume, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact(Skip = "Breaks due to fault in Task Scheduler running after context has closed")] diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rmq_sync_consumer_requeues_without_native_delay_should_use_producer.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rmq_sync_consumer_requeues_without_native_delay_should_use_producer.cs index 46b6a9025d..2d0ffa7bf7 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rmq_sync_consumer_requeues_without_native_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_rmq_sync_consumer_requeues_without_native_delay_should_use_producer.cs @@ -60,7 +60,7 @@ public RmqSyncConsumerDelayTests() new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), new MessageBody("test content for sync delay requeue")); - _sendProducer = new RmqMessageProducer(rmqConnection); + _sendProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var subscription = new RmqSubscription( subscriptionName: new SubscriptionName("rmq-sync-delay-producer-test"), @@ -69,7 +69,7 @@ public RmqSyncConsumerDelayTests() requestType: typeof(MyCommand), messagePumpType: MessagePumpType.Reactor); - _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection)) + _channel = new ChannelFactory(new RmqMessageConsumerFactory(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) .CreateSyncChannel(subscription); new QueueFactory(rmqConnection, queueName, new RoutingKeys(topic)) @@ -133,7 +133,7 @@ public void When_disposing_without_producer_created_should_not_throw() rmqConnection, new ChannelName(Guid.NewGuid().ToString()), new RoutingKey(Guid.NewGuid().ToString()), - isDurable: false); + isDurable: false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act & Assert - should not throw var exception = Record.Exception(() => consumer.Dispose()); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_sending_a_message_should_propagate_context.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_sending_a_message_should_propagate_context.cs index 1c8d9c00c9..9f443aed71 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_sending_a_message_should_propagate_context.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/Reactor/When_sending_a_message_should_propagate_context.cs @@ -55,7 +55,7 @@ public RmqMessageProducerPropagateContextTests() Exchange = new Exchange("paramore.brighter.exchange") }; - _messageProducer = new RmqMessageProducer(rmqConnection) + _messageProducer = new RmqMessageProducer(rmqConnection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { Span = _parentActivity }; diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs index 50255bd8c8..8a4e836700 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_configuring_mutual_tls_connection.cs @@ -194,7 +194,7 @@ public void When_certificate_configuration_is_optional_backwards_compatibility_i private sealed class TestableRmqMessageConsumer : RmqMessageGateway { public TestableRmqMessageConsumer(RmqMessagingGatewayConnection connection) - : base(connection) + : base(connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_forwards_scheduler_to_consumers.cs index d7d127f8b5..a69f173ef9 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_forwards_scheduler_to_consumers.cs @@ -38,7 +38,7 @@ public class When_rmq_sync_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); var scheduler = new StubMessageScheduler(); @@ -54,7 +54,7 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new RmqMessageConsumerFactory(_connection, scheduler); + var consumerFactory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var channelFactory = new ChannelFactory(consumerFactory); // Assert — channel factory reads from the consumer factory diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_has_scheduler_should_pass_to_consumers.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_has_scheduler_should_pass_to_consumers.cs index 17bdf06728..bf1562e032 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_has_scheduler_should_pass_to_consumers.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_channel_factory_has_scheduler_should_pass_to_consumers.cs @@ -25,7 +25,7 @@ public class When_rmq_sync_channel_factory_has_scheduler_should_pass_to_consumer public void Should_implement_channel_factory_with_scheduler() { // Arrange - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Assert @@ -37,7 +37,7 @@ public void Should_create_sync_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -53,7 +53,7 @@ public void Should_create_sync_channel_when_scheduler_set() public void Should_create_channel_without_scheduler_for_backward_compat() { // Arrange — no scheduler set - var consumerFactory = new RmqMessageConsumerFactory(_connection); + var consumerFactory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Act diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_creates_consumer_should_pass_scheduler.cs index 3ba7fd7221..8f69e386dd 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -48,7 +48,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, scheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.Create(_subscription); @@ -62,7 +62,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange — factory constructed without a scheduler (backward compat) - var factory = new RmqMessageConsumerFactory(_connection); + var factory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act var consumer = factory.Create(_subscription); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_scheduler_set_after_construction.cs index 5976a901e9..5d52ca2fae 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/MessagingGateway/When_rmq_sync_consumer_factory_scheduler_set_after_construction.cs @@ -38,7 +38,7 @@ public class When_rmq_sync_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new RmqMessageConsumerFactory(_connection); + var factory = new RmqMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -53,7 +53,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, scheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -64,7 +64,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new RmqMessageConsumerFactory(_connection, originalScheduler); + var factory = new RmqMessageConsumerFactory(_connection, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.RMQ.Sync.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs b/tests/Paramore.Brighter.RMQ.Sync.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs index 91e2bd1071..6366b74329 100644 --- a/tests/Paramore.Brighter.RMQ.Sync.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs +++ b/tests/Paramore.Brighter.RMQ.Sync.Tests/TestDoubles/TestDoubleRmqMessageConsumer.cs @@ -35,7 +35,8 @@ namespace Paramore.Brighter.RMQ.Sync.Tests.TestDoubles; internal sealed class BrokerUnreachableRmqMessageConsumer : RmqMessageConsumer { public BrokerUnreachableRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override void EnsureChannel() { @@ -46,7 +47,8 @@ protected override void EnsureChannel() internal sealed class AlreadyClosedRmqMessageConsumer : RmqMessageConsumer { public AlreadyClosedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override void EnsureChannel() { @@ -57,7 +59,8 @@ protected override void EnsureChannel() internal sealed class OperationInterruptedRmqMessageConsumer : RmqMessageConsumer { public OperationInterruptedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable,isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override void EnsureChannel() { @@ -68,7 +71,8 @@ protected override void EnsureChannel() internal sealed class NotSupportedRmqMessageConsumer : RmqMessageConsumer { public NotSupportedRmqMessageConsumer(RmqMessagingGatewayConnection connection, ChannelName queueName, RoutingKey routingKey, bool isDurable, ushort preFetchSize, bool isHighAvailability) - : base(connection, queueName, routingKey, isDurable, isHighAvailability) { } + : base(connection, queueName, routingKey, isDurable, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, isHighAvailability) { } protected override void EnsureChannel() { diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index f2b62ca57c..5677030c6f 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -50,12 +50,12 @@ public RedisMessageConsumerDeliveryErrorDlqAsyncTests() var dlqQueueName = new ChannelName($"dlq-async-test-dlq-{Guid.NewGuid()}"); _messageProducer = new RedisMessageProducer(configuration, - new RedisMessagePublication { Topic = topic }); + new RedisMessagePublication { Topic = topic }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = new RedisMessageConsumer(configuration, queueName, topic, - deadLetterRoutingKey: dlqTopic); + deadLetterRoutingKey: dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic); + _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index 1002f9d58f..3d5dacdb74 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -49,12 +49,12 @@ public RedisMessageConsumerDeliveryErrorDlqTests() var dlqQueueName = new ChannelName($"dlq-test-dlq-{Guid.NewGuid()}"); _messageProducer = new RedisMessageProducer(configuration, - new RedisMessagePublication { Topic = topic }); + new RedisMessagePublication { Topic = topic }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = new RedisMessageConsumer(configuration, queueName, topic, - deadLetterRoutingKey: dlqTopic); + deadLetterRoutingKey: dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic); + _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_remove_from_inflight.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_remove_from_inflight.cs index d314a18925..a1c438c58f 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_remove_from_inflight.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_remove_from_inflight.cs @@ -46,10 +46,10 @@ public RedisMessageConsumerNoChannelsRejectTests() var queueName = new ChannelName($"no-channels-test-{Guid.NewGuid()}"); _messageProducer = new RedisMessageProducer(configuration, - new RedisMessagePublication { Topic = topic }); + new RedisMessagePublication { Topic = topic }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // No deadLetterRoutingKey, no invalidMessageRoutingKey - _consumer = new RedisMessageConsumer(configuration, queueName, topic); + _consumer = new RedisMessageConsumer(configuration, queueName, topic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index 2e7ec60efa..ba1d541c3a 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -49,13 +49,13 @@ public RedisMessageConsumerUnacceptableFallbackToDlqTests() var dlqQueueName = new ChannelName($"fallback-test-dlq-{Guid.NewGuid()}"); _messageProducer = new RedisMessageProducer(configuration, - new RedisMessagePublication { Topic = topic }); + new RedisMessagePublication { Topic = topic }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Only DLQ configured — no invalidMessageRoutingKey _consumer = new RedisMessageConsumer(configuration, queueName, topic, - deadLetterRoutingKey: dlqTopic); + deadLetterRoutingKey: dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic); + _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index 0284dc5b3d..0f7c8777d1 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -52,14 +52,14 @@ public RedisMessageConsumerUnacceptableInvalidChannelTests() var invalidQueueName = new ChannelName($"invalid-test-invalid-{Guid.NewGuid()}"); _messageProducer = new RedisMessageProducer(configuration, - new RedisMessagePublication { Topic = topic }); + new RedisMessagePublication { Topic = topic }, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = new RedisMessageConsumer(configuration, queueName, topic, deadLetterRoutingKey: dlqTopic, - invalidMessageRoutingKey: invalidTopic); + invalidMessageRoutingKey: invalidTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); - _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic); - _invalidConsumer = new RedisMessageConsumer(configuration, invalidQueueName, invalidTopic); + _dlqConsumer = new RedisMessageConsumer(configuration, dlqQueueName, dlqTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + _invalidConsumer = new RedisMessageConsumer(configuration, invalidQueueName, invalidTopic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisFixture.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisFixture.cs index 35e35986bc..81fb340234 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisFixture.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisFixture.cs @@ -18,8 +18,8 @@ public RedisFixture() RedisMessagingGatewayConfiguration configuration = RedisMessagingGatewayConfiguration(); - MessageProducer = new RedisMessageProducer(configuration, new RedisMessagePublication {Topic = Topic}); - MessageConsumer = new RedisMessageConsumer(configuration, queueName, Topic); + MessageProducer = new RedisMessageProducer(configuration, new RedisMessagePublication {Topic = Topic}, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); + MessageConsumer = new RedisMessageConsumer(configuration, queueName, Topic, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public static RedisMessagingGatewayConfiguration RedisMessagingGatewayConfiguration() diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisMessageGatewayProvider.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisMessageGatewayProvider.cs index 69a196963e..9d9aaaeb0d 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/RedisMessageGatewayProvider.cs @@ -90,7 +90,7 @@ IEnumerable messages public IAmAChannelSync CreateChannel(RedisSubscription subscription) { var channel = new ChannelFactory( - new RedisMessageConsumerFactory(_configuration) + new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateSyncChannel(subscription); // Redis requires a receive before send to establish the subscription @@ -104,8 +104,8 @@ public IAmAChannelSync CreateChannel(RedisSubscription subscription) _dlqConsumer = new RedisMessageConsumer( _configuration, dlqQueueName, - subscription.DeadLetterRoutingKey - ); + subscription.DeadLetterRoutingKey, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqConsumer.Receive(TimeSpan.FromMilliseconds(1000)); } @@ -125,7 +125,7 @@ public async Task CreateChannelAsync( ) { var channel = await new ChannelFactory( - new RedisMessageConsumerFactory(_configuration) + new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) ).CreateAsyncChannelAsync(subscription, cancellationToken); // Redis async ReceiveAsync does NOT enforce a 1s minimum timeout like @@ -139,8 +139,8 @@ public async Task CreateChannelAsync( _dlqConsumer = new RedisMessageConsumer( _configuration, dlqQueueName, - subscription.DeadLetterRoutingKey - ); + subscription.DeadLetterRoutingKey, + loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _dlqConsumer.Receive(TimeSpan.FromMilliseconds(1000)); } @@ -153,7 +153,7 @@ public async Task CreateChannelAsync( public IAmAMessageProducerSync CreateProducer(RedisMessagePublication publication) { - return new RedisMessageProducer(_configuration, publication); + return new RedisMessageProducer(_configuration, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public async Task CreateProducerAsync( @@ -162,7 +162,7 @@ public async Task CreateProducerAsync( ) { await Task.CompletedTask; - return new RedisMessageProducer(_configuration, publication); + return new RedisMessageProducer(_configuration, publication, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } public RedisMessagePublication CreatePublication( diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_creating_redis_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_creating_redis_consumer_with_dlq_subscription_should_pass_routing_keys.cs index 866b32f1d7..6b8f911c08 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_creating_redis_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_creating_redis_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -39,7 +39,7 @@ public RedisMessageConsumerFactoryDlqTests() { //Arrange var configuration = RedisFixture.RedisMessagingGatewayConfiguration(); - _factory = new RedisMessageConsumerFactory(configuration); + _factory = new RedisMessageConsumerFactory(configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_parsing_a_good_redis_message_to_brighter.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_parsing_a_good_redis_message_to_brighter.cs index 9803217839..5dcf3f9577 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_parsing_a_good_redis_message_to_brighter.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_parsing_a_good_redis_message_to_brighter.cs @@ -16,7 +16,7 @@ public class RedisGoodMessageParsingTests [Fact] public void When_parsing_a_good_redis_message_to_brighter() { - Message message = RedisMessageCreator.CreateMessage(GoodMessage); + Message message = new RedisMessageCreator(logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)).CreateMessage(GoodMessage); // Assert existing properties Assert.Equal(DateTime.Parse("2018-02-07T09:38:36Z"), message.Header.TimeStamp); diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_forwards_scheduler_to_consumers.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_forwards_scheduler_to_consumers.cs index 59729b37af..6751eae4f5 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_forwards_scheduler_to_consumers.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_forwards_scheduler_to_consumers.cs @@ -37,7 +37,7 @@ public class When_redis_channel_factory_forwards_scheduler_to_consumers public void Should_forward_scheduler_to_consumer_factory() { // Arrange - var consumerFactory = new RedisMessageConsumerFactory(_configuration); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); var scheduler = new StubMessageScheduler(); @@ -53,7 +53,7 @@ public void Should_read_scheduler_from_consumer_factory() { // Arrange — consumer factory has a scheduler from construction var scheduler = new StubMessageScheduler(); - var consumerFactory = new RedisMessageConsumerFactory(_configuration, scheduler); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var channelFactory = new ChannelFactory(consumerFactory); // Assert — channel factory reads from the consumer factory diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_has_scheduler_should_pass_to_consumers.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_has_scheduler_should_pass_to_consumers.cs index 2d609d3809..076f2c4089 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_has_scheduler_should_pass_to_consumers.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_channel_factory_has_scheduler_should_pass_to_consumers.cs @@ -23,7 +23,7 @@ public class When_redis_channel_factory_has_scheduler_should_pass_to_consumers public void Should_implement_channel_factory_with_scheduler() { // Arrange - var consumerFactory = new RedisMessageConsumerFactory(_configuration); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Assert @@ -35,7 +35,7 @@ public void Should_create_sync_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new RedisMessageConsumerFactory(_configuration); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -52,7 +52,7 @@ public void Should_create_async_channel_when_scheduler_set() { // Arrange var scheduler = new StubMessageScheduler(); - var consumerFactory = new RedisMessageConsumerFactory(_configuration); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); ((IAmAChannelFactoryWithScheduler)channelFactory).Scheduler = scheduler; @@ -68,7 +68,7 @@ public void Should_create_async_channel_when_scheduler_set() public void Should_create_channel_without_scheduler_for_backward_compat() { // Arrange — no scheduler set - var consumerFactory = new RedisMessageConsumerFactory(_configuration); + var consumerFactory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var channelFactory = new ChannelFactory(consumerFactory); // Act diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_creates_producer_should_configure_and_dispose_correctly.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_creates_producer_should_configure_and_dispose_correctly.cs index 9303250b98..266b63e15a 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_creates_producer_should_configure_and_dispose_correctly.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_creates_producer_should_configure_and_dispose_correctly.cs @@ -48,7 +48,7 @@ public void When_requeuing_with_delay_should_wire_scheduler_to_producer() var queueName = new ChannelName($"Producer-Config-Queue-{Guid.NewGuid()}"); var scheduler = new SpySchedulerSync(); - var consumer = new RedisMessageConsumer(configuration, queueName, topic, scheduler); + var consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), @@ -76,7 +76,7 @@ public void When_disposing_after_requeue_should_not_throw() var queueName = new ChannelName($"Producer-Dispose-Queue-{Guid.NewGuid()}"); var scheduler = new SpySchedulerSync(); - var consumer = new RedisMessageConsumer(configuration, queueName, topic, scheduler); + var consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), @@ -99,7 +99,7 @@ public void When_disposing_without_requeue_should_not_throw() var queueName = new ChannelName($"Producer-NoRequeue-Queue-{Guid.NewGuid()}"); var scheduler = new SpySchedulerSync(); - var consumer = new RedisMessageConsumer(configuration, queueName, topic, scheduler); + var consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act & Assert - dispose without producer creation should not throw var exception = Record.Exception(() => consumer.Dispose()); @@ -116,7 +116,7 @@ public async Task When_disposing_async_after_requeue_should_not_throw() var queueName = new ChannelName($"Producer-AsyncDispose-Queue-{Guid.NewGuid()}"); var scheduler = new SpySchedulerSync(); - var consumer = new RedisMessageConsumer(configuration, queueName, topic, scheduler); + var consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); var message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_creates_consumer_should_pass_scheduler.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_creates_consumer_should_pass_scheduler.cs index 7f25b8d0e0..4138f0defe 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_creates_consumer_should_pass_scheduler.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_creates_consumer_should_pass_scheduler.cs @@ -46,7 +46,7 @@ public void Should_create_sync_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new RedisMessageConsumerFactory(_configuration, scheduler); + var factory = new RedisMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.Create(_subscription); @@ -61,7 +61,7 @@ public void Should_create_async_consumer_when_scheduler_provided() { // Arrange — factory constructed with a scheduler var scheduler = new StubMessageScheduler(); - var factory = new RedisMessageConsumerFactory(_configuration, scheduler); + var factory = new RedisMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Act var consumer = factory.CreateAsync(_subscription); @@ -75,7 +75,7 @@ public void Should_create_async_consumer_when_scheduler_provided() public void Should_create_consumer_without_scheduler_for_backward_compat() { // Arrange — factory constructed without a scheduler (backward compat) - var factory = new RedisMessageConsumerFactory(_configuration); + var factory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act var consumer = factory.Create(_subscription); diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_scheduler_set_after_construction.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_scheduler_set_after_construction.cs index 1cc64df606..be25dc6475 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_scheduler_set_after_construction.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_factory_scheduler_set_after_construction.cs @@ -37,7 +37,7 @@ public class When_redis_consumer_factory_scheduler_set_after_construction public void Should_expose_scheduler_set_after_construction() { // Arrange — factory constructed without a scheduler - var factory = new RedisMessageConsumerFactory(_configuration); + var factory = new RedisMessageConsumerFactory(_configuration, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var scheduler = new StubMessageScheduler(); // Act — set scheduler after construction @@ -52,7 +52,7 @@ public void Should_use_constructor_scheduler_when_property_not_set() { // Arrange — factory constructed with a scheduler via constructor var scheduler = new StubMessageScheduler(); - var factory = new RedisMessageConsumerFactory(_configuration, scheduler); + var factory = new RedisMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, scheduler); // Assert — scheduler property reflects the constructor value Assert.Same(scheduler, factory.Scheduler); @@ -63,7 +63,7 @@ public void Should_override_constructor_scheduler_with_property() { // Arrange — factory constructed with one scheduler var originalScheduler = new StubMessageScheduler(); - var factory = new RedisMessageConsumerFactory(_configuration, originalScheduler); + var factory = new RedisMessageConsumerFactory(_configuration, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, originalScheduler); // Act — override with a different scheduler var overrideScheduler = new StubMessageScheduler(); diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_async_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_async_with_delay_should_use_producer.cs index af0ffb83d3..c0c05ce777 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_async_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_async_with_delay_should_use_producer.cs @@ -52,7 +52,7 @@ public When_redis_consumer_requeues_async_with_delay_should_use_producer() var queueName = new ChannelName($"Requeue-Async-Delay-Queue-{Guid.NewGuid()}"); _scheduler = new SpySchedulerAsync(); - _consumer = new RedisMessageConsumer(configuration, queueName, topic, _scheduler); + _consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_delay_should_use_producer.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_delay_should_use_producer.cs index a477e29495..ba452ec1e5 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_delay_should_use_producer.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_delay_should_use_producer.cs @@ -50,7 +50,7 @@ public When_redis_consumer_requeues_with_delay_should_use_producer() var queueName = new ChannelName($"Requeue-Delay-Queue-{Guid.NewGuid()}"); _scheduler = new SpySchedulerSync(); - _consumer = new RedisMessageConsumer(configuration, queueName, topic, _scheduler); + _consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_zero_delay_should_use_direct_list.cs b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_zero_delay_should_use_direct_list.cs index c06a64f9ea..fcb0f95764 100644 --- a/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_zero_delay_should_use_direct_list.cs +++ b/tests/Paramore.Brighter.Redis.Tests/MessagingGateway/When_redis_consumer_requeues_with_zero_delay_should_use_direct_list.cs @@ -50,7 +50,7 @@ public When_redis_consumer_requeues_with_zero_delay_should_use_direct_list() var queueName = new ChannelName($"Requeue-ZeroDelay-Queue-{Guid.NewGuid()}"); _scheduler = new SpySchedulerSync(); - _consumer = new RedisMessageConsumer(configuration, queueName, topic, _scheduler); + _consumer = new RedisMessageConsumer(configuration, queueName, topic, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, _scheduler); _message = new Message( new MessageHeader(Guid.NewGuid().ToString(), topic, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerSocketErrorOnGetClient.cs b/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerSocketErrorOnGetClient.cs index 94c060a641..d3d0267235 100644 --- a/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerSocketErrorOnGetClient.cs +++ b/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerSocketErrorOnGetClient.cs @@ -10,7 +10,8 @@ public class RedisMessageConsumerSocketErrorOnGetClient( RedisMessagingGatewayConfiguration redisMessagingGatewayConfiguration, ChannelName queueName, RoutingKey topic) - : RedisMessageConsumer(redisMessagingGatewayConfiguration, queueName, topic) + : RedisMessageConsumer(redisMessagingGatewayConfiguration, queueName, topic, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { private const string SocketException = "localhost:6379"; diff --git a/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerTimeoutOnGetClient.cs b/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerTimeoutOnGetClient.cs index 4226a95f89..30639ea3de 100644 --- a/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerTimeoutOnGetClient.cs +++ b/tests/Paramore.Brighter.Redis.Tests/TestDoubles/RedisMessageConsumerTimeoutOnGetClient.cs @@ -10,7 +10,8 @@ public class RedisMessageConsumerTimeoutOnGetClient( RedisMessagingGatewayConfiguration redisMessagingGatewayConfiguration, ChannelName queueName, RoutingKey topic) - : RedisMessageConsumer(redisMessagingGatewayConfiguration, queueName, topic) + : RedisMessageConsumer(redisMessagingGatewayConfiguration, queueName, topic, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { private const string PoolTimeoutError = "Redis Timeout expired. The timeout period elapsed prior to obtaining a subscription from the pool. This may have occurred because all pooled connections were in use."; diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs index 30c085aaf7..08c7ce8827 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs @@ -25,7 +25,7 @@ public DispatchBuilderTests() messageMapperRegistry.Register(); var connection = GatewayFactory.CreateConnection(); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -37,7 +37,8 @@ public DispatchBuilderTests() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -62,7 +63,8 @@ public DispatchBuilderTests() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer); + .ConfigureInstrumentation(tracer) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs index d7ffe39de4..98b23cb906 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs @@ -26,7 +26,7 @@ public DispatchBuilderTestsAsync() var connection = GatewayFactory.CreateConnection(); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -38,7 +38,8 @@ public DispatchBuilderTestsAsync() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -63,7 +64,8 @@ public DispatchBuilderTestsAsync() messagePumpType: MessagePumpType.Proactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs index b0fc392328..ea2cb26bf3 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs @@ -39,7 +39,7 @@ public DispatchBuilderWithNamedGateway() }; var connection = GatewayFactory.CreateConnection(); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var container = new ServiceCollection(); var tracer = new BrighterTracer(TimeProvider.System); @@ -51,7 +51,8 @@ public DispatchBuilderWithNamedGateway() .NoExternalBus() .ConfigureInstrumentation(tracer, instrumentationOptions) .RequestContextFactory(new InMemoryRequestContextFactory()) - .RequestSchedulerFactory(new InMemorySchedulerFactory()) + .RequestSchedulerFactory(new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) .Build(); _builder = DispatchBuilder.StartNew() @@ -76,7 +77,8 @@ public DispatchBuilderWithNamedGateway() messagePumpType: MessagePumpType.Reactor, timeOut: TimeSpan.FromMilliseconds(200)) ]) - .ConfigureInstrumentation(tracer, instrumentationOptions); + .ConfigureInstrumentation(tracer, instrumentationOptions) + .ConfigureLogging(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_a_message_consumer_a_cloud_events_async.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_a_message_consumer_a_cloud_events_async.cs index dbdd2be6cf..7c8b2892e3 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_a_message_consumer_a_cloud_events_async.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_a_message_consumer_a_cloud_events_async.cs @@ -19,7 +19,7 @@ public BufferedConsumerCloudEventsTestsAsync() var consumer = GatewayFactory.CreateSimpleConsumer(connection, publication).GetAwaiter().GetResult(); var producer = GatewayFactory.CreateProducer(connection, publication).GetAwaiter().GetResult(); - _consumer = new RocketMessageConsumer(consumer, BatchSize, TimeSpan.FromSeconds(30)); + _consumer = new RocketMessageConsumer(consumer, BatchSize, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _producer = new RocketMqMessageProducer(connection, producer, publication); } diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs index b959fd237a..bb282fb527 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Proactor/When_rejecting_message_with_delivery_error_should_send_to_dlq_async.cs @@ -66,7 +66,7 @@ public RocketMqDeliveryErrorDlqAsyncTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Proactor); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.CreateAsync(sourceSub); // DLQ topic consumer (to verify forwarded messages) diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_a_message_consumer_a_cloud_events.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_a_message_consumer_a_cloud_events.cs index 27365b167f..d8ff0bcc59 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_a_message_consumer_a_cloud_events.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_a_message_consumer_a_cloud_events.cs @@ -19,7 +19,7 @@ public BufferedConsumerCloudEventsTests() var consumer = GatewayFactory.CreateSimpleConsumer(connection, publication).GetAwaiter().GetResult(); var producer = GatewayFactory.CreateProducer(connection, publication).GetAwaiter().GetResult(); - _consumer = new RocketMessageConsumer(consumer, BatchSize, TimeSpan.FromSeconds(30)); + _consumer = new RocketMessageConsumer(consumer, BatchSize, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _producer = new RocketMqMessageProducer(connection, producer, publication); } diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs index f381f6d866..0aa927b1cb 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_delivery_error_should_send_to_dlq.cs @@ -65,7 +65,7 @@ public RocketMqDeliveryErrorDlqTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Reactor); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sourceSub); // DLQ topic consumer (to verify forwarded messages) diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_ack_and_log_warning.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_ack_and_log_warning.cs index e2c8bdb43d..3dacc4c82b 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_ack_and_log_warning.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_no_channels_configured_should_ack_and_log_warning.cs @@ -62,7 +62,7 @@ public RocketMqNoChannelsConfiguredTests() consumerGroup: Guid.NewGuid().ToString(), messagePumpType: MessagePumpType.Reactor); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sourceSub); _message = new Message( diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs index ef8bfdedcc..e55a5ebc36 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_and_no_invalid_channel_should_fallback_to_dlq.cs @@ -65,7 +65,7 @@ public RocketMqUnacceptableFallbackToDlqTests() deadLetterRoutingKey: dlqTopic, messagePumpType: MessagePumpType.Reactor); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sourceSub); // DLQ topic consumer (to verify fallback routing) diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs index d01352eabe..7d4b0beebb 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/Reactor/When_rejecting_message_with_unacceptable_reason_should_send_to_invalid_channel.cs @@ -68,7 +68,7 @@ public RocketMqUnacceptableInvalidChannelTests() invalidMessageRoutingKey: invalidTopic, messagePumpType: MessagePumpType.Reactor); - var consumerFactory = new RocketMessageConsumerFactory(connection); + var consumerFactory = new RocketMessageConsumerFactory(connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _consumer = consumerFactory.Create(sourceSub); // Invalid message topic consumer (to verify forwarded messages) diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/RocketMqMessageGatewayProvider.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/RocketMqMessageGatewayProvider.cs index f131796cca..4bd3336896 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/RocketMqMessageGatewayProvider.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/RocketMqMessageGatewayProvider.cs @@ -148,7 +148,7 @@ public async Task CreateProducerAsync( public IAmAChannelSync CreateChannel(RocketSubscription subscription) { - var channelFactory = new RocketMqChannelFactory(new RocketMessageConsumerFactory(_connection)); + var channelFactory = new RocketMqChannelFactory(new RocketMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var channel = channelFactory.CreateSyncChannel(subscription); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) @@ -163,7 +163,7 @@ public async Task CreateChannelAsync( RocketSubscription subscription, CancellationToken cancellationToken = default) { - var channelFactory = new RocketMqChannelFactory(new RocketMessageConsumerFactory(_connection)); + var channelFactory = new RocketMqChannelFactory(new RocketMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); var channel = await channelFactory.CreateAsyncChannelAsync(subscription, cancellationToken); if (subscription.DeadLetterRoutingKey != null && subscription.RequeueCount > 0) @@ -215,7 +215,7 @@ public async Task GetMessageFromDeadLetterQueueAsync( }) .Build(); - var consumer = new RocketMessageConsumer(dlqConsumer, 1, TimeSpan.FromSeconds(30)); + var consumer = new RocketMessageConsumer(dlqConsumer, 1, TimeSpan.FromSeconds(30), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); try { diff --git a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/When_creating_rocket_consumer_with_dlq_subscription_should_pass_routing_keys.cs b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/When_creating_rocket_consumer_with_dlq_subscription_should_pass_routing_keys.cs index 3bdd9e0997..5e8a28ba37 100644 --- a/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/When_creating_rocket_consumer_with_dlq_subscription_should_pass_routing_keys.cs +++ b/tests/Paramore.Brighter.RocketMQ.Tests/MessagingGateway/When_creating_rocket_consumer_with_dlq_subscription_should_pass_routing_keys.cs @@ -41,7 +41,7 @@ public class RocketConsumerFactoryDlqTests : IDisposable public RocketConsumerFactoryDlqTests() { _connection = GatewayFactory.CreateConnection(); - _factory = new RocketMessageConsumerFactory(_connection); + _factory = new RocketMessageConsumerFactory(_connection, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/Legacy/When_sqlite_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/Legacy/When_sqlite_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs index f3f40ede52..c0446b1dd2 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/Legacy/When_sqlite_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/Legacy/When_sqlite_inbox_and_outbox_lack_causation_column_should_still_add_and_retrieve.cs @@ -233,10 +233,10 @@ private SqliteOutbox OutboxFor(string tableName) _connectionString, databaseName: "brightertests", outBoxTableName: tableName, - binaryMessagePayload: false)); + binaryMessagePayload: false), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private IAmAnInboxSync InboxFor(string tableName) - => new SqliteInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName)); + => new SqliteInbox(new RelationalDatabaseConfiguration(_connectionString, inboxTableName: tableName), logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); private static Message CreateMessage() => new( diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs index cfd3cc48c7..5113fde5f6 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_provisioner_runs_it_should_create_table_or_bootstrap_existing.cs @@ -26,13 +26,13 @@ public async Task When_inbox_provisioner_runs_on_fresh_database_it_should_create var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _freshTableName); - var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteInboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act await provisioner.ProvisionAsync(); @@ -76,13 +76,13 @@ public async Task When_inbox_provisioner_runs_against_existing_table_without_his var config = new RelationalDatabaseConfiguration( _connectionString, inboxTableName: _existingTableName); - var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteInboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); // Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs index 1129230c30..4e8a75645d 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_inbox_table_is_bootstrapped_at_v1_it_should_upgrade_to_v3.cs @@ -51,13 +51,13 @@ public async Task When_sqlite_inbox_table_is_bootstrapped_at_v1_it_should_upgrad await SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, inboxTableName: _tableName); - var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteInboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_migration_is_cancelled_mid_flight_it_should_rollback_releasing_writer_slot.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_migration_is_cancelled_mid_flight_it_should_rollback_releasing_writer_slot.cs index efd1af1731..db8255a604 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_migration_is_cancelled_mid_flight_it_should_rollback_releasing_writer_slot.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_migration_is_cancelled_mid_flight_it_should_rollback_releasing_writer_slot.cs @@ -92,7 +92,7 @@ public async Task When_sqlite_migration_is_cancelled_mid_flight_it_should_rollba // BeginAsync issues BEGIN IMMEDIATE on the same database completes the migration // normally; the 5s lock timeout would expire and surface as SQLITE_BUSY (wrapped as // MigrationLockDeadlockException) if the writer slot were still held. - var freshRunner = new SqliteBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5)); + var freshRunner = new SqliteBoxMigrationRunner(catalog, config, TimeSpan.FromSeconds(5), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await freshRunner.MigrateAsync( _tableName, schemaName: null, BoxType.Outbox, staleHint, CancellationToken.None); @@ -134,7 +134,8 @@ public async Task DisposeAsync() public CancellingSqliteBoxMigrationRunner( IAmABoxMigrationCatalog catalog, IAmARelationalDatabaseConfiguration configuration) - : base(catalog, configuration) + : base(catalog, configuration, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs index 38cb55745f..240f6e993e 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_or_inbox_detects_missing_discriminator_column_it_should_return_negative_one.cs @@ -61,13 +61,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter outbox and names the discriminator. @@ -99,13 +99,13 @@ await ExecuteDdl( Assert.Equal(-1, detected); //Act — provisioner end-to-end. - var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteInboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies this as not a Brighter inbox and names the discriminator. @@ -138,13 +138,13 @@ await ExecuteDdl( Assert.Equal(0, detected); //Act — provisioner end-to-end. - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); //Assert — message identifies the table as not matching any known schema version. diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs index efd8057a68..eb5b483022 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_finds_existing_table_without_history_it_should_bootstrap.cs @@ -20,13 +20,13 @@ public OutboxProvisionerBootstrapTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs index 3fe4c8e62f..6082c5ca34 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_provisioner_runs_on_fresh_database_it_should_create_outbox_table.cs @@ -20,13 +20,13 @@ public OutboxProvisionerFreshDatabaseTests() var config = new RelationalDatabaseConfiguration( _connectionString, outBoxTableName: _tableName); - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); _provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v_latest.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v_latest.cs index e386f4a0ef..1ae60294a0 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v_latest.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_outbox_table_is_bootstrapped_at_vk_it_should_upgrade_to_v_latest.cs @@ -59,13 +59,13 @@ public async Task When_sqlite_outbox_table_is_bootstrapped_at_vk_it_should_upgra await SeedMarkerRow(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_per_schema_scope_is_selected_it_should_be_a_no_op_and_not_throw.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_per_schema_scope_is_selected_it_should_be_a_no_op_and_not_throw.cs index 523ec13558..9379c34e5e 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_per_schema_scope_is_selected_it_should_be_a_no_op_and_not_throw.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_per_schema_scope_is_selected_it_should_be_a_no_op_and_not_throw.cs @@ -87,13 +87,13 @@ private SqliteOutboxProvisioner BuildProvisioner(RelationalDatabaseConfiguration // Evident data: PerSchema is the scope under test. var runner = new SqliteBoxMigrationRunner( new SqliteOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), - scope: MigrationHistoryScope.PerSchema); + scope: MigrationHistoryScope.PerSchema, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } private async Task TableCountAsync(string tableName) diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs index d975c9139d..8512e36dd7 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_provisioner_runs_against_existing_outbox_with_mismatched_payload_mode_it_should_throw_configuration_exception.cs @@ -50,7 +50,7 @@ public async Task When_existing_outbox_body_is_text_and_provisioner_is_configure new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); @@ -72,7 +72,7 @@ public async Task When_existing_outbox_body_is_binary_and_provisioner_is_configu new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act & Assert var exception = await Assert.ThrowsAsync(() => provisioner.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_beyond_lock_timeout_it_should_throw_sqlite_busy.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_beyond_lock_timeout_it_should_throw_sqlite_busy.cs index 212af63830..b450db0165 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_beyond_lock_timeout_it_should_throw_sqlite_busy.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_beyond_lock_timeout_it_should_throw_sqlite_busy.cs @@ -76,7 +76,7 @@ public SqliteRunnerLockTimeoutBoundsContentionTests() _connectionString = $"Data Source={_dbPath}"; _config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); _runner = new SqliteBoxMigrationRunner( - new SingleV1Catalog(_config), _config, TightLockTimeout); + new SingleV1Catalog(_config), _config, TightLockTimeout, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_with_concurrent_writer_it_should_retry_sqlite_busy_with_backoff_and_succeed.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_with_concurrent_writer_it_should_retry_sqlite_busy_with_backoff_and_succeed.cs index ae75fd86f9..cd31e6aa8d 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_with_concurrent_writer_it_should_retry_sqlite_busy_with_backoff_and_succeed.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_contends_with_concurrent_writer_it_should_retry_sqlite_busy_with_backoff_and_succeed.cs @@ -53,7 +53,7 @@ public SqliteRunnerSqliteBusyContentionTests() { _connectionString = $"Data Source={_dbPath}"; _config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - _runner = new SqliteBoxMigrationRunner(new SingleV1Catalog(), _config); + _runner = new SqliteBoxMigrationRunner(new SingleV1Catalog(), _config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); } [Fact] diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs index 6d00bf6203..081ca1b52d 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_fails_mid_chain_it_should_roll_back_all_migrations_and_history_rows_atomically.cs @@ -64,7 +64,7 @@ public async Task When_sqlite_runner_fails_mid_chain_it_should_roll_back_all_mig realMigrations, BrokenVersion, BrokenUpScript); var brokenCatalog = new BrokenChainCatalog(brokenMigrations, realCatalog.FreshInstallDdl(config)); - var brokenRunner = new SqliteBoxMigrationRunner(brokenCatalog, config); + var brokenRunner = new SqliteBoxMigrationRunner(brokenCatalog, config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var staleHint = new BoxTableState(TableExists: true, HistoryExists: false, CurrentVersion: SeedVersion); //Act + Assert (1) — broken V6 in chain: runner throws and rolls back everything. @@ -88,13 +88,13 @@ await Assert.ThrowsAsync(() => brokenRunner.MigrateAsync( Assert.Equal(1, await GetMarkerRowCount()); //Act + Assert (2) — retry with the real migration list: bootstrap path completes V4..V7. - var realRunner = new SqliteBoxMigrationRunner(realCatalog, config); + var realRunner = new SqliteBoxMigrationRunner(realCatalog, config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - realRunner); + realRunner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); await provisioner.ProvisionAsync(); //Assert — exactly one synthetic V3 + one applied per V4..V7 (no duplicates). diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs index d5ddb44ef8..5aebeefd6a 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_called_with_non_monotonic_migrations_it_should_throw.cs @@ -70,7 +70,7 @@ private async Task AssertMigrationListRejected(IReadOnlyList m //Arrange — do NOT create the box table (so fresh path is selected). var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); var malformedCatalog = new MalformedListCatalog(malformed); - var runner = new SqliteBoxMigrationRunner(malformedCatalog, config); + var runner = new SqliteBoxMigrationRunner(malformedCatalog, config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); //Act + Assert — runner refuses to begin migration when the version sequence is malformed. diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_with_enable_wal_mode_false_it_should_not_change_journal_mode.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_with_enable_wal_mode_false_it_should_not_change_journal_mode.cs index 1d3e0a4081..0c675e52e6 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_with_enable_wal_mode_false_it_should_not_change_journal_mode.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_with_enable_wal_mode_false_it_should_not_change_journal_mode.cs @@ -61,7 +61,7 @@ public async Task When_wal_mode_disabled_it_should_preserve_existing_delete_jour var config = new RelationalDatabaseConfiguration( ConnectionString, outBoxTableName: tableName); var runner = new SqliteBoxMigrationRunner( - new SqliteOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), enableWalMode: false); + new SqliteOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), enableWalMode: false, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — let the runner provision a fresh outbox. var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); @@ -83,7 +83,7 @@ public async Task When_wal_mode_enabled_it_should_switch_to_wal_journal_mode() var config = new RelationalDatabaseConfiguration( ConnectionString, outBoxTableName: tableName); var runner = new SqliteBoxMigrationRunner( - new SqliteOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), enableWalMode: true); + new SqliteOutboxMigrationCatalog(), config, TimeSpan.FromSeconds(30), enableWalMode: true, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act var freshHint = new BoxTableState(TableExists: false, HistoryExists: false, CurrentVersion: 0); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs index 4ad107ecd3..6a4a9f69ac 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_runner_is_constructed_without_lock_timeout_default_should_be_thirty_seconds.cs @@ -103,7 +103,8 @@ public async Task DisposeAsync() // Uses the detection-helper ctor with `lockTimeout` OMITTED — the path under regression-pin. public TimeoutCapturingSqliteBoxMigrationRunner(IAmARelationalDatabaseConfiguration configuration) - : base(new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), configuration) + : base(new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), configuration, + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance) { } diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v_latest.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v_latest.cs index 7ea409f84b..19317ba56e 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v_latest.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_sqlite_table_has_spec_0023_era_history_at_v1_it_should_transition_cleanly_to_v_latest.cs @@ -52,13 +52,13 @@ public async Task When_sqlite_table_has_spec_0023_era_history_at_v1_it_should_tr var columnsBefore = await GetTableColumns(); var config = new RelationalDatabaseConfiguration(_connectionString, outBoxTableName: _tableName); - var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config); + var runner = new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisioner = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - runner); + runner, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act await provisioner.ProvisionAsync(); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_two_sqlite_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_two_sqlite_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs index 7dc51db792..71cb287866 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_two_sqlite_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/BoxProvisioning/When_two_sqlite_provisioners_race_on_legacy_table_they_should_produce_exactly_one_synthetic_history_row.cs @@ -57,13 +57,13 @@ public async Task When_two_outbox_provisioners_race_on_legacy_table_they_should_ new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new SqliteOutboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteOutboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteOutboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); @@ -105,13 +105,13 @@ public async Task When_two_inbox_provisioners_race_on_legacy_table_they_should_p new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); var provisionerB = new SqliteInboxProvisioner( new SqliteBoxDetectionHelper(), new SqliteInboxMigrationCatalog(), new SqlitePayloadModeValidator(), config, - new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config)); + new SqliteBoxMigrationRunner(new SqliteInboxMigrationCatalog(), config, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); //Act — race two provisioners against the same legacy table. await Task.WhenAll(provisionerA.ProvisionAsync(), provisionerB.ProvisionAsync()); diff --git a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxAsyncTest.cs b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxAsyncTest.cs index ff9b41267f..1b03da115d 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxAsyncTest.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxAsyncTest.cs @@ -14,7 +14,7 @@ public class SqliteTextInboxAsyncTest : RelationalDatabaseInboxAsyncTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new SqliteInbox(configuration); + return new SqliteInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override async Task CreateInboxTableAsync(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxTest.cs b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxTest.cs index 9e644be6f5..017b96172c 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxTest.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/SqliteTextInboxTest.cs @@ -13,7 +13,7 @@ public class SqliteTextInboxTest : RelationalDatabaseInboxTests protected override RelationalDatabaseInbox CreateInbox(RelationalDatabaseConfiguration configuration) { - return new SqliteInbox(configuration); + return new SqliteInbox(configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } protected override void CreateInboxTable(RelationalDatabaseConfiguration configuration) diff --git a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/When_sqlite_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/When_sqlite_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs index 59869c818d..c45d2f05c2 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/Inbox/When_sqlite_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/Inbox/When_sqlite_inbox_tracks_causation_id_should_store_and_retrieve_via_base_tests.cs @@ -17,7 +17,7 @@ protected override void BeforeEachTest() _configuration = new RelationalDatabaseConfiguration( Tests.Configuration.ConnectionString, inboxTableName: $"{Tests.Configuration.TablePrefix}{Uuid.New():N}"); - _inbox = new SqliteInbox(_configuration); + _inbox = new SqliteInbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); base.BeforeEachTest(); } diff --git a/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Binary/SqliteBinaryOutboxProvider.cs b/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Binary/SqliteBinaryOutboxProvider.cs index 8aaa9e59b8..2c34888a49 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Binary/SqliteBinaryOutboxProvider.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Binary/SqliteBinaryOutboxProvider.cs @@ -18,12 +18,12 @@ public class SqliteBinaryOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxPr public IAmAnOutboxSync CreateOutbox() { - return new SqliteOutbox(_configuration); + return new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new SqliteOutbox(_configuration); + return new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -79,13 +79,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new SqliteOutbox(_configuration); + var outbox = new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new SqliteOutbox(_configuration); + var outbox = new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } } diff --git a/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Text/SqliteTextOutboxProvider.cs b/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Text/SqliteTextOutboxProvider.cs index 17a79251f8..71aa94b854 100644 --- a/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Text/SqliteTextOutboxProvider.cs +++ b/tests/Paramore.Brighter.Sqlite.Tests/Outbox/Text/SqliteTextOutboxProvider.cs @@ -18,12 +18,12 @@ public class SqliteTextOutboxProvider : IAmAnOutboxProviderSync, IAmAnOutboxProv public IAmAnOutboxSync CreateOutbox() { - return new SqliteOutbox(_configuration); + return new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public IAmAnOutboxAsync CreateOutboxAsync() { - return new SqliteOutbox(_configuration); + return new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); } public void CreateStore() @@ -79,13 +79,13 @@ public async Task DeleteStoreAsync(IEnumerable messages) public IEnumerable GetAllMessages() { - var outbox = new SqliteOutbox(_configuration); + var outbox = new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return outbox.Get(new RequestContext()); } public async Task> GetAllMessagesAsync() { - var outbox = new SqliteOutbox(_configuration); + var outbox = new SqliteOutbox(_configuration, logger: global::Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger(global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance)); return await outbox.GetAsync(new RequestContext()); } diff --git a/tests/Paramore.Brighter.TickerQ.Tests/TestDoubles/Fixtures/BaseTickerQFixture.cs b/tests/Paramore.Brighter.TickerQ.Tests/TestDoubles/Fixtures/BaseTickerQFixture.cs index b928ee5150..3aa90e0047 100644 --- a/tests/Paramore.Brighter.TickerQ.Tests/TestDoubles/Fixtures/BaseTickerQFixture.cs +++ b/tests/Paramore.Brighter.TickerQ.Tests/TestDoubles/Fixtures/BaseTickerQFixture.cs @@ -46,7 +46,7 @@ protected BaseTickerQFixture() var producerRegistry = new ProducerRegistry(new Dictionary { - [RoutingKey] = new InMemoryMessageProducer(InternalBus, new Publication { Topic = RoutingKey, RequestType = typeof(MyEvent) }) + [RoutingKey] = new InMemoryMessageProducer(InternalBus, global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, new Publication { Topic = RoutingKey, RequestType = typeof(MyEvent) }) }); var messageMapperRegistry = GetMapperRegistery(); @@ -62,7 +62,7 @@ protected BaseTickerQFixture() new EmptyMessageTransformerFactoryAsync(), trace, new FindPublicationByPublicationTopicOrRequestType(), - Outbox + global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance, Outbox ); _serviceCollection.AddSingleton(sp => @@ -90,7 +90,7 @@ protected BaseTickerQFixture() policyRegistry, new ResiliencePipelineRegistry(), outboxBus, - scheduler); + scheduler, loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); }); diff --git a/tests/Paramore.Brighter.Validation.FluentValidation.Tests/TestDoubles/CommandProcessorHarness.cs b/tests/Paramore.Brighter.Validation.FluentValidation.Tests/TestDoubles/CommandProcessorHarness.cs index d92993ac48..7fa3d763ee 100644 --- a/tests/Paramore.Brighter.Validation.FluentValidation.Tests/TestDoubles/CommandProcessorHarness.cs +++ b/tests/Paramore.Brighter.Validation.FluentValidation.Tests/TestDoubles/CommandProcessorHarness.cs @@ -92,7 +92,7 @@ private static CommandProcessorHarness Build(IValidator? valida new InMemoryRequestContextFactory(), new PolicyRegistry(), new ResiliencePipelineRegistry(), - new InMemorySchedulerFactory()); + new InMemorySchedulerFactory(loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance), loggerFactory: global::Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance); return new CommandProcessorHarness(commandProcessor, receipt); }