Пример #1
0
        public void Handle(IConsumingContext <T> context)
        {
            this.EnsureMetricCollector(context);

            var message = context.Message;

            if (!this.CanReplyAndExistsCacheConfig(context))
            {
                this.CollectMetrics(message.Label.ToString(), false);
                this.consumer.Handle(context);
                return;
            }

            var cachedValue = this.cacheConfiguration.Cache[message];
            var cached      = cachedValue != null;

            this.CollectMetrics(message.Label.ToString(), cached);

            if (cached)
            {
                context.Reply(cachedValue);
                return;
            }

            var cachingContext = new CachingContext <T>(context, this.cacheConfiguration);

            this.consumer.Handle(cachingContext);
        }
Пример #2
0
        public void Handle(IConsumingContext <TestRequest> context)
        {
            var id = context.Message.Payload.Id;

            var value = this.DataSource.ContainsKey(id) ? this.DataSource[id] : null;

            context.Reply(new TestResponse {
                Value = value
            });
        }
Пример #3
0
        /// <summary>
        /// Handles incoming message.
        /// </summary>
        /// <param name="context">Consuming context.</param>
        public void Handle(IConsumingContext <T> context)
        {
            BusProcessingContext.Current = new BusProcessingContext(((IDeliveryContext)context).Delivery);

            this.@operator
            .Apply(context.Message)
            .ForEach(m => context.Bus.Emit(m.Label, m.Payload, m.Headers));

            context.Accept();
        }
Пример #4
0
        /// <summary>
        /// Инициализирует сагу.
        /// </summary>
        /// <param name="context">Контекст обработки входящего сообщения.</param>
        /// <param name="canInitiate">Если <c>true</c> - тогда при инициализации можно создавать новую сагу.</param>
        /// <returns>Сага соответствующая сообщению, новая сага или <c>null</c>, если сагу получить или создать невозможно.</returns>
        public ISagaContext <TS, TK> InitializeSaga(IConsumingContext <TM> context, bool canInitiate)
        {
            var sagaId = this.SagaIdSeparator.GetId(context.Message);
            var saga   = this.SagaRepository.Get(sagaId);

            if (saga == null)
            {
                if (canInitiate)
                {
                    saga = this.SagaFactory.Create(sagaId);
                }
            }

            return(saga);
        }
Пример #5
0
        /// <inheritdoc />
        public void Handle(IConsumingContext <T> context)
        {
            BusProcessingContext.Current = new BusProcessingContext(((IDeliveryContext)context).Delivery, context.Bus);

            this.@operator
            .Apply(context.Message)
            .ForEach(
                m =>
            {
                var headers = new Dictionary <string, object>(m.Headers);
                Headers.ApplyBreadcrumbs(headers, context.Bus.Endpoint.Address);
                Headers.ApplyOriginalMessageId(headers);
                context.Bus.Emit(m.Label, m.Payload, headers);
            });

            context.Accept();
        }
Пример #6
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                consumer.Handle(context);
            };

            this.consumers[label] = consumingAction;
        }
Пример #7
0
        private void EnsureMetricCollector(IConsumingContext <T> context)
        {
            if (this.metricsCollectorInitialized)
            {
                return;
            }

            lock (this)
            {
                try
                {
                    this.metricsCollector = (context.Bus as AbstractBus)?.Configuration?.MetricsCollector;
                }
                catch (Exception e)
                {
                    Log.Warn(m => m("Could not get metric collector"), e);
                }

                this.metricsCollectorInitialized = true;
            }
        }
Пример #8
0
        /// <summary>
        /// Обрабатывает входящее сообщение.
        /// </summary>
        /// <param name="context">Контекст обработки входящего сообщения.</param>
        public void Handle(IConsumingContext <TM> context)
        {
            var saga = this.SagaLifecycle.InitializeSaga(context, this.CanInitiate);

            if (saga == null)
            {
                this.SagaFailedHandler.SagaNotFoundHandle(context);

                return;
            }

            try
            {
                this.SagaStep.Handle(saga, context);
            }
            catch (Exception exception)
            {
                this.SagaFailedHandler.SagaFailedHandle(saga, context, exception);
                throw;
            }

            this.SagaLifecycle.FinilizeSaga(saga);
        }
Пример #9
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                this.logger.Trace(
                    m => m($"{typeof(T)}: получил сообщение " +
                           $"[{JsonConvert.SerializeObject(context.Message.Payload)}] на обработку"));

                consumer.Handle(context);
            };

            this.consumers[label] = consumingAction;
        }
Пример #10
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                var sw = Stopwatch.StartNew();

                consumer.Handle(context);

                this.MetricsCollector?.Histogram("contour.rmq.consuming.duration", sw.ElapsedMilliseconds, 1D, new[] { "endpoint:" + this.busContext.Endpoint.Address, "label:" + label.ToString() });
            };

            this.consumers[label] = consumingAction;
        }
Пример #11
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <ExpandoObject> context)
 {
     _logger.InfoFormat("Received [{0}].", context.Message.Label);
 }
Пример #12
0
 /// <summary>
 /// ќбрабатывает управл¤ющие сообщени¤ с целью корректировки правил маршрутизации.
 /// </summary>
 /// <param name="context"> онтекст полученного сообщени¤.</param>
 public void Handle(IConsumingContext <T> context)
 {
     this.createRoute(context.Message, this.storage);
     context.Accept();
 }
Пример #13
0
 /// <summary>
 /// Обрабатывает исключения возникшие при выполнении шага саги.
 /// </summary>
 /// <param name="sagaContext">Данные саги.</param>
 /// <param name="context">Контекст полученного сообщения.</param>
 /// <param name="exception">Обрабатываемое исключение.</param>
 public void SagaFailedHandle(ISagaContext <TS, TK> sagaContext, IConsumingContext <TM> context, Exception exception)
 {
     this.failedAction(sagaContext, context, exception);
 }
Пример #14
0
 /// <summary>
 /// Обрабатывает ситуацию, когда сага не найдена.
 /// </summary>
 /// <param name="context">Контекст обработки сообщения, в котором возникла эта ситуация.</param>
 public void SagaNotFoundHandle(IConsumingContext <TM> context)
 {
     this.notFoundAction(context);
 }
Пример #15
0
 /// <summary>
 /// Override to implement message consuming
 /// </summary>
 public abstract Task Consume(IConsumingContext consumingContext);
Пример #16
0
        /// <inheritdoc />
        public override async Task Consume(IConsumingContext consumingContext)
        {
            _lastMsgTime = DateTime.Now;

            var consumedMessage = consumingContext.GetMessage <TMsgPayload>();

            var logger = consumingContext.GetLogger <MqBatchConsumer <TMsgPayload, TLogic> >();

            _lastLogger           = logger;
            _lastLogic            = _singletonLogic ?? consumingContext.CreateLogic <TLogic>();
            _lastConsumingContext = consumingContext;

            logger.Debug("Input mq message")
            .AndFactIs("queue", Queue)
            .AndFactIs("msg-id", consumedMessage.MessageId)
            .AndLabel("batch-consumer")
            .Write();

            _messages.Add(consumedMessage);

            if (_messages.Count >= BatchSize)
            {
                logger.Debug("Perform consuming")
                .AndFactIs("queue", Queue)
                .AndFactIs("msg-count", _messages.Count)
                .AndLabel("sync-mq-batch-processing")
                .Write();

                await PerformConsumingAsync();
            }

            if (_monitorTask != null)
            {
                ExceptionDto exDto = null;

                if (_monitorTask.Exception != null)
                {
                    exDto = ExceptionDto.Create(_monitorTask.Exception);
                }

                logger.Debug("Monitor task state")
                .AndFactIs("Status", _monitorTask.Status)
                .AndFactIs("IsCompleted", _monitorTask.IsCompleted)
                .AndFactIs("IsCompletedSuccessfully", _monitorTask.IsCompletedSuccessfully)
                .AndFactIs("IsFaulted", _monitorTask.IsFaulted)
                .AndFactIs("IsCanceled", _monitorTask.IsCanceled)
                .AndFactIs("Exception", exDto ?? (object)"no-exception")
                .Write();
            }

            _monitorTask ??= Task.Run(Async);

            //try
            //{
            //    logger.Debug("Monitor task state")
            //        .AndFactIs("task", _monitorTask)
            //        .Write();
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine(e);
            //    throw;
            //}
        }
Пример #17
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <T> context)
 {
     this._handlerResolver().
     Handle(context);
 }
Пример #18
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <T> context)
 {
     this._handlerAction(context);
 }
Пример #19
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <BooMessage> context)
 {
     WaitEvent.Signal();
 }
Пример #20
0
 /// <summary>
 /// Выполняет шаг саги.
 /// </summary>
 /// <param name="sagaContext">Контекст саги доступный на данном шаге выполнения.</param>
 /// <param name="consumingContext">Контекст обработки входящего сообщения.</param>
 public void Handle(ISagaContext <TS, TK> sagaContext, IConsumingContext <TM> consumingContext)
 {
     this.action(sagaContext, consumingContext);
 }
Пример #21
0
 public CachingContext(IConsumingContext <T> context, CacheConfiguration cacheConfiguration)
 {
     this.context            = context;
     this.cacheConfiguration = cacheConfiguration;
 }
Пример #22
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <T> context)
 {
     this._handler.Value.Handle(context);
 }
Пример #23
0
 /// <summary>
 /// The handle.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 public void Handle(IConsumingContext <T> context)
 {
     this._received.Set();
 }
Пример #24
0
 private bool CanReplyAndExistsCacheConfig(IConsumingContext <T> context)
 {
     return(context.CanReply && (this.cacheConfiguration?.Enabled ?? false) && this.cacheConfiguration?.Cache != null && this.cacheConfiguration?.Ttl != null);
 }