Пример #1
0
        public void FactoryCaches()
        {
            DateTimeOffset firstNow  = new DateTimeOffset(2017, 3, 27, 13, 40, 23, TimeSpan.Zero);
            DateTimeOffset secondNow = new DateTimeOffset(2017, 3, 27, 13, 42, 23, TimeSpan.Zero);

            _subDateTimeService.UtcNow
            .Returns(firstNow, secondNow);
            _subMessageHandlerFactory.Create().Returns(c => new HttpClientHandler());

            HttpClientFactory factory = CreateFactory();

            HttpClient firstClient  = factory.GetOrCreateClient();
            HttpClient secondClient = factory.GetOrCreateClient();

            Assert.AreEqual(firstClient, secondClient);
        }
Пример #2
0
        private async Task ProcessAsync(IncomingMessage msg, CancellationToken cToken)
        {
            IMessageHandler handler = null;

            try
            {
                handler = _handlerFactory.Create(msg);
                Logger.Debug("Handler {0} found for request {1}", handler.GetType().Name, msg.GetType().Name);
                var responses = await handler.HandleAsync(msg, cToken);

                if (responses == null)
                {
                    return;
                }

                Logger.Debug("{0} messages to send back", responses.Count);
                foreach (var r in responses)
                {
                    await _nodeMessageChannel.SendAsync(r, cToken);

                    MessageLog.Debug("OUT:{0}", r);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
            finally
            {
                if (handler != null)
                {
                    _handlerFactory.Release(handler);
                }
            }
        }
Пример #3
0
        public void RegisterHandler <TMessage, THandler>(IMessageHandlerFactory <TMessage, THandler> factory) where THandler : IHandler <TMessage> where TMessage : class, IHaveProcessId, IHaveId
        {
            var cfg = new ContainerConfiguration(c => c.Register <THandler>(ctx => factory.Create(ctx.Resolve <IMessageProcessContext>())),
                                                 c => c.RegisterType <MessageHandleActor <TMessage, THandler> >());

            _containerConfigurations.Add(cfg);
            _maps.Add(factory.CreateRouteMap());
        }
Пример #4
0
        private HttpClient Create()
        {
            HttpClientHandler handler = _messageHandlerFactory.Create();

            handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            return(new HttpClient(handler));
        }
        public WebHttpClientFactory(IMessageHandlerFactory messageHandlerFactory)
        {
            _messageHandlerFactory = messageHandlerFactory;

            HttpClientHandler handler = messageHandlerFactory.Create();

            handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            _httpClient = new HttpClient(handler);
        }
 public IEnumerable <IMessageHandler> GetHandlersForType(Type type)
 {
     foreach (Type handlerType in this)
     {
         var handler = _factory.Create(handlerType);
         if (handler.CanHandle(type))
         {
             yield return(handler);
         }
     }
 }
        public void WhenMessageHandlerCreateCalled_ThenFactoryIsInvoked()
        {
            var handler = new HttpClientHandler();

            _subMessageHandlerFactory.Create().Returns(handler);

            HealthVaultSodaConnection healthVaultSodaConnection = CreateHealthVaultSodaConnection();
            IMessageHandlerFactory    factory = healthVaultSodaConnection;
            var handlerResult = factory.Create();

            Assert.AreEqual(handler, handlerResult);
        }
Пример #8
0
        public async void Process(string route, string messageId, string topic, string payload, bool resend,
                                  CancellationToken cancellationToken)
        {
            var sw = Stopwatch.StartNew();

            try
            {
                var type            = _messageTypesCache.Get(topic);
                var message         = JsonConvert.DeserializeObject(payload, type);
                var handlerType     = _messageHandlersCache.Get(topic);
                var handlerInstance = _messageHandlerFactory.Create(handlerType);
                await handlerInstance.Handle(route, messageId, message, resend, cancellationToken);
            }
            catch (Exception e)
            {
                _messagingLogger.Error(e);
            }
            finally
            {
                _messagingLogger.Debug($"{messageId} processed in {sw.ElapsedMilliseconds}");
            }
        }
Пример #9
0
#pragma warning disable SA1204 // Static elements should appear before instance elements
#pragma warning disable SA1202 // Elements should be ordered by access
        /// <summary>
        /// Processes the message by invoking the message handler.
        /// </summary>
        public static async Task <bool> ProcessMessage(
            ILogger <ServiceBusMessageBroker> logger,
            ITracer tracer,
            ISubscriptionMap subscriptions,
            IMessageHandlerFactory handlerFactory,
            ISerializer serializer,
            string messageScope,
            IMediator mediator,
            Microsoft.Azure.ServiceBus.Message serviceBusMessage)
#pragma warning restore SA1204 // Static elements should appear before instance elements
#pragma warning restore SA1202 // Elements should be ordered by access
        {
            var processed   = false;
            var messageName = serviceBusMessage.Label;

            if (subscriptions.Exists(messageName))
            {
                foreach (var subscription in subscriptions.GetAll(messageName))
                {
                    var messageType = subscriptions.GetByName(messageName);
                    if (messageType == null)
                    {
                        continue;
                    }

                    // get parent span infos from message
                    ISpan parentSpan = null;
                    if (serviceBusMessage.UserProperties.ContainsKey("TraceId") && serviceBusMessage.UserProperties.ContainsKey("SpanId"))
                    {
                        // dehydrate parent span
                        parentSpan = new Span(serviceBusMessage.UserProperties["TraceId"] as string, serviceBusMessage.UserProperties["SpanId"] as string);
                    }

                    using (logger.BeginScope(new Dictionary <string, object>
                    {
                        [LogPropertyKeys.CorrelationId] = serviceBusMessage.CorrelationId,
                        //[LogPropertyKeys.TrackId] = scope.Span.SpanId = allready done in Span ScopeManager (activate)
                    }))
                        using (var scope = tracer?.BuildSpan(messageName, LogKeys.AppMessaging, SpanKind.Consumer, parentSpan).Activate(logger))
                        {
                            // map some message properties to the typed message
                            //var jsonMessage = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(serviceBusMessage.Body), messageType); // TODO: use ISerializer here, compacter messages
                            //var message = jsonMessage as Domain.Message;
                            if (!(serializer.Deserialize(serviceBusMessage.Body, messageType) is Domain.Message message))
                            {
                                return(false);
                            }

                            // TODO: message can be null, skip
                            if (message.Origin.IsNullOrEmpty())
                            {
                                //message.CorrelationId = jsonMessage.AsJToken().GetStringPropertyByToken("CorrelationId");
                                message.Origin = serviceBusMessage.UserProperties.ContainsKey("Origin") ? serviceBusMessage.UserProperties["Origin"] as string : string.Empty;
                            }

                            logger.LogJournal(LogKeys.AppMessaging, $"message processed: {serviceBusMessage.Label} (id={{MessageId}}, service={{Service}}, origin={{MessageOrigin}}, size={serviceBusMessage.Body.Length.Bytes().ToString("#.##")})",
                                              LogPropertyKeys.TrackReceiveMessage, args: new[] { message?.Id, messageScope, message.Origin });
                            logger.LogTrace(LogKeys.AppMessaging, message.Id, serviceBusMessage.Label, LogTraceNames.Message);

                            // construct the handler by using the DI container
                            var handler      = handlerFactory.Create(subscription.HandlerType); // should not be null, did you forget to register your generic handler (EntityMessageHandler<T>)
                            var concreteType = typeof(IMessageHandler <>).MakeGenericType(messageType);

                            var method = concreteType.GetMethod("Handle");
                            if (handler != null && method != null)
                            {
                                if (mediator != null)
                                {
                                    await mediator.Publish(new MessageHandledDomainEvent(message, messageScope)).AnyContext();
                                }

                                await((Task)method.Invoke(handler, new object[] { message as object })).AnyContext();
                            }
                            else
                            {
                                logger.LogWarning("{LogKey:l} process failed, message handler could not be created. is the handler registered in the service provider? (name={MessageName}, service={Service}, id={MessageId}, origin={MessageOrigin})",
                                                  LogKeys.AppMessaging, serviceBusMessage.Label, messageScope, message.Id, message.Origin);
                            }
                        }
                }

                processed = true;
            }
            else
            {
                logger.LogDebug($"{{LogKey:l}} unprocessed: {messageName}", LogKeys.AppMessaging);
            }

            return(processed);
        }
 HttpClientHandler IMessageHandlerFactory.Create()
 {
     return(_messageHandlerFactory.Create());
 }