Esempio n. 1
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
            IConsumeContext <TMessage> context, InstanceHandlerSelector <TConsumer, TMessage> selector)
            where TMessage : class
        {
            TConsumer consumer = _factoryMethod();

            if (consumer == null)
            {
                throw new ConfigurationException(string.Format("Unable to resolve consumer type '{0}'.", typeof(TConsumer)));
            }

            try
            {
                foreach (var handler in selector(consumer, context))
                {
                    yield return(handler);
                }
            }
            finally
            {
                var disposable = consumer as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Esempio n. 2
0
        GetConsumer <TMessage>(IConsumeContext <TMessage> context,
                               InstanceHandlerSelector <TConsumer, TMessage> selector)
            where TMessage : class
        {
            IEnumerable <Action <IConsumeContext <TMessage> > > consumers = _consumerFactory.GetConsumer(context, selector);

            foreach (var action in consumers)
            {
                Action <IConsumeContext <TMessage> > consumer = action;

                yield return(message =>
                {
                    var received = new ReceivedMessageImpl <TMessage>(message);

                    try
                    {
                        consumer(message);
                    }
                    catch (Exception ex)
                    {
                        received.SetException(ex);
                    }
                    finally
                    {
                        _received.Add(received);
                    }
                });
            }
        }
Esempio n. 3
0
        public void Setup()
        {
            _repository = new InMemorySagaRepository <SimpleSaga>();
            var initiatePolicy = new InitiatingSagaPolicy <SimpleSaga, InitiateSimpleSaga>(x => x.CorrelationId, x => false);

            _sagaId       = CombGuid.Generate();
            _initiateSaga = new InitiateSimpleSaga {
                CorrelationId = _sagaId, Name = "Chris"
            };
            var context = _initiateSaga.ToConsumeContext();

            _repository.GetSaga(context, _sagaId,
                                (i, c) => InstanceHandlerSelector.ForInitiatedBy <SimpleSaga, InitiateSimpleSaga>(i), initiatePolicy)
            .Each(x => x(context));

            _initiateOtherSaga = new InitiateSimpleSaga {
                CorrelationId = _otherSagaId, Name = "Dru"
            };

            _otherSagaId = Guid.NewGuid();
            context      = _initiateOtherSaga.ToConsumeContext();
            _repository.GetSaga(context, _otherSagaId,
                                (i, c) => InstanceHandlerSelector.ForInitiatedBy <SimpleSaga, InitiateSimpleSaga>(i), initiatePolicy)
            .Each(x => x(context));

            _observeSaga = new ObservableSagaMessage {
                Name = "Chris"
            };
        }
Esempio n. 4
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
            IConsumeContext <TMessage> context, InstanceHandlerSelector <T, TMessage> selector)
            where TMessage : class
        {
            var activationBlock = _kernel.BeginBlock();

            var consumer = activationBlock.Get <T>();

            if (consumer == null)
            {
                throw new ConfigurationException(string.Format("Unable to resolve type '{0}' from container: ", typeof(T)));
            }

            try
            {
                IEnumerable <Action <IConsumeContext <TMessage> > > result = selector(consumer, context);

                foreach (var handler in result)
                {
                    yield return(handler);
                }
            }
            finally
            {
                activationBlock.Dispose();
            }
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
            IConsumeContext <TMessage> context, InstanceHandlerSelector <T, TMessage> selector)
            where TMessage : class
        {
            using (_container.BeginScope())
            {
                var consumer = _container.Resolve <T>();
                if (consumer == null)
                {
                    throw new ConfigurationException(string.Format("Unable to resolve type '{0}' from container: ", typeof(T)));
                }

                try
                {
                    foreach (var handler in selector(consumer, context))
                    {
                        yield return(handler);
                    }
                }
                finally
                {
                    _container.Release(consumer);
                }
            }
        }
Esempio n. 6
0
 protected SagaMessageSinkBase(ISagaRepository <TSaga> repository, ISagaPolicy <TSaga, TMessage> policy,
                               ISagaLocator <TMessage> locator, InstanceHandlerSelector <TSaga, TMessage> selector)
 {
     _selector  = selector;
     _locator   = locator;
     Repository = repository;
     Policy     = policy;
 }
        /// <summary> Enumerates get saga in this collection. </summary>
        /// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are null. </exception>
        /// <exception cref="SagaException"> Thrown when a saga error condition occurs. </exception>
        /// <typeparam name="TMessage"> Type of the message. </typeparam>
        /// <param name="context"> The context. </param>
        /// <param name="sagaId"> Identifier for the saga. </param>
        /// <param name="selector"> The selector. </param>
        /// <param name="policy"> The policy. </param>
        /// <returns> An enumerator that allows foreach to be used to process get saga&lt; t message&gt; in this collection. </returns>
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(
            IConsumeContext <TMessage> context,
            Guid sagaId,
            InstanceHandlerSelector <TSaga, TMessage> selector,
            ISagaPolicy <TSaga, TMessage> policy) where TMessage : class
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }
            if (policy == null)
            {
                throw new ArgumentNullException("policy");
            }

            TSaga instance = Queryable.FirstOrDefault(x => x.CorrelationId == sagaId);

            if (instance == null)
            {
                if (policy.CanCreateInstance(context))
                {
                    yield return(CreateNewSagaAction(sagaId, selector, policy));
                }
                else
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat(
                            "SAGA: {0} Ignoring Missing {1} for {2}",
                            typeof(TSaga).ToFriendlyName(),
                            sagaId,
                            typeof(TMessage).ToFriendlyName());
                    }
                }
            }
            else
            {
                if (policy.CanUseExistingInstance(context))
                {
                    yield return(UseExistingSagaAction(sagaId, selector, policy, instance));
                }
                else
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat(
                            "SAGA: {0} Ignoring Existing {1} for {2}",
                            typeof(TSaga).ToFriendlyName(),
                            sagaId,
                            typeof(TMessage).ToFriendlyName());
                    }
                }
            }
        }
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>
     (IConsumeContext <TMessage> context, Guid sagaId, InstanceHandlerSelector <T, TMessage> selector, ISagaPolicy <T, TMessage> policy)
     where TMessage : class
 {
     return(_repository.GetSaga(context, sagaId, selector, policy)
            .Select(consumer => (Action <IConsumeContext <TMessage> >)(x => {
         using (_container.BeginLifetimeScope())
             consumer(x);
     })));
 }
        /// <summary>
        ///     Creates new saga action.
        /// </summary>
        /// <exception cref="SagaException"> Thrown when a saga error condition occurs.</exception>
        /// <typeparam name="TMessage"> Type of the message.</typeparam>
        /// <param name="sagaId">   Identifier for the saga.</param>
        /// <param name="selector"> The selector.</param>
        /// <param name="policy">   The policy.</param>
        /// <returns>
        ///     The new new saga action&lt; t message&gt;
        /// </returns>
        Action <IConsumeContext <TMessage> > CreateNewSagaAction <TMessage>(
            Guid sagaId,
            InstanceHandlerSelector <TSaga, TMessage> selector,
            ISagaPolicy <TSaga, TMessage> policy)
            where TMessage : class
        {
            return(x =>
            {
                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat(
                        "SAGA: {0} Creating New {1} for {2}",
                        typeof(TSaga).ToFriendlyName(),
                        sagaId,
                        typeof(TMessage).ToFriendlyName());
                }

                try
                {
                    TSaga instance = policy.CreateInstance(x, sagaId);

                    foreach (var callback in selector(instance, x))
                    {
                        callback(x);
                    }

                    if (!policy.CanRemoveInstance(instance))
                    {
                        Collection.Insert(instance, WriteConcern.Acknowledged);
                    }
                    else
                    {
                        Collection.Save(instance, WriteConcern.Acknowledged);
                    }
                }
                catch (Exception ex)
                {
                    var sagaException = new SagaException(
                        "Create Saga Instance Exception",
                        typeof(TSaga),
                        typeof(TMessage),
                        sagaId,
                        ex);

                    if (Log.IsErrorEnabled)
                    {
                        Log.Error(sagaException);
                    }

                    throw sagaException;
                }
            });
        }
        /// <summary>
        ///     Use existing saga action.
        /// </summary>
        /// <exception cref="SagaException"> Thrown when a saga error condition occurs.</exception>
        /// <typeparam name="TMessage"> Type of the message.</typeparam>
        /// <param name="sagaId">   Identifier for the saga.</param>
        /// <param name="selector"> The selector.</param>
        /// <param name="policy">   The policy.</param>
        /// <param name="instance"> The instance.</param>
        /// <returns>
        ///     .
        /// </returns>
        Action <IConsumeContext <TMessage> > UseExistingSagaAction <TMessage>(
            Guid sagaId,
            InstanceHandlerSelector <TSaga, TMessage> selector,
            ISagaPolicy <TSaga, TMessage> policy,
            TSaga instance)
            where TMessage : class
        {
            return(x =>
            {
                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat(
                        "SAGA: {0} Using Existing {1} for {2}",
                        typeof(TSaga).ToFriendlyName(),
                        sagaId,
                        typeof(TMessage).ToFriendlyName());
                }

                try
                {
                    foreach (var callback in selector(instance, x))
                    {
                        callback(x);
                    }

                    if (policy.CanRemoveInstance(instance))
                    {
                        Collection.Remove(
                            GetMongoQuery(Queryable.Where(q => q.CorrelationId == sagaId)),
                            RemoveFlags.Single,
                            WriteConcern.Acknowledged);
                    }
                }
                catch (Exception ex)
                {
                    var sagaException = new SagaException(
                        "Existing Saga Instance Exception",
                        typeof(TSaga),
                        typeof(TMessage),
                        sagaId,
                        ex);
                    if (Log.IsErrorEnabled)
                    {
                        Log.Error(sagaException);
                    }

                    throw sagaException;
                }
            });
        }
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>
     (IConsumeContext <TMessage> context, InstanceHandlerSelector <T, TMessage> selector)
     where TMessage : class
 {
     using (_container.BeginLifetimeScope()) {
         T consumer = _container.GetInstance <T>();
         if (consumer == null)
         {
             throw new ConfigurationException(string.Format("Unable to resolve type '{0}' from container: ", typeof(T)));
         }
         foreach (Action <IConsumeContext <TMessage> > action in selector(consumer, context))
         {
             yield return(action);
         }
     }
 }
Esempio n. 12
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
            IConsumeContext <TMessage> context, InstanceHandlerSelector <T, TMessage> selector)
            where TMessage : class
        {
            //lookup TMessage against all the types we loaded from the assembly we scanned and get back the handler
            if (!_messageHandlerMap.ContainsKey(typeof(T)))
            {
                throw new InvalidOperationException(string.Format("There is no consumer registered to handle commands of type '{0}'.", typeof(T)));
            }

            var consumerType = _messageHandlerMap[typeof(TMessage)];

            var consumerInstance = (T)Activator.CreateInstance(consumerType);

            IEnumerable <Action <IConsumeContext <TMessage> > > result = selector(consumerInstance, context);

            return(result);
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId,
                                                                                      InstanceHandlerSelector <TSaga, TMessage>
                                                                                      selector, ISagaPolicy <TSaga, TMessage> policy)
            where TMessage : class
        {
            ISagaPolicy <TSaga, TMessage> sagaPolicy = new SagaPolicyTestDecorator <TSaga, TMessage>(policy, sagaId, _created);

            InstanceHandlerSelector <TSaga, TMessage> interceptSelector = (s, c) =>
            {
                IEnumerable <Action <IConsumeContext <TMessage> > > result = selector(s, c);

                return(DecorateSelector(s, result));
            };

            IEnumerable <Action <IConsumeContext <TMessage> > > consumers = _sagaRepository.GetSaga(context, sagaId, interceptSelector,
                                                                                                    sagaPolicy);

            foreach (var action in consumers)
            {
                Action <IConsumeContext <TMessage> > consumer = action;

                yield return(message =>
                {
                    var received = new ReceivedMessage <TMessage>(message);

                    try
                    {
                        consumer(message);
                    }
                    catch (Exception ex)
                    {
                        received.SetException(ex);
                    }
                    finally
                    {
                        _received.Add(received);
                    }
                });
            }
        }
Esempio n. 14
0
        public void Setup()
        {
            _sagaId = NewId.NextGuid();

            _repository = new InMemorySagaRepository <TestSaga>();

            var initiatePolicy = new InitiatingSagaPolicy <TestSaga, InitiateSimpleSaga>(x => x.CorrelationId, x => false);


            var message = new InitiateSimpleSaga(_sagaId);

            IConsumeContext <InitiateSimpleSaga> context = message.ToConsumeContext();

            _repository.GetSaga(context, message.CorrelationId,
                                (i, c) => InstanceHandlerSelector.ForDataEvent(i, TestSaga.Initiate), initiatePolicy)
            .Each(x => x(context));

            message = new InitiateSimpleSaga(NewId.NextGuid());
            context = message.ToConsumeContext();
            _repository.GetSaga(context, message.CorrelationId,
                                (i, c) => InstanceHandlerSelector.ForDataEvent(i, TestSaga.Initiate), initiatePolicy)
            .Each(x => x(context));
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
            IConsumeContext <TMessage> context, InstanceHandlerSelector <T, TMessage> selector)
            where TMessage : class
        {
            using (var innerScope = _scope.BeginLifetimeScope(_name))
            {
                T consumer = null;
                try
                {
                    consumer = innerScope.Resolve <T>();
                }
                catch (Exception ex)
                {
                    var message = "Could not resolve '{0}' from container '{1}'->'{2}'".FormatWith(typeof(T).Name, _scope.Tag, innerScope.Tag);
                    throw new ConfigurationException(message, ex);
                }

                foreach (var handler in selector(consumer, context))
                {
                    yield return(handler);
                }
            }
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context,
                                                                                      Guid sagaId, InstanceHandlerSelector <T, TMessage> selector, ISagaPolicy <T, TMessage> policy)
            where TMessage : class
        {
            return(_repository.GetSaga(context, sagaId, selector, policy)
                   .Select(consumer => (Action <IConsumeContext <TMessage> >)(x =>
            {
                IActivationBlock activationBlock = _kernel.BeginBlock();

                try
                {
                    consumer(x);
                }
                finally
                {
                    activationBlock.Dispose();
                }
            })));
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId,
                                                                                      InstanceHandlerSelector <TSaga, TMessage> selector,
                                                                                      ISagaPolicy <TSaga, TMessage> policy) where TMessage : class
        {
            using (var db = dbProvider.Open())
                using (var transaction = db.BeginTransaction())
                {
                    TSaga instance = db.Get <TSaga>(sagaId, transaction);
                    Console.WriteLine("Got instance: {0}", instance == null ? "no instance" : instance.ToString());
                    if (instance == null)
                    {
                        if (policy.CanCreateInstance(context))
                        {
                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Creating New {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    instance = policy.CreateInstance(x, sagaId);

                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (!policy.CanRemoveInstance(instance))
                                    {
                                        try
                                        {
                                            db.Insert(instance, transaction);
                                        }
                                        catch (Exception)
                                        {
                                            // if insert fails update
                                            db.Update(instance, transaction);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Create Saga Instance Exception", typeof(TSaga), typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }
                                    //if(transaction.IsActive) - Transaction is always active
                                    transaction.Rollback();

                                    throw sex;
                                }
                            });
                        }
                        else
                        {
                            if (_log.IsDebugEnabled)
                            {
                                _log.DebugFormat("SAGA: {0} Ignoring Missing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                 typeof(TMessage).ToFriendlyName());
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Have existing instance " + instance.ToString());
                        if (policy.CanUseExistingInstance(context))
                        {
                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Using Existing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (policy.CanRemoveInstance(instance))
                                    {
                                        db.Delete(instance, transaction);
                                    }
                                    else
                                    {
                                        db.Update(instance, transaction);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Existing Saga Instance Exception", typeof(TSaga), typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }
                                    //if(transaction.IsActive) - Transaction is always active
                                    transaction.Rollback();

                                    throw sex;
                                }
                            });
                        }
                        else
                        {
                            if (_log.IsDebugEnabled)
                            {
                                _log.DebugFormat("SAGA: {0} Ignoring Existing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                 typeof(TMessage).ToFriendlyName());
                            }
                        }
                    }
                    transaction.Commit();
                }
        }
Esempio n. 18
0
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context,
                                                                               Guid sagaId, InstanceHandlerSelector <TInstance, TMessage> selector, ISagaPolicy <TInstance, TMessage> policy)
     where TMessage : class
 {
     return(_repository.GetSaga(context, sagaId, selector, policy));
 }
Esempio n. 19
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId,
                                                                                      InstanceHandlerSelector <TSaga, TMessage>
                                                                                      selector, ISagaPolicy <TSaga, TMessage> policy)
            where TMessage : class
        {
            bool needToLeaveSagas = true;

            Monitor.Enter(_sagas);
            try
            {
                TSaga instance = _sagas[sagaId];

                if (instance == null)
                {
                    if (policy.CanCreateInstance(context))
                    {
                        instance = policy.CreateInstance(context, sagaId);
                        _sagas.Add(instance);

                        lock (instance)
                        {
                            Monitor.Exit(_sagas);
                            needToLeaveSagas = false;

                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Creating New {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (policy.CanRemoveInstance(instance))
                                    {
                                        _sagas.Remove(instance);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Create Saga Instance Exception", typeof(TSaga), typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }

                                    throw sex;
                                }
                            });
                        }
                    }
                    else
                    {
                        if (_log.IsDebugEnabled)
                        {
                            _log.DebugFormat("SAGA: {0} Ignoring Missing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                             typeof(TMessage).ToFriendlyName());
                        }
                    }
                }
                else
                {
                    if (policy.CanUseExistingInstance(context))
                    {
                        Monitor.Exit(_sagas);
                        needToLeaveSagas = false;
                        lock (instance)
                        {
                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Using Existing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (policy.CanRemoveInstance(instance))
                                    {
                                        _sagas.Remove(instance);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Existing Saga Instance Exception", typeof(TSaga), typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }

                                    throw sex;
                                }
                            });
                        }
                    }
                    else
                    {
                        if (_log.IsDebugEnabled)
                        {
                            _log.DebugFormat("SAGA: {0} Ignoring Existing {1} for {2}", typeof(TSaga).ToFriendlyName(), sagaId,
                                             typeof(TMessage).ToFriendlyName());
                        }
                    }
                }
            }
            finally
            {
                if (needToLeaveSagas)
                {
                    Monitor.Exit(_sagas);
                }
            }
        }
Esempio n. 20
0
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(
     IConsumeContext <TMessage> context, InstanceHandlerSelector <TConsumer, TMessage> selector)
     where TMessage : class
 {
     return(_delegate.GetConsumer(context, selector));
 }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId,
                                                                                      InstanceHandlerSelector <TSaga, TMessage> selector,
                                                                                      ISagaPolicy <TSaga, TMessage> policy)
            where TMessage : class
        {
            return(_repository.GetSaga(context, sagaId, (saga, message) =>
            {
                _callback(saga);

                return selector(saga, message);
            }, policy));
        }
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(IConsumeContext <TMessage> context,
                                                                                   InstanceHandlerSelector <TConsumer, TMessage> selector)
     where TMessage : class
 {
     yield return(x =>
     {
         _interceptor(() =>
         {
             foreach (var consumer in _consumerFactory.GetConsumer(context, selector))
             {
                 consumer(x);
             }
         });
     });
 }
Esempio n. 23
0
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId,
                                                                               InstanceHandlerSelector <TSaga, TMessage> selector, ISagaPolicy <TSaga, TMessage> policy) where TMessage : class
 {
     using (CreateContainerScope(context))
     {
         foreach (var handler in _repository.GetSaga(context, sagaId, selector, policy))
         {
             yield return(handler);
         }
     }
 }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(IConsumeContext <TMessage> context,
                                                                                          InstanceHandlerSelector
                                                                                          <RequestConsumer, TMessage> selector)
            where TMessage : class
        {
            var consumer = new RequestConsumer(_bus);

            IEnumerable <Action <IConsumeContext <TMessage> > > result = selector(consumer, context);

            return(result);
        }
Esempio n. 25
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context,
                                                                                      Guid sagaId,
                                                                                      InstanceHandlerSelector <TSaga, TMessage>
                                                                                      selector,
                                                                                      ISagaPolicy <TSaga, TMessage> policy)
            where TMessage : class
        {
            using (ISession session = _sessionFactory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    var instance = session.Get <TSaga>(sagaId, LockMode.Upgrade);
                    if (instance == null)
                    {
                        if (policy.CanCreateInstance(context))
                        {
                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Creating New {1} for {2}",
                                                     typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    instance = policy.CreateInstance(x, sagaId);

                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (!policy.CanRemoveInstance(instance))
                                    {
                                        session.Save(instance);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Create Saga Instance Exception", typeof(TSaga),
                                                                typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }

                                    if (transaction.IsActive)
                                    {
                                        transaction.Rollback();
                                    }

                                    throw sex;
                                }
                            });
                        }
                        else
                        {
                            if (_log.IsDebugEnabled)
                            {
                                _log.DebugFormat("SAGA: {0} Ignoring Missing {1} for {2}", typeof(TSaga).ToFriendlyName(),
                                                 sagaId,
                                                 typeof(TMessage).ToFriendlyName());
                            }
                        }
                    }
                    else
                    {
                        if (policy.CanUseExistingInstance(context))
                        {
                            yield return(x =>
                            {
                                if (_log.IsDebugEnabled)
                                {
                                    _log.DebugFormat("SAGA: {0} Using Existing {1} for {2}",
                                                     typeof(TSaga).ToFriendlyName(), sagaId,
                                                     typeof(TMessage).ToFriendlyName());
                                }

                                try
                                {
                                    foreach (var callback in selector(instance, x))
                                    {
                                        callback(x);
                                    }

                                    if (policy.CanRemoveInstance(instance))
                                    {
                                        session.Delete(instance);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var sex = new SagaException("Existing Saga Instance Exception", typeof(TSaga),
                                                                typeof(TMessage), sagaId, ex);
                                    if (_log.IsErrorEnabled)
                                    {
                                        _log.Error(sex);
                                    }

                                    if (transaction.IsActive)
                                    {
                                        transaction.Rollback();
                                    }

                                    throw sex;
                                }
                            });
                        }
                        else
                        {
                            if (_log.IsDebugEnabled)
                            {
                                _log.DebugFormat("SAGA: {0} Ignoring Existing {1} for {2}", typeof(TSaga).ToFriendlyName(),
                                                 sagaId,
                                                 typeof(TMessage).ToFriendlyName());
                            }
                        }
                    }

                    if (transaction.IsActive)
                    {
                        transaction.Commit();
                    }
                }
        }
Esempio n. 26
0
        IEnumerable <Action <IConsumeContext <TMessage> > > IConsumerFactory <TConsumer> .GetConsumer <TMessage>(IConsumeContext <TMessage> context,
                                                                                                                 InstanceHandlerSelector <TConsumer, TMessage> selector)
        {
            using (ICodeSwitchContainerScope innerScope = CreateContainerScope(context))
            {
                TConsumer consumer;
                if (!innerScope.TryResolve(out consumer))
                {
                    throw new ConfigurationException(string.Format("The consumer type {0} could not be resolved from the container.",
                                                                   typeof(TConsumer).ToShortTypeName()));
                }

                foreach (var handler in selector(consumer, context))
                {
                    yield return(handler);
                }
            }
        }
Esempio n. 27
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(
            IConsumeContext <TMessage> context,
            Guid sagaId,
            InstanceHandlerSelector <TSaga, TMessage> selector,
            ISagaPolicy <TSaga, TMessage> policy) where TMessage : class
        {
            using (var session = this.documentStore.OpenSession())
            {
                session.Advanced.UseOptimisticConcurrency = true;

                var instance = session.Load <TSaga>(sagaId);

                if (instance == null)
                {
                    if (policy.CanCreateInstance(context))
                    {
                        yield return(x =>
                        {
                            try
                            {
                                instance = policy.CreateInstance(x, sagaId);

                                foreach (var callback in selector(instance, x))
                                {
                                    callback(x);
                                }

                                if (policy.CanRemoveInstance(instance))
                                {
                                    return;
                                }

                                session.Store(instance);
                                session.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                var sex = new SagaException(
                                    "Create Saga Instance Exception",
                                    typeof(TSaga),
                                    typeof(TMessage),
                                    sagaId,
                                    ex);

                                throw sex;
                            }
                        });
                    }
                }
                else
                {
                    if (policy.CanUseExistingInstance(context))
                    {
                        yield return(x =>
                        {
                            try
                            {
                                const int NbtriesMax = 5;

                                foreach (var callback in selector(instance, x))
                                {
                                    callback(x);
                                }

                                if (policy.CanRemoveInstance(instance))
                                {
                                    session.Delete(instance);
                                }

                                try
                                {
                                    session.SaveChanges();
                                }
                                catch (ConcurrencyException)
                                {
                                    if (x.RetryCount <= NbtriesMax)
                                    {
                                        x.RetryLater();
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                var sex = new SagaException(
                                    "Existing Saga Instance Exception",
                                    typeof(TSaga),
                                    typeof(TMessage),
                                    sagaId,
                                    ex);

                                throw sex;
                            }
                        });
                    }
                }
            }
        }
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context,
                                                                                      Guid sagaId, InstanceHandlerSelector <TInstance, TMessage> selector, ISagaPolicy <TInstance, TMessage> policy)
            where TMessage : class
        {
            var handlers = _repository.GetSaga(context, sagaId, selector, policy);

            int handlerCount = 0;

            foreach (var handler in handlers)
            {
                handlerCount++;
                yield return(handler);
            }

            int retryLimit;

            if (handlerCount == 0 && IsRetryEvent(context.Message, out retryLimit))
            {
                int attempts = context.RetryCount;
                if (attempts < retryLimit)
                {
                    yield return(msgContext =>
                    {
                        _log.DebugFormat("Queuing {0} {1} for retry {2}", typeof(TMessage).Name, context.MessageId, attempts + 1);
                        msgContext.RetryLater();
                    });
                }
                else
                {
                    _log.DebugFormat("Retry limit for {0} {1} reached {2}", typeof(TMessage).Name, context.MessageId, attempts + 1);
                }
            }
        }
Esempio n. 29
0
        public IEnumerable <Action <IConsumeContext <TMessage> > > GetConsumer <TMessage>(IConsumeContext <TMessage> context,
                                                                                          InstanceHandlerSelector <TConsumer, TMessage> selector)
            where TMessage : class
        {
            foreach (var action in _consumerFactory.GetConsumer(context, selector))
            {
                Action <IConsumeContext <TMessage> > consumer = action;
                yield return(x =>
                {
                    DateTime startTime = DateTime.UtcNow;
                    Stopwatch timer = Stopwatch.StartNew();
                    try
                    {
                        consumer(x);

                        timer.Stop();

                        x.NotifyResourceUsageCompleted(x.Bus.Endpoint.Address.Uri, startTime, timer.Elapsed);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                });
            }
        }
 public IEnumerable <Action <IConsumeContext <TMessage> > > GetSaga <TMessage>(IConsumeContext <TMessage> context, Guid sagaId, InstanceHandlerSelector <TSaga, TMessage> selector, ISagaPolicy <TSaga, TMessage> policy) where TMessage : class
 {
     return(_inner.GetSaga(context, sagaId, (saga, message) =>
     {
         _context.InjectProperties(saga);
         return selector(saga, message);
     }, policy));
 }