Exemplo n.º 1
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Testing InMemory EventBus (y/n) ? ");
            var result = Console.ReadKey().Key;

            if (result == ConsoleKey.Y)
            {
                Console.WriteLine("Jitting now...");

                var bus = new InMemoryEventBus();
                await bus.PublishEventAsync(new TestEvent(-1, false, 0));

                Console.WriteLine("Testing 250 events WITHOUT parallel dispatch WITHOUT work simulation");
                for (int i = 0; i < 250; i++)
                {
                    await bus.PublishEventAsync(new TestEvent(i, false, 0));
                }

                Console.WriteLine("Testing 250 events WITHOUT parallel dispatch WITH 100 ms work simulation");
                for (int i = 0; i < 250; i++)
                {
                    await bus.PublishEventAsync(new TestEvent(i, true, 100));
                }

                Console.WriteLine("Testing 250 events WITH parallel dispatch WITH 100 ms work simulation");

                var tasks = new List <Task>();
                for (int i = 0; i < 250; i++)
                {
                    tasks.Add(bus.PublishEventAsync(new TestEvent(i, true, 100)));
                }
                await Task.WhenAll(tasks);
            }
            Console.Read();
        }
Exemplo n.º 2
0
        public async Task InMemoryEventBus_PublishEventAsync_ResolutionException_Should_NotTryToResolveTwice()
        {
            var scopeMock         = new Mock <IScope>();
            var loggerMock        = new Mock <ILogger>();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(loggerMock.Object);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(It.IsAny <Type>(), It.IsAny <IResolverParameter[]>()))
            .Throws(new IoCResolutionException());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new UnresolvableEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            scopeMock.Verify(m => m.Resolve(typeof(UnresolvableEventHandler), It.IsAny <IResolverParameter[]>()), Times.Once());

            (await b.PublishEventAsync(new UnresolvableEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            scopeMock.Verify(m => m.Resolve(typeof(UnresolvableEventHandler), It.IsAny <IResolverParameter[]>()), Times.Once());
            loggerMock.Verify(x =>
                              x.Log(LogLevel.Error, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Once());
        }
Exemplo n.º 3
0
        public async Task InMemoryEventBus_PublishEventAsync_ResolutionException_Should_NotTryToResolveTwice()
        {
            var scopeMock         = new Mock <IScope>();
            var loggerFactoryMock = new Mock <ILoggerFactory>();
            var fakeLogger        = new FakeLogger(LogLevel.Error);

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(fakeLogger);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(It.IsAny <Type>(), It.IsAny <IResolverParameter[]>()))
            .Throws(new IoCResolutionException());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new UnresolvableEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            scopeMock.Verify(m => m.Resolve(typeof(UnresolvableEventHandler), It.IsAny <IResolverParameter[]>()), Times.Once());

            (await b.PublishEventAsync(new UnresolvableEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            scopeMock.Verify(m => m.Resolve(typeof(UnresolvableEventHandler), It.IsAny <IResolverParameter[]>()), Times.Once());
            fakeLogger.CurrentLogValue.Should().NotBeNullOrEmpty();
            fakeLogger.NbLogs.Should().Be(1);
        }
Exemplo n.º 4
0
 async Task ReceiveMessageAsync(Message message, CancellationToken token)
 {
     if (message?.Body != null)
     {
         try
         {
             var bodyAsString = Encoding.UTF8.GetString(message.Body);
             if (!string.IsNullOrWhiteSpace(bodyAsString))
             {
                 var objType = Type.GetType(message.ContentType);
                 if (objType.GetInterfaces().Any(i => i.Name == nameof(IDomainEvent)))
                 {
                     var eventInstance = _configuration.QueueConfiguration.Serializer.DeserializeEvent(bodyAsString, objType);
                     _configuration.QueueConfiguration.Callback?.Invoke(eventInstance);
                     if (_configuration.QueueConfiguration.DispatchInMemory && _inMemoryEventBus != null)
                     {
                         await _inMemoryEventBus.PublishEventAsync(eventInstance).ConfigureAwait(false);
                     }
                 }
             }
         }
         catch (Exception exc)
         {
             _logger.LogErrorMultilines("AzureServiceBusServer : Error when treating event.", exc.ToString());
         }
     }
     else
     {
         var eventType = message?.ContentType;
         _logger.LogWarning("AzureServiceBusServer : Empty message received or event fired by unknown model !" +
                            (!string.IsNullOrWhiteSpace(eventType) ? $"Event type : {eventType}" : ""));
     }
 }
Exemplo n.º 5
0
        public async Task InMemoryEventBus_PublishEventAsync_Should_Respect_Priority()
        {
            var b = new InMemoryEventBus();

            s_OrderString.Should().BeNullOrWhiteSpace();

            (await b.PublishEventAsync(new OrderedEvent()).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            s_OrderString.Should().Be("HNL");
        }
Exemplo n.º 6
0
        public async Task InMemoryEventBus_PublishEventAsync_OneHandlerInError_Should_NotDispatch_MultipleTimes_ToSuccessfullHandlers()
        {
            var errorEvent = new ErrorEvent();
            var b          = new InMemoryEventBus(new InMemoryEventBusConfigurationBuilder()
                                                  .SetRetryStrategy(1, 2).Build());

            (await b.PublishEventAsync(errorEvent)).IsSuccess.Should().BeFalse();

            errorEvent.Data.Should().Be("1222");
        }
Exemplo n.º 7
0
        public async Task Publish_Event_CriticalHandlerThrow_Should_NotCallNextHandlers()
        {
            var evt        = new CriticalEvent();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder();
            var bus = new InMemoryEventBus(cfgBuilder.Build());

            (await bus.PublishEventAsync(evt)).IsSuccess.Should().BeTrue();

            evt.HandlerData.Should().Be("AB");
        }
Exemplo n.º 8
0
        public async Task InMemoryEventBus_PublishEventAsync_HandlerInDispatcher()
        {
            CoreDispatcher.AddHandlerToDispatcher(new TestEventContextHandler(1));
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(1);
        }
Exemplo n.º 9
0
        public async Task InMemoryEventBus_PublishEventAsync_ContextAsHandler()
        {
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }, new TestEventContextHandler(0)).ConfigureAwait(false))
            .IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(0);
        }
Exemplo n.º 10
0
        public async Task Publish_Event_CriticalHandlerThrow_Should_BeTheOnlyOneRetried_If_RetryStrategy_IsDefined()
        {
            var evt        = new CriticalEvent();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(1, 3);
            var bus = new InMemoryEventBus(cfgBuilder.Build());

            (await bus.PublishEventAsync(evt)).IsSuccess.Should().BeTrue();

            evt.HandlerData.Should().Be("ABBBC");
            evt.NbTries.Should().Be(3);
        }
Exemplo n.º 11
0
        public async Task InMemoryEventBus_Configuration_DispatchIfClause()
        {
            TestIfEventHandler.ResetData();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .DispatchOnlyIf <TestIfEvent>(e => e.Data > 1);

            var b = new InMemoryEventBus(cfgBuilder.Build());

            TestIfEventHandler.Data.Should().Be(0);

            (await b.PublishEventAsync(new TestIfEvent {
                Data = 1
            }).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            TestIfEventHandler.Data.Should().Be(0);

            (await b.PublishEventAsync(new TestIfEvent {
                Data = 10
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestIfEventHandler.Data.Should().Be(10);
        }
Exemplo n.º 12
0
        public async Task InMemoryEventBus_Configuration_RetryStrategy_CallbackNoInvoked()
        {
            bool callbackCalled = false;
            var  cfgBuilder     =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(100, 3)
                .DefineErrorCallback((e, ctx) => callbackCalled = true);

            var b = new InMemoryEventBus(cfgBuilder.Build());

            (await b.PublishEventAsync(new TestRetryEvent()).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            callbackCalled.Should().BeFalse();
        }
Exemplo n.º 13
0
        public async Task InMemoryEventBus_Configuration_ParallelDispatch()
        {
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .AllowParallelDispatchFor <ParallelEvent>();

            var b = new InMemoryEventBus(cfgBuilder.Build());

            var evt = new ParallelEvent();

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            evt.ThreadsInfos.Should().HaveCount(2);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Start the MSMQ in-app server.
        /// </summary>
        public Task StartAsync(CancellationToken cancellationToken = default)
        {
            if (cancellationToken == default)
            {
                _tokenSource = new CancellationTokenSource();
                _token       = _tokenSource.Token;
            }
            else
            {
                _token = cancellationToken;
            }
            var queue = Helpers.GetMessageQueue(_configuration.QueueName);

            RunningTask = Task.Run(() =>
            {
                while (true)
                {
                    var message = queue.Receive();
                    //Start every reception in a separate task for perf and safety.
                    Task.Run(async() =>
                    {
                        if (!string.IsNullOrWhiteSpace(message.Body?.ToString()))
                        {
                            try
                            {
                                var enveloppe = message.Body.ToString().FromJson <Enveloppe>();
                                if (enveloppe.Emiter != _emiter)
                                {
                                    var data = enveloppe.Data.FromJson(Type.GetType(enveloppe.AssemblyQualifiedDataType));
                                    _configuration?.Callback(data);
                                    if (data is IDomainEvent @event && (_configuration == null || _configuration.DispatchInMemory))
                                    {
                                        await _inMemoryEventBus?.PublishEventAsync(@event);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                _logger?.LogError($"MSMQServer : Cannot treat message id {message.Id} {Environment.NewLine} {e}");
                            }
                        }
                    }, cancellationToken);
                }
            }, cancellationToken);
            return(Task.CompletedTask);
        }
Exemplo n.º 15
0
 private async void OnEventReceived(object model, BasicDeliverEventArgs args)
 {
     if (args.Body?.Any() == true && model is EventingBasicConsumer consumer)
     {
         try
         {
             var dataAsStr = Encoding.UTF8.GetString(args.Body);
             var enveloppe = dataAsStr.FromJson <Enveloppe>();
             if (enveloppe != null)
             {
                 if (enveloppe.Emiter == _config.Emiter)
                 {
                     return;
                 }
                 if (!string.IsNullOrWhiteSpace(enveloppe.Data) && !string.IsNullOrWhiteSpace(enveloppe.AssemblyQualifiedDataType))
                 {
                     var objType = Type.GetType(enveloppe.AssemblyQualifiedDataType);
                     if (objType != null)
                     {
                         if (objType.GetInterfaces().Any(i => i.Name == nameof(IDomainEvent)))
                         {
                             var evt = _config.QueueConfiguration.Serializer.DeserializeEvent(enveloppe.Data, objType);
                             _config.QueueConfiguration.Callback?.Invoke(evt);
                             if (_config.QueueConfiguration.DispatchInMemory && _inMemoryEventBus != null)
                             {
                                 await _inMemoryEventBus.PublishEventAsync(evt).ConfigureAwait(false);
                             }
                             consumer.Model.BasicAck(args.DeliveryTag, false);
                         }
                     }
                 }
             }
         }
         catch (Exception exc)
         {
             _logger.LogErrorMultilines("RabbitMQServer : Error when treating event.", exc.ToString());
             consumer.Model.BasicReject(args.DeliveryTag, false); //TODO make it configurable for retry or so
         }
     }
     else
     {
         _logger.LogWarning("RabbitMQServer : Empty message received or event fired by bad model !");
     }
 }
Exemplo n.º 16
0
        public async Task InMemoryEventBus_PublishEventAsync_HandlerSameInstance_Should_NotBeCalledTwice()
        {
            TestEventContextHandler.CallTimes = 0;
            var h = new TestEventContextHandler(1);

            CoreDispatcher.AddHandlerToDispatcher(new TestEventContextHandler(1));
            CoreDispatcher.AddHandlerToDispatcher(h);
            CoreDispatcher.AddHandlerToDispatcher(h);

            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(1);
            TestEventContextHandler.CallTimes.Should().Be(1);
        }
Exemplo n.º 17
0
        public async Task InMemoryEventBus_ResolutionError_Type_IsSubViewModel_Should_NotLogAnything()
        {
            var scopeMock         = new Mock <IScope>();
            var loggerMock        = new Mock <ILogger>();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(loggerMock.Object);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(typeof(SubViewModel), It.IsAny <IResolverParameter[]>())).Throws(new Exception());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new SubVMEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            loggerMock.Verify(x =>
                              x.Log(LogLevel.Error, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Never());
        }
Exemplo n.º 18
0
        public async Task InMemoryEventBus_ResolutionError_Type_IsSubViewModel_Should_NotLogAnything()
        {
            var scopeMock         = new Mock <IScope>();
            var fakeLogger        = new FakeLogger(LogLevel.Error);
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(fakeLogger);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(typeof(SubViewModel), It.IsAny <IResolverParameter[]>())).Throws(new Exception());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new SubVMEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            fakeLogger.CurrentLogValue.Should().BeNullOrEmpty();
            fakeLogger.NbLogs.Should().Be(0);
        }
Exemplo n.º 19
0
        public async Task InMemoryEventBus_Configuration_RetryStrategy_WhenDispatchParallel()
        {
            bool callbackCalled = false;
            var  cfgBuilder     =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(100, 3)
                .DefineErrorCallback((e, ctx) => callbackCalled = true)
                .AllowParallelDispatchFor <ParallelEvent>();

            var b = new InMemoryEventBus(cfgBuilder.Build());

            var evt = new ParallelEvent()
            {
                RetryMode = true
            };

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            callbackCalled.Should().BeFalse();
            evt.ThreadsInfos.Should().HaveCount(2);
        }
Exemplo n.º 20
0
        public async Task InMemoryEventBus_PublishEventAsync_TransactionnalEvent()
        {
            TransactionEventHandler.DataParsed = string.Empty;

            var evt = new TransactionEvent(
                new Event1 {
                Data = "Data1"
            },
                new Event2 {
                Data = "Data2"
            },
                new Event3 {
                Data = "Data3"
            }
                );

            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TransactionEventHandler.DataParsed.Should().Be("|1:Data1|2:Data2|3:Data3");
        }
Exemplo n.º 21
0
        public async Task PublishEventAsync_Should_ResultFail_ShouldBeReturned()
        {
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestResultFailedEvent(), null).ConfigureAwait(false)).IsSuccess.Should().BeFalse();
        }
Exemplo n.º 22
0
 public async Task PublishSingleEvent()
 {
     var bus = new InMemoryEventBus();
     await bus.PublishEventAsync(new TestDispatchEvent(0, MillisecondsJobDuration != 0, MillisecondsJobDuration));
 }
Exemplo n.º 23
0
        public async Task InMemoryEventBus_PublishEventAsync_ExceptionInHandler()
        {
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestExceptionEvent(), null).ConfigureAwait(false)).IsSuccess.Should().BeFalse();
        }