Example #1
0
        public void When_looking_for_undispatched_messages_in_outbox()
        {
            //Arrange
            var outbox = new InMemoryOutbox();

            var messageId    = Guid.NewGuid();
            var messageToAdd = new Message(
                new MessageHeader(messageId, "test_topic", MessageType.MT_DOCUMENT),
                new MessageBody("message body"));


            //Act
            outbox.Add(messageToAdd);

            var outstandingMessages = outbox.OutstandingMessages(0);

            //Assert
            outstandingMessages.Count().Should().Be(1);
            outstandingMessages.First().Id.Should().Be(messageId);
        }
Example #2
0
        private static async Task Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("usage: MultipleSender <count>");
                Console.WriteLine("eg   : MultipleSender 500");
                return;
            }

            if (!int.TryParse(args[0], out int repeatCount))
            {
                Console.WriteLine($"{args[0]} is not a valid number");
                return;
            }

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new HostBuilder()
                       .ConfigureServices((hostContext, services) =>
            {
                //create the gateway
                var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");

                services.AddBrighter(options =>
                {
                    var outBox = new InMemoryOutbox();
                    options.BrighterMessaging = new BrighterMessaging(outBox, new MsSqlMessageProducer(messagingConfiguration));
                }).AutoFromAssemblies();

                services.AddHostedService <RunCommandProcessor>(provider => new RunCommandProcessor(provider.GetService <IAmACommandProcessor>(), repeatCount));
            })
                       .UseConsoleLifetime()
                       .UseSerilog()
                       .Build();

            await host.RunAsync();
        }
Example #3
0
        private static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new HostBuilder()
                       .ConfigureServices((hostContext, services) =>

            {
                var outbox            = new InMemoryOutbox();
                var gatewayConnection = new RmqMessagingGatewayConnection
                {
                    AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                    Exchange = new Exchange("paramore.brighter.exchange")
                };
                var producer = new RmqMessageProducer(
                    connection: gatewayConnection,
                    new Publication
                {
                    MakeChannels = OnMissingChannel.Create
                });

                services.AddBrighter(options =>
                {
                    options.BrighterMessaging = new BrighterMessaging(outbox, producer);
                }).AutoFromAssemblies(typeof(GreetingEvent).Assembly);

                services.AddSingleton <IAmAnOutboxViewer <Message> >(outbox);

                services.AddHostedService <RunCommandProcessor>();
                services.AddHostedService <TimedOutboxSweeper>();
            }
                                          )
                       .UseConsoleLifetime()
                       .Build();

            await host.RunAsync();
        }
        public ProduceBehaviorTests()
        {
            var services = new ServiceCollection();

            services.AddSilverback()
            .WithConnectionToMessageBroker(
                options => options
                .AddBroker <TestBroker>()
                .AddOutbox <InMemoryOutbox>());

            services
            .AddSingleton(Substitute.For <IHostApplicationLifetime>())
            .AddLoggerSubstitute();

            var serviceProvider = services.BuildServiceProvider();

            _behavior = (ProduceBehavior)serviceProvider.GetServices <IBehavior>()
                        .First(behavior => behavior is ProduceBehavior);
            _broker = serviceProvider.GetRequiredService <TestBroker>();
            _outbox = (InMemoryOutbox)serviceProvider.GetRequiredService <IOutboxWriter>();
        }
Example #5
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var serviceCollection = new ServiceCollection();

            var rmqConnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };
            var producer = new RmqMessageProducer(rmqConnection);

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection);

            serviceCollection.AddBrighter(options =>
            {
                var outBox                = new InMemoryOutbox();
                options.ChannelFactory    = new ChannelFactory(rmqMessageConsumerFactory);
                options.BrighterMessaging = new BrighterMessaging(outBox, producer);
            }).AutoFromAssemblies();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();

            Console.WriteLine("Requesting Salutation...");

            //blocking call
            commandProcessor.Call <GreetingRequest, GreetingReply>(new GreetingRequest {
                Name = "Ian", Language = "en-gb"
            }, 2000);

            Console.WriteLine("Done...");
            Console.ReadLine();
        }
Example #6
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton <ILoggerFactory>(new SerilogLoggerFactory());

            var rmqConnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var producer = new RmqMessageProducer(rmqConnection, new RmqPublication
            {
                MaxOutStandingMessages = 5,
                MaxOutStandingCheckIntervalMilliSeconds = 500,
                WaitForConfirmsTimeOutInMilliseconds    = 1000,
                MakeChannels = OnMissingChannel.Create
            });

            serviceCollection.AddBrighter(options =>
            {
                var outBox = new InMemoryOutbox();
                options.BrighterMessaging = new BrighterMessaging(outBox, producer);
            }).AutoFromAssemblies();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();

            commandProcessor.Post(new GreetingEvent("Ian says: Hi there!"));
            commandProcessor.Post(new FarewellEvent("Ian says: See you later!"));
        }
        public CommandProcessorWithInMemoryOutboxAscyncTests()
        {
            _myCommand.Value = "Hello World";

            _outbox = new InMemoryOutbox();
            _fakeMessageProducerWithPublishConfirmation = new FakeMessageProducerWithPublishConfirmation();

            const string topic = "MyCommand";

            _message = new Message(
                new MessageHeader(_myCommand.Id, topic, MessageType.MT_COMMAND),
                new MessageBody(JsonSerializer.Serialize(_myCommand, JsonSerialisationOptions.Options))
                );

            var messageMapperRegistry = new MessageMapperRegistry(new SimpleMessageMapperFactory((_) => new MyCommandMessageMapper()));

            messageMapperRegistry.Register <MyCommand, MyCommandMessageMapper>();

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .RetryAsync();

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreakerAsync(1, TimeSpan.FromMilliseconds(1));

            _commandProcessor = new CommandProcessor(
                new InMemoryRequestContextFactory(),
                new PolicyRegistry {
                { CommandProcessor.RETRYPOLICYASYNC, retryPolicy }, { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy }
            },
                messageMapperRegistry,
                _outbox,
                new ProducerRegistry(new Dictionary <string, IAmAMessageProducer>()
            {
                { topic, _fakeMessageProducerWithPublishConfirmation },
            }));
        }
Example #8
0
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging();

            var asbConnection = new AzureServiceBusConfiguration("Endpoint=sb://.servicebus.windows.net/;Authentication=Managed Identity", true);

            var producer = AzureServiceBusMessageProducerFactory.Get(asbConnection);

            serviceCollection.AddBrighter(options =>
            {
                var outBox = new InMemoryOutbox();
                options.BrighterMessaging = new BrighterMessaging(outBox, producer: producer);
            }).AutoFromAssemblies();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();

            bool run = true;

            while (run)
            {
                Console.WriteLine("Sending....");

                commandProcessor.Post(new GreetingEvent("Paul"));
                commandProcessor.Post(new GreetingAsyncEvent("Paul - Async"));

                Console.WriteLine("Press q to Quit or any other key to continue");

                var keyPress = Console.ReadKey();
                if (keyPress.KeyChar == 'q')
                {
                    run = false;
                }
            }
        }
Example #9
0
        public void When_marking_dispatched_in_outbox()
        {
            //Arrange
            var outbox = new InMemoryOutbox();

            var messageId    = Guid.NewGuid();
            var messageToAdd = new Message(
                new MessageHeader(messageId, "test_topic", MessageType.MT_DOCUMENT),
                new MessageBody("message body"));


            //Act
            outbox.Add(messageToAdd);
            var dispatchedAt = DateTime.Now;

            outbox.MarkDispatched(messageId, dispatchedAt);

            var dispatchedMessages = outbox.DispatchedMessages(500);

            //Assert
            dispatchedMessages.Count().Should().Be(1);
            dispatchedMessages.First().Id.Should().Be(messageId);
        }
Example #10
0
        public void When_reading_from_outbox()
        {
            //Arrange
            var outbox = new InMemoryOutbox();

            var messageId    = Guid.NewGuid();
            var messageToAdd = new Message(
                new MessageHeader(messageId, "test_topic", MessageType.MT_DOCUMENT),
                new MessageBody("message body"));


            //Act
            outbox.Add(messageToAdd);

            var retrievedMessage = outbox.Get(messageId);

            //Assert
            retrievedMessage.Should().NotBeNull();
            retrievedMessage.Id.Should().Be(messageId);
            retrievedMessage.Header.Topic.Should().Be(messageToAdd.Header.Topic);
            retrievedMessage.Header.MessageType.Should().Be(messageToAdd.Header.MessageType);
            retrievedMessage.Body.Value.Should().Be(messageToAdd.Body.Value);
        }
Example #11
0
        public PostFailureLimitCommandTests()
        {
            _outbox = new InMemoryOutbox();
            _fakeMessageProducer = new FakeErroringMessageProducerSync();

            var messageMapperRegistry =
                new MessageMapperRegistry(new SimpleMessageMapperFactory((_) => new MyCommandMessageMapper()));

            messageMapperRegistry.Register <MyCommand, MyCommandMessageMapper>();

            _commandProcessor = CommandProcessorBuilder.With()
                                .Handlers(new HandlerConfiguration(new SubscriberRegistry(), new EmptyHandlerFactorySync()))
                                .DefaultPolicy()
                                .ExternalBus(new ExternalBusConfiguration(
                                                 new ProducerRegistry(new Dictionary <string, IAmAMessageProducer>()
            {
                { "MyCommand", _fakeMessageProducer },
            }),
                                                 messageMapperRegistry),
                                             _outbox
                                             )
                                .RequestContextFactory(new InMemoryRequestContextFactory())
                                .Build();
        }
        public void When_too_new_to_sweep_leaves_them()
        {
            //Arrange
            const int milliSecondsSinceSent = 500;

            var outbox           = new InMemoryOutbox();
            var commandProcessor = new FakeCommandProcessor();
            var sweeper          = new OutboxSweeper(milliSecondsSinceSent, outbox, commandProcessor);

            var messages = new Message[] { new MessageTestDataBuilder(), new MessageTestDataBuilder(), new MessageTestDataBuilder() };

            foreach (var message in messages)
            {
                outbox.Add(message);
                commandProcessor.Post(message.ToStubRequest());
            }

            //Act
            sweeper.Sweep();

            //Assert
            commandProcessor.Dispatched.Count.Should().Be(3);
            commandProcessor.Posted.Count.Should().Be(0);
        }
Example #13
0
 public InMemoryOutboundQueueTests()
 {
     _queue = new InMemoryOutbox(new TransactionalListSharedItems <OutboxStoredMessage>());
 }
Example #14
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            container.Register <IHandleRequests <GreetingRequest>, GreetingRequestHandler>();
            container.Register <IAmAMessageMapper <GreetingRequest>, GreetingRequestMessageMapper>();
            container.Register <IAmAMessageMapper <GreetingReply>, GreetingReplyMessageMapper>();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingRequest, GreetingRequestHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var outbox = new InMemoryOutbox();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingRequest), typeof(GreetingRequestMessageMapper) },
                { typeof(GreetingReply), typeof(GreetingReplyMessageMapper) }
            };

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var producer = new RmqMessageProducer(rmqConnnection);

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .TaskQueues(new MessagingConfiguration(outbox, producer, messageMapperRegistry))
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            container.Register <IAmACommandProcessor>(commandProcessor);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(commandProcessor)
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new ChannelFactory(rmqMessageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingRequest>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("Greeting.Request"),
                    new RoutingKey("Greeting.Request"),
                    timeoutInMilliseconds: 200,
                    isDurable: true,
                    highAvailability: true)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }
Example #15
0
        private static CommandProcessor BuildCommandProcessor(IServiceProvider provider)
        {
            var options            = provider.GetService <IBrighterOptions>();
            var subscriberRegistry = provider.GetService <ServiceCollectionSubscriberRegistry>();
            var useRequestResponse = provider.GetService <IUseRpc>();

            var handlerFactory       = new ServiceProviderHandlerFactory(provider);
            var handlerConfiguration = new HandlerConfiguration(subscriberRegistry, handlerFactory);

            var messageMapperRegistry = MessageMapperRegistry(provider);

            var outbox      = provider.GetService <IAmAnOutboxSync <Message> >();
            var asyncOutbox = provider.GetService <IAmAnOutboxAsync <Message> >();
            var overridingConnectionProvider = provider.GetService <IAmABoxTransactionConnectionProvider>();

            if (outbox == null)
            {
                outbox = new InMemoryOutbox();
            }
            if (asyncOutbox == null)
            {
                asyncOutbox = new InMemoryOutbox();
            }

            var inboxConfiguration = provider.GetService <InboxConfiguration>();

            var producerRegistry = provider.GetService <IAmAProducerRegistry>();

            var needHandlers = CommandProcessorBuilder.With();

            var featureSwitchRegistry = provider.GetService <IAmAFeatureSwitchRegistry>();

            if (featureSwitchRegistry != null)
            {
                needHandlers = needHandlers.ConfigureFeatureSwitches(featureSwitchRegistry);
            }

            var policyBuilder = needHandlers.Handlers(handlerConfiguration);

            var messagingBuilder = options.PolicyRegistry == null
                ? policyBuilder.DefaultPolicy()
                : policyBuilder.Policies(options.PolicyRegistry);

            var loggerFactory = provider.GetService <ILoggerFactory>();

            ApplicationLogging.LoggerFactory = loggerFactory;

            var commandProcessor = AddExternalBusMaybe(
                options,
                producerRegistry,
                messagingBuilder,
                messageMapperRegistry,
                inboxConfiguration,
                outbox,
                overridingConnectionProvider,
                useRequestResponse)
                                   .RequestContextFactory(options.RequestContextFactory)
                                   .Build();

            return(commandProcessor);
        }