Exemple #1
0
        public override void Handle(IMessage msg, string processor)
        {
            using (var scope = Container.BeginLifetimeScope())
            {
                dynamic saga = HandlerInvoker.InstantiateHandler(scope);

                var correlationId = saga.GetCorrelationId(msg as IEvent);

                dynamic sagaState = scope.Resolve(SagaStateType);

                this.LogDebug($"Message '{msg}' started new saga {SagaStateType}");

                saga.Data = sagaState;
                HandlerInvoker.HandleMessage(msg, saga, processor);

                try
                {
                    SaveSagaState(sagaState, scope, correlationId, true);
                }
                catch (SagaExistsException)
                {
                    this.LogInfo($"Saga '{SagaStateType.FullName}' already exists. We leave it there");
                }
            }
        }
Exemple #2
0
        /**Add a route to the list of routes.
         * @param id The RouteID
         * @param type The pattern type to use
         * @param pattern The route pattern to match to
         * @param handler A lambda(or similar) to invoke a new HttpHandler, such as ()=>{return new MyHandler;}
         */
        public void AddRoute(string id, PatternTypes type, string pattern, HandlerInvoker handler)
        {
            var r = new Route {
                Pattern = pattern, Handler = handler, PatternType = type, ID = id
            };

            Routes.Add(r);
        }
Exemple #3
0
 /**Add a route to the list of routes.
  * @param id The RouteID
  * @param type The pattern type to use
  * @param pattern The route pattern to match to
  * @param handler A lambda(or similar) to invoke a new HttpHandler, such as ()=>{return new MyHandler;}
  */
 static public void AddRoute(string id, PatternTypes type, string pattern, HandlerInvoker handler)
 {
     /**TODO: This needs to be smart enough so that routes can not be added while routes are being parsed, else get a
      * "collection modified" exception from .Net. **/
     if (router == null)
     {
         router = new Router();
     }
     router.AddRoute(id, type, pattern, handler);
 }
Exemple #4
0
        async Task TryMountSagaDataOnInvoker(HandlerInvoker sagaInvoker, object body, string label, List <RelevantSagaInfo> loadedSagaData, List <RelevantSagaInfo> newlyCreatedSagaData, ITransactionContext transactionContext)
        {
            var foundExistingSagaData = false;

            var correlationProperties = _sagaHelper.GetCorrelationProperties(body, sagaInvoker.Saga);
            var correlationPropertiesRelevantForMessage = correlationProperties.ForMessage(body).ToArray();

            foreach (var correlationProperty in correlationPropertiesRelevantForMessage)
            {
                var valueFromMessage = correlationProperty.ValueFromMessage(new MessageContext(transactionContext), body);
                var sagaData         = await _sagaStorage.Find(sagaInvoker.Saga.GetSagaDataType(), correlationProperty.PropertyName, valueFromMessage);

                if (sagaData == null)
                {
                    continue;
                }

                sagaInvoker.SetSagaData(sagaData);
                foundExistingSagaData = true;
                loadedSagaData.Add(new RelevantSagaInfo(sagaData, correlationProperties, sagaInvoker.Saga));

                _log.Debug("Found existing saga data with ID {sagaDataId} for message {messageLabel}", sagaData.Id, label);
                break;
            }

            if (!foundExistingSagaData)
            {
                var messageType = body.GetType();
                var canBeInitiatedByThisMessageType = sagaInvoker.CanBeInitiatedBy(messageType);

                if (canBeInitiatedByThisMessageType)
                {
                    var newSagaData = _sagaHelper.CreateNewSagaData(sagaInvoker.Saga);

                    // if there's exacly one correlation property that points to a property on the saga data, we can set it
                    if (correlationPropertiesRelevantForMessage.Length == 1)
                    {
                        TrySetCorrelationPropertyValue(newSagaData, correlationPropertiesRelevantForMessage[0], body, transactionContext);
                    }

                    sagaInvoker.SetSagaData(newSagaData);

                    _log.Debug("Created new saga data with ID {sagaDataId} for message {messageLabel}", newSagaData.Id, label);

                    newlyCreatedSagaData.Add(new RelevantSagaInfo(newSagaData, correlationProperties, sagaInvoker.Saga));
                }
                else
                {
                    _log.Debug("Could not find existing saga data for message {messageLabel}", label);
                    sagaInvoker.SkipInvocation();
                }
            }
        }
Exemple #5
0
        public async Task HandlerInvokerTest()
        {
            //ARRANGE
            var result         = 0;
            var command        = new TestCommand(Guid.NewGuid(), Guid.NewGuid());
            var handler        = new TestCommandHandler(() => result = 10);
            var handlerInvoker = new HandlerInvoker();
            //ACT
            await handlerInvoker.InvokeHandlers(new[] { handler }, command);

            //ASSERT
            Assert.AreEqual(10, result);
        }
            public async Task Single_Handler_Can_Be_Invoked()
            {
                //ARRANGE
                var result         = 0;
                var logger         = new Mock <IGWLogger <BaseMessageHandler <TestMessage> > >();
                var command        = new TestMessage(Guid.NewGuid(), Guid.NewGuid());
                var handler        = new TestMessageHandler(() => result = 10, logger.Object, false);
                var handlerInvoker = new HandlerInvoker();
                //ACT
                await handlerInvoker.InvokeHandlers(new[] { handler }, command, CancellationToken.None);

                //ASSERT
                Assert.That(result, Is.EqualTo(10));
            }
            public void If_Handler_Is_Null_Argument_Null_Exception_Is_Thrown()
            {
                //ARRANGE
                var command        = new TestMessage(Guid.NewGuid(), Guid.NewGuid());
                var handlerInvoker = new HandlerInvoker();

                //ACT
                async Task Del()
                {
                    await handlerInvoker.InvokeHandlers(null, command, CancellationToken.None);
                }

                //ASSERT
                Assert.That(Del, Throws.ArgumentNullException);
            }
Exemple #8
0
        async Task TryMountSagaDataOnInvoker(HandlerInvoker sagaInvoker, object body, string label, List <RelevantSagaInfo> loadedSagaData, List <RelevantSagaInfo> newlyCreatedSagaData)
        {
            var foundExistingSagaData = false;

            var correlationProperties = _sagaHelper.GetCorrelationProperties(body, sagaInvoker.Saga);
            var correlationPropertiesRelevantForMessage = correlationProperties.ForMessage(body);

            foreach (var correlationProperty in correlationPropertiesRelevantForMessage)
            {
                var valueFromMessage = correlationProperty.ValueFromMessage(body);
                var sagaData         =
                    await
                    _sagaStorage.Find(sagaInvoker.Saga.GetSagaDataType(), correlationProperty.PropertyName, valueFromMessage);

                if (sagaData == null)
                {
                    continue;
                }

                sagaInvoker.SetSagaData(sagaData);
                foundExistingSagaData = true;
                loadedSagaData.Add(new RelevantSagaInfo(sagaData, correlationProperties, sagaInvoker.Saga));

                _log.Debug("Found existing saga data with ID {0} for message {1}", sagaData.Id, label);
                break;
            }

            if (!foundExistingSagaData)
            {
                var messageType = body.GetType();
                var canBeInitiatedByThisMessageType = sagaInvoker.CanBeInitiatedBy(messageType);

                if (canBeInitiatedByThisMessageType)
                {
                    var newSagaData = _sagaHelper.CreateNewSagaData(sagaInvoker.Saga);
                    sagaInvoker.SetSagaData(newSagaData);
                    _log.Debug("Created new saga data with ID {0} for message {1}", newSagaData.Id, label);
                    newlyCreatedSagaData.Add(new RelevantSagaInfo(newSagaData, correlationProperties, sagaInvoker.Saga));
                }
                else
                {
                    _log.Debug("Could not find existing saga data for message {0}", label);
                    sagaInvoker.SkipInvocation();
                }
            }
        }
Exemple #9
0
        public async Task HandlerInvokerTest()
        {
            //ARRANGE
            var result         = 0;
            var command        = new TestCommand(Guid.NewGuid(), Guid.NewGuid());
            var handler        = new TestCommandHandler(() => result = 10);
            var handlerInvoker = new HandlerInvoker();
            var serialised     = JsonConvert.SerializeObject(command, command.GetType(), new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Objects
            });
            var deserialised = JsonConvert.DeserializeObject(serialised, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Objects
            });
            //ACT
            await handlerInvoker.InvokeHandlers(new[] { handler }, (object)deserialised);

            //ASSERT
            Assert.AreEqual(10, result);
        }
        public async Task Setup()
        {
            exampleEventMappedTypeName = FullNameTypeMap.Instance.GetNameForType(typeof(ExampleEvent));

            var services = new ServiceCollection();

            services.AddSingleton(mockHandler);
            serviceProvider = services.BuildServiceProvider();

            behaviour = new HandlerInvoker(
                mockMessageSource.Object,
                services,
                FullNameTypeMap.Instance,
                "EndpointName",
                Mock.Of <IOutgoingPipeline>());

            await behaviour
            .Initialise(CancellationToken.None)
            .ConfigureAwait(false);
        }
            Muliple_Exceptions_Thrown_Within_Handlers_The_Exceptions_Will_Bubble_Though_To_Invoker_As_An_Aggreated_Exception()
            {
                //ARRANGE
                var          logger         = new Mock <IGWLogger <BaseMessageHandler <TestMessage> > >();
                const string errorMessage   = "Hello World! I am an error message";
                var          command        = new TestMessage(Guid.NewGuid(), Guid.NewGuid());
                var          handler1       = new TestMessageHandler(() => throw new Exception(errorMessage), logger.Object, false);
                var          handler2       = new TestMessageHandler(() => throw new Exception(errorMessage), logger.Object, false);
                var          handlerInvoker = new HandlerInvoker();

                //ACT
                try
                {
                    await handlerInvoker.InvokeHandlers(new object[] { handler1, handler2 }, command, CancellationToken.None);
                }
                catch (AggregateException ae)
                {
                    //ASSERT
                    Assert.That(ae.InnerExceptions.Count, Is.EqualTo(2));
                }
            }
            public async Task Exception_Thrown_Within_Handler_The_Exception_Will_Bubble_Though_To_Invoker()
            {
                //ARRANGE
                var          logger         = new Mock <IGWLogger <BaseMessageHandler <TestMessage> > >();
                const string errorMessage   = "Hello World! I am an error message";
                var          command        = new TestMessage(Guid.NewGuid(), Guid.NewGuid());
                var          handler        = new TestMessageHandler(() => throw new Exception(errorMessage), logger.Object, false);
                var          handlerInvoker = new HandlerInvoker();

                //ACT
                try
                {
                    await handlerInvoker.InvokeHandlers(new[] { handler }, command, CancellationToken.None);
                }
                catch (AggregateException ae)
                {
                    //ASSERT
                    var exception = ae.InnerExceptions.First();
                    Assert.That(exception, Is.TypeOf <Exception>());
                    Assert.That(exception.Message, Is.EqualTo(errorMessage));
                }
            }
Exemple #13
0
 internal HandlerInvokerWrapper(HandlerInvoker handlerInvokerImplementation, string messageType)
 {
     _handlerInvokerImplementation = handlerInvokerImplementation;
     _messageType = messageType;
 }