Exemplo n.º 1
0
        private string GetMessageInContext(Message message)
        {
            var serializedMessage = _serialisationRegister.GeTypeSerialiser(message.GetType()).Serialiser.Serialise(message);
            var context           = new { Subject = message.GetType().Name, Message = serializedMessage };

            return(JsonConvert.SerializeObject(context));
        }
Exemplo n.º 2
0
        private async Task <bool> CallMessageHandlers(Message message)
        {
            var handlerFuncs = _handlerMap.Get(message.GetType());

            if ((handlerFuncs == null) || (handlerFuncs.Count == 0))
            {
                return(true);
            }

            bool allHandlersSucceeded;
            var  watch = System.Diagnostics.Stopwatch.StartNew();

            if (handlerFuncs.Count == 1)
            {
                // a shortcut for the usual case
                allHandlersSucceeded = await handlerFuncs[0](message);
            }
            else
            {
                var handlerTasks   = handlerFuncs.Select(func => func(message));
                var handlerResults = await Task.WhenAll(handlerTasks);

                allHandlersSucceeded = handlerResults.All(x => x);
            }

            watch.Stop();
            Log.Trace("Handled message - MessageType: {0}", message.GetType().Name);
            _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);

            return(allHandlersSucceeded);
        }
Exemplo n.º 3
0
        private bool CallMessageHandlers(Message message)
        {
            var handlerFuncs = _handlerMap.Get(message.GetType());

            if (handlerFuncs == null)
            {
                return(true);
            }

            var allHandlersSucceeded = true;

            foreach (var handlerFunc in handlerFuncs)
            {
                var watch = new System.Diagnostics.Stopwatch();
                watch.Start();

                var thisHandlerSucceeded = handlerFunc(message);
                allHandlersSucceeded = allHandlersSucceeded && thisHandlerSucceeded;

                watch.Stop();
                Log.Trace("Handled message - MessageType: {0}", message.GetType().Name);
                _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);
            }

            return(allHandlersSucceeded);
        }
Exemplo n.º 4
0
        private async Task <bool> CallMessageHandler(string queueName, Message message, CancellationToken cancellationToken)
        {
            var messageType = message.GetType();

            var middleware = _middlewareMap.Get(queueName, messageType);

            if (middleware == null)
            {
                _logger.LogError(
                    "Failed to dispatch. Middleware for message of type '{MessageTypeName}' not found in middleware map.",
                    message.GetType().FullName);
                return(false);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            using (_messagingMonitor.MeasureDispatch())
            {
                bool dispatchSuccessful = false;
                try
                {
                    var context = new HandleMessageContext(message, messageType, queueName);
                    dispatchSuccessful = await middleware.RunAsync(context, null, cancellationToken)
                                         .ConfigureAwait(false);
                }
                finally
                {
                    watch.Stop();

                    var logMessage =
                        "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms.";
                    if (dispatchSuccessful)
                    {
                        _logger.LogInformation(logMessage,
                                               "Succeeded",
                                               message.Id,
                                               messageType,
                                               watch.ElapsedMilliseconds);
                    }
                    else
                    {
                        _logger.LogWarning(logMessage,
                                           "Failed",
                                           message.Id,
                                           messageType,
                                           watch.ElapsedMilliseconds);
                    }
                }

                return(dispatchSuccessful);
            }
        }
Exemplo n.º 5
0
        public void Publish(Message message)
        {
            var messageToSend = _serialisationRegister.GeTypeSerialiser(message.GetType()).Serialiser.Serialise(message);
            var messageType   = message.GetType().Name;

            Client.Publish(new PublishRequest
            {
                Subject  = messageType,
                Message  = messageToSend,
                TopicArn = Arn
            });

            EventLog.Info("Published message: '{0}' with content {1}", messageType, messageToSend);
        }
        private async Task <bool> CallMessageHandler(string queueName, Message message)
        {
            var messageType = message.GetType();

            var handler = _handlerMap.Get(queueName, messageType);

            if (handler == null)
            {
                _logger.LogError(
                    "Failed to dispatch. Handler for message of type '{MessageTypeName}' not found in handler map.",
                    message.GetType().FullName);
                return(false);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            using (_messagingMonitor.MeasureHandler())
            {
                bool handlerSucceeded = false;
                try
                {
                    handlerSucceeded = await handler(message).ConfigureAwait(false);
                }
                finally
                {
                    watch.Stop();

                    var logMessage =
                        "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms.";
                    if (handlerSucceeded)
                    {
                        _logger.LogInformation(logMessage,
                                               "Succeeded",
                                               message.Id,
                                               messageType,
                                               watch.ElapsedMilliseconds);
                    }
                    else
                    {
                        _logger.LogWarning(logMessage,
                                           "Failed",
                                           message.Id,
                                           messageType,
                                           watch.ElapsedMilliseconds);
                    }
                }

                return(handlerSucceeded);
            }
        }
Exemplo n.º 7
0
        public void Publish(Message message)
        {
            var messageToSend = _serialisationRegister.GeTypeSerialiser(message.GetType()).Serialiser.Serialise(message);
            var messageType = message.GetType().ToKey();

            Client.Publish(new PublishRequest
                               {
                                   Subject = messageType,
                                   Message = messageToSend,
                                   TopicArn = Arn
                               });

            EventLog.Info("Published message: '{0}' with content {1}", messageType, messageToSend);
        }
Exemplo n.º 8
0
        private static string GetMessageInContext(Message message)
        {
            // ToDo: No no mr JsonConvert.
            var context = new { Subject = message.GetType().Name, Message = message };

            return(JsonConvert.SerializeObject(context));
        }
        private PublishRequest BuildPublishRequest(Message message)
        {
            var messageToSend = _serialisationRegister.Serialise(message, serializeForSnsPublishing: true);
            var messageType   = _messageSubjectProvider.GetSubjectForType(message.GetType());

            var messageAttributeValues = message.MessageAttributes?.ToDictionary(
                source => source.Key,
                source =>
            {
                if (source.Value == null)
                {
                    return(null);
                }

                return(new MessageAttributeValue
                {
                    StringValue = source.Value.StringValue,
                    BinaryValue = source.Value.BinaryValue != null ? new MemoryStream(source.Value.BinaryValue, false) : null,
                    DataType = source.Value.DataType
                });
            });

            return(new PublishRequest
            {
                TopicArn = Arn,
                Subject = messageType,
                Message = messageToSend,
                MessageAttributes = messageAttributeValues
            });
        }
Exemplo n.º 10
0
        private async Task <bool> CallMessageHandler(Message message)
        {
            var messageType = message.GetType();

            var handler = _handlerMap.Get(messageType);

            if (handler == null)
            {
                return(true);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            var handlerSucceeded = await handler(message).ConfigureAwait(false);

            watch.Stop();

            _logger.LogTrace(
                "Handled message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}.",
                message.Id,
                messageType,
                watch.Elapsed);

            _messagingMonitor.HandleTime(watch.Elapsed);

            return(handlerSucceeded);
        }
Exemplo n.º 11
0
        private async Task <bool> CallMessageHandler(Message message)
        {
            var handler = _handlerMap.Get(message.GetType());

            if (handler == null)
            {
                return(true);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            var handlerSucceeded = await handler(message).ConfigureAwait(false);

            watch.Stop();
            _log.LogTrace($"Handled message - MessageType: {message.GetType().Name}");
            _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);

            return(handlerSucceeded);
        }
Exemplo n.º 12
0
        private PublishRequest BuildPublishRequest(Message message)
        {
            var messageToSend = _serialisationRegister.Serialise(message, serializeForSnsPublishing: true);
            var messageType   = message.GetType().Name;

            return(new PublishRequest
            {
                TopicArn = Arn,
                Subject = messageType,
                Message = messageToSend
            });
        }
Exemplo n.º 13
0
        private PublishRequest BuildPublishRequest(Message message, PublishMetadata metadata)
        {
            var messageToSend = _serializationRegister.Serialize(message, serializeForSnsPublishing: true);
            var messageType   = _messageSubjectProvider.GetSubjectForType(message.GetType());

            return(new PublishRequest
            {
                TopicArn = Arn,
                Subject = messageType,
                Message = messageToSend,
                MessageAttributes = BuildMessageAttributes(metadata)
            });
        }
Exemplo n.º 14
0
        public void Publish(Message message)
        {
            var messageToSend = _serialisationRegister.Serialise(message, serializeForSnsPublishing:true);
            var messageType = message.GetType().Name;

            Client.Publish(new PublishRequest
                {
                    Subject = messageType,
                    Message = messageToSend,
                    TopicArn = Arn
                });

            EventLog.Info("Published message: '{0}' with content {1}", messageType, messageToSend);
        }
Exemplo n.º 15
0
        public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken)
        {
            if (QueueUrl is null)
            {
                throw new PublishException("Queue URL was null, perhaps you need to call `StartAsync` on the `IMessagePublisher` before publishing.");
            }

            var request = BuildSendMessageRequest(message, metadata);
            SendMessageResponse response;

            try
            {
                response = await _client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false);
            }
            catch (AmazonServiceException ex)
            {
                throw new PublishException(
                          $"Failed to publish message to SQS. {nameof(request.QueueUrl)}: {request.QueueUrl},{nameof(request.MessageBody)}: {request.MessageBody}",
                          ex);
            }

            using (_logger.BeginScope(new Dictionary <string, object>
            {
                ["AwsRequestId"] = response?.MessageId
            }))
            {
                _logger.LogInformation(
                    "Published message {MessageId} of type {MessageType} to {DestinationType} '{MessageDestination}'.",
                    message.Id,
                    message.GetType().FullName,
                    "Queue",
                    request.QueueUrl);
            }

            if (MessageResponseLogger != null)
            {
                var responseData = new MessageResponse
                {
                    HttpStatusCode   = response?.HttpStatusCode,
                    MessageId        = response?.MessageId,
                    ResponseMetadata = response?.ResponseMetadata
                };
                MessageResponseLogger.Invoke(responseData, message);
            }
        }
Exemplo n.º 16
0
        public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken)
        {
            var             request  = BuildPublishRequest(message, metadata);
            PublishResponse response = null;

            try
            {
                response = await Client.PublishAsync(request, cancellationToken).ConfigureAwait(false);
            }
            catch (AmazonServiceException ex)
            {
                if (!ClientExceptionHandler(ex, message))
                {
                    throw new PublishException(
                              $"Failed to publish message to SNS. Topic ARN: '{request.TopicArn}', Subject: '{request.Subject}', Message: '{request.Message}'.",
                              ex);
                }
            }

            using (_logger.BeginScope(new[]
            {
                new KeyValuePair <string, object>("AwsRequestId", response?.MessageId)
            }))
            {
                _logger.LogInformation(
                    "Published message {MessageId} of type {MessageType} to {DestinationType} '{MessageDestination}'.",
                    message.Id,
                    message.GetType().Name,
                    "Topic",
                    request.TopicArn);
            }

            if (MessageResponseLogger != null)
            {
                var responseData = new MessageResponse
                {
                    HttpStatusCode   = response?.HttpStatusCode,
                    MessageId        = response?.MessageId,
                    ResponseMetadata = response?.ResponseMetadata
                };
                MessageResponseLogger.Invoke(responseData, message);
            }
        }
Exemplo n.º 17
0
        public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken)
        {
            var request = BuildSendMessageRequest(message, metadata);
            SendMessageResponse response;

            try
            {
                response = await _client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false);
            }
            catch (AmazonServiceException ex)
            {
                throw new PublishException(
                          $"Failed to publish message to SQS. {nameof(request.QueueUrl)}: {request.QueueUrl},{nameof(request.MessageBody)}: {request.MessageBody}",
                          ex);
            }

            using (Logger.BeginScope(new[]
            {
                new KeyValuePair <string, object>("AwsRequestId", response?.MessageId)
            }))
            {
                Logger.LogInformation(
                    "Published message {MessageId} of type {MessageType} to {DestinationType} '{MessageDestination}'.",
                    message.Id,
                    message.GetType().Name,
                    "Queue",
                    request.QueueUrl);
            }

            if (MessageResponseLogger != null)
            {
                var responseData = new MessageResponse
                {
                    HttpStatusCode   = response?.HttpStatusCode,
                    MessageId        = response?.MessageId,
                    ResponseMetadata = response?.ResponseMetadata
                };
                MessageResponseLogger.Invoke(responseData, message);
            }
        }
Exemplo n.º 18
0
        public async Task PublishAsync(Message message)
        {
            var messageToSend = _serialisationRegister.Serialise(message, serializeForSnsPublishing: true);
            var messageType   = message.GetType().Name;
            var request       = new PublishRequest
            {
                TopicArn = Arn,
                Subject  = messageType,
                Message  = messageToSend
            };

            try
            {
                await Client.PublishAsync(request);

                _eventLog.LogInformation($"Published message: '{messageType}' with content {messageToSend}");
            }
            catch (Exception ex)
            {
                throw new PublishException(
                          $"Failed to publish message to SNS. TopicArn: {request.TopicArn} Subject: {request.Subject} Message: {request.Message}",
                          ex);
            }
        }
Exemplo n.º 19
0
        public void ProcessMessageAction(Amazon.SQS.Model.Message message)
        {
            Message typedMessage = null;
            string  rawMessage   = null;

            try
            {
                typedMessage = _serialisationRegister.DeserializeMessage(message.Body);

                var handlingSucceeded = true;

                if (typedMessage != null)
                {
                    List <Func <Message, bool> > handlers;
                    if (!_handlers.TryGetValue(typedMessage.GetType(), out handlers))
                    {
                        return;
                    }

                    foreach (var handle in handlers)
                    {
                        var watch = new System.Diagnostics.Stopwatch();
                        watch.Start();

                        handlingSucceeded = handle(typedMessage);

                        watch.Stop();
                        Log.Trace("Handled message - MessageType: {0}", typedMessage.GetType().Name);
                        _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);
                    }
                }

                if (handlingSucceeded)
                {
                    _queue.Client.DeleteMessage(new DeleteMessageRequest {
                        QueueUrl = _queue.Url, ReceiptHandle = message.ReceiptHandle
                    });
                }
            }
            catch (KeyNotFoundException ex)
            {
                Log.Trace(
                    "Didn't handle message [{0}]. No serialiser setup",
                    rawMessage ?? "");
                _queue.Client.DeleteMessage(new DeleteMessageRequest
                {
                    QueueUrl      = _queue.Url,
                    ReceiptHandle = message.ReceiptHandle
                });
                _onError(ex, message);
            }
            catch (Exception ex)
            {
                var msg = string.Format(
                    "Issue handling message... {0}. StackTrace: {1}",
                    message,
                    ex.StackTrace);
                Log.Error(ex, msg);
                if (typedMessage != null)
                {
                    _messagingMonitor.HandleException(typedMessage.GetType().Name);
                }
                _onError(ex, message);
            }
        }
Exemplo n.º 20
0
        private bool CallMessageHandlers(Message message)
        {
            var handlerFuncs = _handlerMap.Get(message.GetType());

            if (handlerFuncs == null)
            {
                return true;
            }

            var allHandlersSucceeded = true;
            foreach (var handlerFunc in handlerFuncs)
            {
                var watch = new System.Diagnostics.Stopwatch();
                watch.Start();

                var thisHandlerSucceeded = handlerFunc(message);
                allHandlersSucceeded = allHandlersSucceeded && thisHandlerSucceeded;

                watch.Stop();
                Log.Trace("Handled message - MessageType: {0}", message.GetType().Name);
                _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);
            }

            return allHandlersSucceeded;
        }
Exemplo n.º 21
0
        private async Task<bool> CallMessageHandlers(Message message)
        {
            var handlerFuncs = _handlerMap.Get(message.GetType());

            if ((handlerFuncs == null) || (handlerFuncs.Count == 0))
            {
                return true;
            }

            bool allHandlersSucceeded;
            var watch = System.Diagnostics.Stopwatch.StartNew();

            if (handlerFuncs.Count == 1)
            {
                // a shortcut for the usual case
                allHandlersSucceeded = await handlerFuncs[0](message).ConfigureAwait(false);
            }
            else
            {
                var handlerTasks = handlerFuncs.Select(func => func(message));
                var handlerResults = await Task.WhenAll(handlerTasks).ConfigureAwait(false);
                allHandlersSucceeded = handlerResults.All(x => x);
            }

            watch.Stop();
            Log.Trace("Handled message - MessageType: {0}", message.GetType().Name);
            _messagingMonitor.HandleTime(watch.ElapsedMilliseconds);

            return allHandlersSucceeded;
        }
Exemplo n.º 22
0
 private string GetMessageInContext(Message message)
 {
     var serializedMessage = _serialisationRegister.GeTypeSerialiser(message.GetType()).Serialiser.Serialise(message);
     var context = new { Subject = message.GetType().ToKey(), Message = serializedMessage };
     return JsonConvert.SerializeObject(context);
 }