public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (returnInfo == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(transportMessage.CorrelationId))
            {
                return;
            }

            if (transportMessage.Headers.ContainsKey(Headers.HttpTo) ||
                transportMessage.Headers.ContainsKey(Headers.DestinationSites))
            {
                return;
            }

            transportMessage.Headers[Headers.HttpTo] = returnInfo.HttpFrom;
            transportMessage.Headers[Headers.OriginatingSite] = returnInfo.OriginatingSite;

            if (!transportMessage.Headers.ContainsKey(Headers.RouteTo))
            {
                transportMessage.Headers[Headers.RouteTo] = returnInfo.ReplyToAddress.ToString();
            }

            // send to be backwards compatible with Gateway 3.X
            transportMessage.Headers[GatewayHeaders.LegacyMode] = returnInfo.LegacyMode.ToString();
        }
        void SendFailureMessage(TransportMessage message, Exception e, string reason)
        {
            if (errorQueue == null)
            {
                Logger.Error("Message processing always fails for message with ID " + message.Id + ".", e);
                return;
            }

            SetExceptionHeaders(message, e, reason);
            try
            {
                var sender = Configure.Instance.Builder.Build<ISendMessages>();

                sender.Send(message, errorQueue);
            }
            catch (Exception exception)
            {
                var qnfEx = exception as QueueNotFoundException;
                string errorMessage;

                if (qnfEx != null)
                {
                    errorMessage = string.Format("Could not forward failed message to error queue '{0}' as it could not be found.", qnfEx.Queue);
                    Logger.Fatal(errorMessage);
                }
                else
                {
                    errorMessage = "Could not forward failed message to error queue.";
                    Logger.Fatal(errorMessage, exception);
                }

                throw new InvalidOperationException(errorMessage, exception);
            }
        }
        public void Handle(TransportMessage message)
        {
            var sagaId = Guid.Empty;

            if (message.Headers.ContainsKey(Headers.SagaId))
                sagaId = Guid.Parse(message.Headers[Headers.SagaId]);

            if (message.Headers.ContainsKey(Headers.ClearTimeouts))
            {
                if(sagaId == Guid.Empty)
                    throw new InvalidOperationException("Invalid saga id specified, clear timeouts is only supported for saga instances");

                Persister.ClearTimeoutsFor(sagaId);
                Manager.ClearTimeout(sagaId);
            }
            else
            {
                if (!message.Headers.ContainsKey(Headers.Expire))
                    throw new InvalidOperationException("Non timeout message arrived at the timeout manager, id:" + message.Id);

                var data = new TimeoutData
                               {
                                   Destination = message.ReplyToAddress,
                                   SagaId = sagaId,
                                   State = message.Body,
                                   Time = message.Headers[Headers.Expire].ToUtcDateTime(),
                                   CorrelationId = message.CorrelationId,
                                   Headers = message.Headers
                               };

                Persister.Add(data);
                Manager.PushTimeout(data);
            }
        }
Beispiel #4
0
        TransportMessage MapToTransportMessage(TimeoutData timeoutData)
        {
            var transportMessage = new TransportMessage
                                       {
                                           ReplyToAddress = Address.Local,
                                           Headers = new Dictionary<string, string>(),
                                           Recoverable = true,
                                           MessageIntent = MessageIntentEnum.Send,
                                           CorrelationId = timeoutData.CorrelationId,
                                           Body = timeoutData.State
                                       };

            if (timeoutData.Headers != null)
            {
                transportMessage.Headers = timeoutData.Headers;
            }
            else
            {
                //we do this to be backwards compatible, this can be removed when going to 3.1.X
                transportMessage.Headers[Headers.Expire] = timeoutData.Time.ToWireFormattedString();

                if (timeoutData.SagaId != Guid.Empty)
                    transportMessage.Headers[Headers.SagaId] = timeoutData.SagaId.ToString();

            }

            return transportMessage;
        }
        string GetRemoteAddress(TransportMessage msg)
        {
            if (msg.Headers.ContainsKey(Headers.HttpTo))
                return msg.Headers[Headers.HttpTo];

            return remoteUrl;
        }
        public static TransportMessage ToTransportMessage(BasicDeliverEventArgs message)
        {
            var properties = message.BasicProperties;

            if (!properties.IsMessageIdPresent() || string.IsNullOrWhiteSpace(properties.MessageId))
            {
                throw new InvalidOperationException("A non empty message_id property is required when running NServiceBus on top of RabbitMq. If this is a interop message please make sure to set the message_id property before publishing the message");
            }

            var headers = DeserializeHeaders(message);

            var result = new TransportMessage(properties.MessageId, headers)
            {
                Body = message.Body,
            };

            if (properties.IsReplyToPresent())
            {
                result.ReplyToAddress = Address.Parse(properties.ReplyTo);
            }

            if (properties.IsCorrelationIdPresent())
            {
                result.CorrelationId = properties.CorrelationId;
            }

            //When doing native interop we only require the type to be set the "fullName" of the message
            if (!result.Headers.ContainsKey(Headers.EnclosedMessageTypes) && properties.IsTypePresent())
            {
                result.Headers[Headers.EnclosedMessageTypes] = properties.Type;
            }

            return result;
        }
        protected void SendMessageToGatewayQueue(IMessage messageToSend)
        {
            transportMessage = null;
            messageReceived = new ManualResetEvent(false);

            bus.Send("gateway", messageToSend);
        }
		public static TransportMessage ToTransportMessage(this SqsTransportMessage sqsTransportMessage, IAmazonS3 amazonS3, SqsConnectionConfiguration connectionConfiguration)
        {
            var messageId = sqsTransportMessage.Headers[Headers.MessageId];

			var result = new TransportMessage(messageId, sqsTransportMessage.Headers);

            if (!string.IsNullOrEmpty(sqsTransportMessage.S3BodyKey))
            {
                var s3GetResponse = amazonS3.GetObject(connectionConfiguration.S3BucketForLargeMessages, sqsTransportMessage.S3BodyKey);
                result.Body = new byte[s3GetResponse.ResponseStream.Length];
                using (BufferedStream bufferedStream = new BufferedStream(s3GetResponse.ResponseStream))
                {
                    int count;
                    int transferred = 0;
                    while ((count = bufferedStream.Read(result.Body, transferred, 8192)) > 0)
                    {
                        transferred += count;
                    }
                }
            }
            else
			{
				result.Body = Convert.FromBase64String(sqsTransportMessage.Body);
			}

            result.TimeToBeReceived = sqsTransportMessage.TimeToBeReceived;

			if (sqsTransportMessage.ReplyToAddress != null)
			{
				result.Headers[Headers.ReplyToAddress] = sqsTransportMessage.ReplyToAddress.ToString();
			}

            return result;
        }
Beispiel #9
0
        /// <summary>
        ///     Converts a TransportMessage to an Msmq message.
        ///     Doesn't set the ResponseQueue of the result.
        /// </summary>
        public static Message Convert(TransportMessage message)
        {
            var result = new Message();

            if (message.Body != null)
            {
                result.BodyStream = new MemoryStream(message.Body);
            }

            AssignMsmqNativeCorrelationId(message, result);

            result.Recoverable = message.Recoverable;

            if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            {
                result.TimeToBeReceived = message.TimeToBeReceived;
            }

            using (var stream = new MemoryStream())
            {
                headerSerializer.Serialize(stream, message.Headers.Select(pair => new HeaderInfo
                {
                    Key = pair.Key,
                    Value = pair.Value
                }).ToList());
                result.Extension = stream.ToArray();
            }

            result.AppSpecific = (int) message.MessageIntent;

            return result;
        }
        public bool Handle(TransportMessage message)
        {
            var destinationSites = GetDestinationSitesFor(message);

            //if there is more than 1 destination we break it up into multiple messages
            if (destinationSites.Count() > 1)
            {
                foreach (var destinationSite in destinationSites)
                {
                    CloneAndSendLocal(message, destinationSite);
                }

                return true;
            }

            var destination = destinationSites.FirstOrDefault();

            if (destination == null)
            {
                throw new InvalidOperationException("No destination found for message");
            }

            SendToSite(message, destination);

            return true;
        }
 void IMutateOutgoingTransportMessages.MutateOutgoing(IMessage[] messages, TransportMessage transportMessage)
 {
     if (messageHeaders != null)
         if (messageHeaders.ContainsKey(messages[0]))
             foreach (var key in messageHeaders[messages[0]].Keys)
                 transportMessage.Headers.Add(key, messageHeaders[messages[0]][key]);
 }
 public bool Handle(TransportMessage errorMessage)
 {
     transport.PipelineFactory
           .GetPipeline(errorPipelineName)
           .Push(errorMessage.AsEndpointMessage(serializer, endpointWhereErrorOccured));
     return true;
 }
        public void When_a_message_is_received_the_Handle_method_should_called_on_the_satellite()
        {
            var tm = new TransportMessage();
            FakeReceiver.FakeMessageReceived(tm);

            Assert.That(_sat.IsMessageHandled, Is.True);
        }
        Dictionary<string,string> MapToHeaders(TransportMessage from)
        {
            var to = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

            to[NServiceBus + Id] = from.Id;
            to[NServiceBus + CorrelationId] = GetCorrelationForBackwardsCompatibility(from);
            to[NServiceBus + Recoverable] = from.Recoverable.ToString();
            to[NServiceBus + TimeToBeReceived] = from.TimeToBeReceived.ToString();

            if (from.ReplyToAddress != null) //Handles SendOnly endpoints, where ReplyToAddress is not set
            {
                to[NServiceBus + ReplyToAddress] = from.ReplyToAddress.ToString();
            }

            SetBackwardsCompatibilityHeaders(to);

            string replyToAddress;
            if (from.Headers.TryGetValue(ReplyToAddress, out replyToAddress))
            {
                to[Headers.RouteTo] = replyToAddress;
            }

            from.Headers.ToList()
                .ForEach(header => to[NServiceBus + Headers.HeaderName + "." + header.Key] = header.Value);

            return to;
        }
Beispiel #15
0
        public static TransportMessage Map(IDictionary<string, string> from)
        {
            if (!from.ContainsKey(GatewayHeaders.IsGatewayMessage))
            {
                return new TransportMessage();
            }

            var headers = ExtractHeaders(from);
            var to = new TransportMessage(from[NServiceBus + Id], headers);

            to.CorrelationId = StripSlashZeroFromCorrelationId(from[NServiceBus + CorrelationId]) ?? to.Id;

            bool recoverable;
            if (bool.TryParse(from[NServiceBus + Recoverable], out recoverable))
            {
                to.Recoverable = recoverable;
            }

            TimeSpan timeToBeReceived;
            TimeSpan.TryParse(from[NServiceBus + TimeToBeReceived], out timeToBeReceived);
            to.TimeToBeReceived = timeToBeReceived;

            if (to.TimeToBeReceived < MinimumTimeToBeReceived)
            {
                to.TimeToBeReceived = MinimumTimeToBeReceived;
            }

            return to;
        }
		public void ReceiveMessageLater(TransportMessage m, string address)
		{
			if (!string.IsNullOrEmpty(address))
			{
				Send(m, address);
			}
		}
        public TransportMessage ToTransportMessage(BrokeredMessage message)
        {
            TransportMessage t;
            var rawMessage = message.GetBody<byte[]>();

            if (message.Properties.Count == 0)
            {
                t = DeserializeMessage(rawMessage);
            }
            else
            {
                t = new TransportMessage(message.MessageId, message.Properties.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value.ToString()))
                        {
                            CorrelationId = message.CorrelationId,
                            TimeToBeReceived = message.TimeToLive
                        };

                t.MessageIntent =
                    (MessageIntentEnum)
                    Enum.Parse(typeof(MessageIntentEnum), message.Properties[Headers.MessageIntent].ToString());

                if ( !String.IsNullOrWhiteSpace( message.ReplyTo ) )
                {
                    t.ReplyToAddress = Address.Parse( message.ReplyTo ); // Will this work?
                }

                t.Body = rawMessage;
            }

            return t;
        }
        public void Send(TransportMessage message)
        {
            var received = MessageReceived;

            if (received != null)
                received(message, this);
        }
        private static string SerializeToXml(TransportMessage transportMessage)
        {
            var overrides = new XmlAttributeOverrides();
            var attrs = new XmlAttributes {XmlIgnore = true};

            // Exclude non-serializable members
            overrides.Add(typeof (TransportMessage), "Body", attrs);
            overrides.Add(typeof (TransportMessage), "ReplyToAddress", attrs);
            overrides.Add(typeof (TransportMessage), "Headers", attrs);

            var sb = new StringBuilder();
            var xws = new XmlWriterSettings { Encoding = Encoding.Unicode };
            var xw = XmlWriter.Create(sb, xws);
            var xs = new XmlSerializer(typeof (TransportMessage), overrides);
            xs.Serialize(xw, transportMessage);

            var xdoc = XDocument.Parse(sb.ToString());
            var body = new XElement("Body");
            var cdata = new XCData(Encoding.UTF8.GetString(transportMessage.Body));
            body.Add(cdata);
            xdoc.SafeElement("TransportMessage").Add(body);

            sb.Clear();
            var sw = new StringWriter(sb);
            xdoc.Save(sw);

            return sb.ToString();
        }
 public void Send(TransportMessage message, Address address)
 {
    using(var redisClient = new RedisClient())
    {
        redisClient.Add(string.Format("{0}:{1}", address.Machine, address.Queue), message);
    }
 }
 /// <summary>
 /// Ensure that the content type which is introduced in V4.0.0 and later versions is present in the header.
 /// </summary>
 /// <param name="transportMessage">Transport Message to mutate.</param>
 public void MutateIncoming(TransportMessage transportMessage)
 {
     if (!transportMessage.IsControlMessage() && !transportMessage.Headers.ContainsKey(Headers.ContentType))
     {
         transportMessage.Headers[Headers.ContentType] = Serializer.ContentType;
     }
 }
Beispiel #22
0
        void HandleProcessingAlwaysFailsForMessage(TransportMessage message, Exception e, int numberOfRetries)
        {
            message.SetExceptionHeaders(e, localAddress ?? config.LocalAddress);

            if (MessageWasSentFromSLR(message))
            {
                SendToErrorQueue(message, e);
                return;
            }

            var flrPart = numberOfRetries > 0
                ? $"Message with '{message.Id}' id has failed FLR and"
                : $"FLR is disabled and the message '{message.Id}'";

            //HACK: We need this hack here till we refactor the SLR to be a first class concept in the TransportReceiver
            if (RetriesQueue == null)
            {
                Logger.ErrorFormat("{0} will be moved to the configured error queue.", flrPart);
                SendToErrorQueue(message, e);
                return;
            }

            var defer = SecondLevelRetriesConfiguration.RetryPolicy.Invoke(message);

            if (defer < TimeSpan.Zero)
            {
                Logger.ErrorFormat(
                    "SLR has failed to resolve the issue with message {0} and will be forwarded to the error queue at {1}",
                    message.Id, ErrorQueue);
                SendToErrorQueue(message, e);
                return;
            }

            SendToRetriesQueue(message, e, flrPart);
        }
        public static IBasicProperties FillRabbitMqProperties(TransportMessage message, IBasicProperties properties)
        {
            properties.MessageId = message.Id;

            properties.CorrelationId = message.CorrelationId;

            if (message.TimeToBeReceived < TimeSpan.MaxValue)
                properties.Expiration = message.TimeToBeReceived.TotalMilliseconds.ToString();

            properties.SetPersistent(message.Recoverable);

            properties.Headers = message.Headers;

            if (message.Headers.ContainsKey(Headers.EnclosedMessageTypes))
            {
                properties.Type = message.Headers[Headers.EnclosedMessageTypes].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
            }

            if (message.Headers.ContainsKey(Headers.ContentType))
                properties.ContentType = message.Headers[Headers.ContentType];
            else
            {
                properties.ContentType = "application/octet-stream";
            }

            if (message.ReplyToAddress != null && message.ReplyToAddress != Address.Undefined)
                properties.ReplyTo = message.ReplyToAddress.Queue;

            return properties;
        }
        static bool HasReachedMaxTime(TransportMessage message)
        {
            var timestampHeader = TransportMessageHeaderHelper.GetHeader(message, SecondLevelRetriesHeaders.RetriesTimestamp);

            if (String.IsNullOrEmpty(timestampHeader))
            {
                return false;
            }

            try
            {
                var handledAt = DateTimeExtensions.ToUtcDateTime(timestampHeader);

                if (DateTime.UtcNow > handledAt.AddDays(1))
                {
                    return true;
                }
            }
                // ReSharper disable once EmptyGeneralCatchClause
                // this code won't usually throw but in case a user has decided to hack a message/headers and for some bizarre reason 
                // they changed the date and that parse fails, we want to make sure that doesn't prevent the message from being 
                // forwarded to the error queue.
            catch (Exception)
            {
            }

            return false;
        }
        public void Defer(TransportMessage message, SendOptions sendOptions)
        {
            message.Headers[TimeoutManagerHeaders.RouteExpiredTimeoutTo] = sendOptions.Destination.ToString();

            DateTime deliverAt;

            if (sendOptions.DelayDeliveryWith.HasValue)
            {
                deliverAt = DateTime.UtcNow + sendOptions.DelayDeliveryWith.Value;
            }
            else
            {
                if (sendOptions.DeliverAt.HasValue)
                {
                    deliverAt = sendOptions.DeliverAt.Value;    
                }
                else
                {
                    throw new ArgumentException("A delivery time needs to be specified for Deferred messages");
                }
                
            }

            message.Headers[TimeoutManagerHeaders.Expire] = DateTimeExtensions.ToWireFormattedString(deliverAt);
            
            try
            {
                MessageSender.Send(message, new SendOptions(TimeoutManagerAddress));
            }
            catch (Exception ex)
            {
                Log.Error("There was a problem deferring the message. Make sure that DisableTimeoutManager was not called for your endpoint.", ex);
                throw;
            }
        }
        public void Send(object messageToSend, TimeSpan timeToBeReceived)
        {
            var message = new TransportMessage
            {
                TimeToBeReceived = timeToBeReceived
            };

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(new[] { messageToSend }, stream);
                message.Body = stream.ToArray();
            }

            //hack to remove the type info from the json
            var bodyString = Encoding.UTF8.GetString(message.Body);

            var toReplace = ", " + messageToSend.GetType().Assembly.GetName().Name;

            bodyString = bodyString.Replace(toReplace, ", ServiceControl");

            message.Body = Encoding.UTF8.GetBytes(bodyString);
            // end hack
            message.Headers[Headers.EnclosedMessageTypes] = messageToSend.GetType().FullName;
            message.Headers[Headers.ContentType] = ContentTypes.Json; //Needed for ActiveMQ transport

            try
            {
                messageSender.Send(message, new SendOptions(serviceControlBackendAddress) { ReplyToAddress = configure.LocalAddress });
                circuitBreaker.Success();
            }
            catch (Exception ex)
            {
                circuitBreaker.Failure(ex);
            }            
        }
Beispiel #27
0
        private SqlCommand BuildSendCommand(SqlConnection connection, TransportMessage transportMessage, Address address)
        {
            var command = connection.CreateCommand();

            command.CommandText = String.Format(SqlCommands.Send, address);
            command.CommandType = CommandType.Text;

            command.Parameters.AddWithValue("@Id", transportMessage.MessageId);
            command.Parameters.AddWithValue("@ReplyTo", transportMessage.ReplyToAddress.ToString());
            command.Parameters.AddWithValue("@Headers", objectSerializer.SerializeObject(transportMessage.Headers));
            command.Parameters.AddWithValue("@Body", transportMessage.Body);

            if (transportMessage.CorrelationId != Guid.Empty)
            {
                command.Parameters.AddWithValue("@CorrelationId", transportMessage.CorrelationId);
            }
            else
            {
                command.Parameters.AddWithValue("@CorrelationId", DBNull.Value);
            }

            if (transportMessage.HasExpiryTime)
            {
                command.Parameters.AddWithValue("@Expires", transportMessage.ExpiryTime);
            }
            else
            {
                command.Parameters.AddWithValue("@Expires", DBNull.Value);
            }

            return command;
        }
        void Defer(TimeSpan defer, TransportMessage message)
        {
            var retryMessageAt = DateTime.UtcNow + defer;

            TransportMessageHeaderHelper.SetHeader(message, Headers.Retries,
                (TransportMessageHeaderHelper.GetNumberOfRetries(message) + 1).ToString(CultureInfo.InvariantCulture));

            var addressOfFaultingEndpoint = TransportMessageHeaderHelper.GetAddressOfFaultingEndpoint(message);

            if (!TransportMessageHeaderHelper.HeaderExists(message, SecondLevelRetriesHeaders.RetriesTimestamp))
            {
                TransportMessageHeaderHelper.SetHeader(message, SecondLevelRetriesHeaders.RetriesTimestamp,
                    DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow));
            }

            logger.DebugFormat("Defer message and send it to {0}", addressOfFaultingEndpoint);

            var sendOptions = new SendOptions(addressOfFaultingEndpoint)
            {
                DeliverAt = retryMessageAt
            };


            MessageDeferrer.Defer(message, sendOptions);
        }
        /// <summary>
        /// Stores the original saga id and type of the incoming message
        /// </summary>
        /// <param name="transportMessage"></param>
        public void MutateIncoming(TransportMessage transportMessage)
        {
            originatingSagaId = null;
            originatingSagaType = null;

            // We need this for backwards compatibility because in v4.0.0 we still have this headers being sent as part of the message even if MessageIntent == MessageIntentEnum.Publish
            if (transportMessage.MessageIntent == MessageIntentEnum.Publish)
            {
                if (transportMessage.Headers.ContainsKey(Headers.SagaId))
                {
                    transportMessage.Headers.Remove(Headers.SagaId);
                }

                if (transportMessage.Headers.ContainsKey(Headers.SagaType))
                {
                    transportMessage.Headers.Remove(Headers.SagaType);
                }
            }

            if (transportMessage.Headers.ContainsKey(Headers.OriginatingSagaId))
            {
                originatingSagaId = transportMessage.Headers[Headers.OriginatingSagaId];
            }

            if (transportMessage.Headers.ContainsKey(Headers.OriginatingSagaType))
            {
                originatingSagaType = transportMessage.Headers[Headers.OriginatingSagaType];
            }
        }
        public static TransportMessage ToTransportMessage(this BrokeredMessage message)
        {
            TransportMessage t;
            var rawMessage = BrokeredMessageBodyConversion.ExtractBody(message);

            if (message.Properties.Count > 0)
            {
                var headers = message.Properties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string);
                if (!String.IsNullOrWhiteSpace(message.ReplyTo))
                {
                    headers[Headers.ReplyToAddress] = message.ReplyTo;
                }

                t = new TransportMessage(message.MessageId, headers)
                {
                    CorrelationId = message.CorrelationId,
                    TimeToBeReceived = message.TimeToLive,
                    MessageIntent = (MessageIntentEnum)Enum.Parse(typeof(MessageIntentEnum), message.Properties[Headers.MessageIntent].ToString()),
                    Body = rawMessage
                };
            }
            else
            {
                t = new TransportMessage
                {
                    Body = rawMessage
                };
            }

            return t;
        }
 public Task OnReceived(IMessageSender sender, TransportMessage message)
 {
     return(Task.CompletedTask);
 }
 public static bool IsDnsResultMessage(this TransportMessage message)
 {
     return(message.ContentType == typeof(DnsTransportMessage).FullName);
 }
Beispiel #33
0
 void AssertReceived <T>(TransportMessage receivedEvent)
 {
     Assert.AreEqual(typeof(T).FullName, receivedEvent.CorrelationId);
 }
Beispiel #34
0
 public IncomingContext(TransportMessage message)
 {
     Set(message);
 }
Beispiel #35
0
        public byte[] Encode(TransportMessage message)
        {
            var transportMessage = new ProtoBufTransportMessage(message);

            return(SerializerUtilitys.Serialize(transportMessage));
        }
Beispiel #36
0
 public void Send(TransportMessage message, string destination)
 {
     Send(message, Address.Parse(destination));
 }
Beispiel #37
0
 public void MutateIncoming(TransportMessage transportMessage)
 {
     var headers      = transportMessage.Headers;
     var nsbVersion   = headers[Headers.NServiceBusVersion];
     var customHeader = headers["MyCustomHeader"];
 }
Beispiel #38
0
 public MessageDispatch CreateMessageDispatch(TransportMessage transportMessage)
 {
     return(new MessageDispatch(MessageContext.CreateNew(transportMessage), null, null));
 }
Beispiel #39
0
        async Task ProcessMessage(Message receivedMessage, CancellationToken token)
        {
            try
            {
                await maxConcurrencySempahore.WaitAsync(token).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                // shutting down, semaphore doesn't need to be released because it was never acquired
                return;
            }

            try
            {
                IncomingMessage  incomingMessage  = null;
                TransportMessage transportMessage = null;

                var isPoisonMessage = false;
                try
                {
                    transportMessage = JsonConvert.DeserializeObject <TransportMessage>(receivedMessage.Body);

                    incomingMessage = await transportMessage.ToIncomingMessage(s3Client, configuration, token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // shutting down
                    return;
                }
                catch (Exception ex)
                {
                    // Can't deserialize. This is a poison message
                    Logger.Warn($"Treating message with SQS Message Id {receivedMessage.MessageId} as a poison message due to exception {ex}. Moving to error queue.");
                    isPoisonMessage = true;
                }

                if (incomingMessage == null || transportMessage == null)
                {
                    Logger.Warn($"Treating message with SQS Message Id {receivedMessage.MessageId} as a poison message because it could not be converted to an IncomingMessage. Moving to error queue.");
                    isPoisonMessage = true;
                }

                if (isPoisonMessage)
                {
                    await MovePoisonMessageToErrorQueue(receivedMessage).ConfigureAwait(false);

                    return;
                }

                if (!IsMessageExpired(receivedMessage, incomingMessage))
                {
                    await ProcessMessageWithInMemoryRetries(incomingMessage, token).ConfigureAwait(false);
                }

                // Always delete the message from the queue.
                // If processing failed, the onError handler will have moved the message
                // to a retry queue.
                await DeleteMessage(receivedMessage, transportMessage, incomingMessage, token).ConfigureAwait(false);
            }
            finally
            {
                maxConcurrencySempahore.Release();
            }
        }
 public void Send(TransportMessage message)
 {
     _messages.Enqueue(message);
 }
 private void SendToPersistenceService(TransportMessage transportMessage, IEnumerable <Peer> persistencePeers)
 {
     _innerTransport.Send(transportMessage, persistencePeers, new SendContext());
 }
Beispiel #42
0
 public static TransportMessage ForEndpoint(this TransportMessage message, string endpoint)
 {
     message.Headers[MessageHeaders.Endpoint] = endpoint;
     return(message);
 }
 public void Send(TransportMessage message, IEnumerable <Peer> peers)
 {
     Send(message, peers, new SendContext());
 }
Beispiel #44
0
 /// <summary>
 /// Constructs the in-mem transport message from the given <see cref="TransportMessage"/>
 /// </summary>
 public InMemTransportMessage(TransportMessage transportMessage)
 {
     Headers = transportMessage.Headers;
     Body    = transportMessage.Body;
 }
Beispiel #45
0
 IList <Site> GetDestinationSitesFor(TransportMessage messageToDispatch)
 {
     return(Builder.BuildAll <IRouteMessagesToSites>()
            .SelectMany(r => r.GetDestinationSitesFor(messageToDispatch)).ToList());
 }
 private void TriggerMessageReceived(TransportMessage transportMessage)
 {
     MessageReceived?.Invoke(transportMessage);
 }
Beispiel #47
0
 public Task Invoke(TransportMessage message)
 {
     return(InvokeInternal(message, 0));
 }
Beispiel #48
0
        /// <summary>
        /// Adds the <see cref="TransportMessage"/> as an outgoing message destined for the addresses specified by <paramref name="destinationAddresses"/>
        /// under the given <paramref name="messageId"/>
        /// </summary>
        public void AddOutgoingMessage(string messageId, IEnumerable <string> destinationAddresses, TransportMessage transportMessage)
        {
            var outgoingMessage = new OutgoingMessage(destinationAddresses, transportMessage);

            GetOrCreate(messageId).Add(outgoingMessage);
        }
Beispiel #49
0
 protected void AddTestMessage(TransportMessage messageToAdd)
 {
     queue.Send(messageToAdd, QueueName);
 }
Beispiel #50
0
        static void PrintHeaders(TransportMessage message)
        {
            Console.WriteLine(@"Headers:
{0}", string.Join(Environment.NewLine, message.Headers.Select(kvp => $"    {kvp.Key}: {kvp.Value}")));
        }
Beispiel #51
0
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            var headers = transportMessage.Headers;

            headers["MyCustomHeader"] = "My custom value";
        }
Beispiel #52
0
        async Task StoreMessageUntilDue(string deferredUntil, Dictionary <string, string> headers, TransportMessage transportMessage)
        {
            var approximateDueTime = GetTimeToBeDelivered(deferredUntil);

            _log.Debug("Deferring message {0} until {1}", headers[Headers.MessageId], approximateDueTime);

            headers.Remove(Headers.DeferredUntil);

            await _timeoutManager.Defer(approximateDueTime, headers, transportMessage.Body);
        }
Beispiel #53
0
 IEnumerable <Site> GetDestinationSitesFor(TransportMessage messageToDispatch)
 {
     return(builder.BuildAll <IRouteMessagesToSites>()
            .SelectMany(r => r.GetDestinationSitesFor(messageToDispatch)));
 }
        public void outgoing_no_headers()
        {
            var transportMessage = new TransportMessage();

            Assert.DoesNotThrow(() => _uow.MutateOutgoing(Moq.It.IsAny <LogicalMessage>(), transportMessage));
        }
Beispiel #55
0
 public Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
 {
     _sendCallback(destinationAddress);
     return(_transport.Send(destinationAddress, message, context));
 }
Beispiel #56
0
        public void Handle(TransportMessage msg, string remoteUrl)
        {
            var address = remoteUrl;
            var headers = new WebHeaderCollection();

            if (msg.Headers.ContainsKey(NServiceBus.Headers.HttpTo))
            {
                address = msg.Headers[NServiceBus.Headers.HttpTo];
            }

            var request = WebRequest.Create(address);

            request.Method = "POST";

            var buffer = msg.Body;

            request.ContentType = "application/x-www-form-urlencoded";

            if (!String.IsNullOrEmpty(msg.IdForCorrelation))
            {
                msg.IdForCorrelation = msg.Id;
            }

            HeaderMapper.Map(msg, headers);

            string hash = Hasher.Hash(buffer);

            headers[HttpHeaders.ContentMd5Key] = hash;
            headers["NServiceBus.Gateway"]     = "true";
            headers[HttpHeaders.FromKey]       = from;
            headers[HeaderMapper.NServiceBus + HeaderMapper.CallType] = Enum.GetName(typeof(CallType), CallType.Submit);

            request.Headers       = headers;
            request.ContentLength = buffer.Length;

            var stream = request.GetRequestStream();

            stream.Write(buffer, 0, buffer.Length);

            Logger.Debug("Sending message to: " + address);

            var response   = request.GetResponse() as HttpWebResponse;
            var statusCode = (int)response.StatusCode;

            response.Close();

            Logger.Debug("Got HTTP response with status code " + statusCode);


            if (statusCode == 200)
            {
                Logger.Debug("Message transferred successfully. Going to acknowledge.");

                var ack = WebRequest.Create(address);
                ack.Method      = "POST";
                ack.ContentType = "application/x-www-form-urlencoded";
                ack.Headers     = headers;
                ack.Headers[HeaderMapper.NServiceBus + HeaderMapper.CallType] = Enum.GetName(typeof(CallType), CallType.Ack);
                ack.ContentLength = 0;

                Logger.Debug("Sending ack to: " + address);

                var ackResponse = ack.GetResponse() as HttpWebResponse;
                var ackCode     = (int)ackResponse.StatusCode;
                response.Close();

                Logger.Debug("Got HTTP response with status code " + ackCode);

                if (ackCode != 200)
                {
                    Logger.Info("Ack not transferred successfully. Trying again...");
                    throw new Exception("Retrying");
                }

                notifier.RaiseMessageProcessed(TransportTypeEnum.FromMsmqToHttp, msg);
            }
            else
            {
                Logger.Info("Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
Beispiel #57
0
 public void FakeMessageBeeingProcessed(TransportMessage transportMessage)
 {
     StartedMessageProcessing(this, new EventArgs());
     TransportMessageReceived(this, new TransportMessageReceivedEventArgs(transportMessage));
     FinishedMessageProcessing(this, new EventArgs());
 }
Beispiel #58
0
 public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
 {
     logger.Info("Adding Thread.CurrentPrincipal user to headers");
     transportMessage.Headers["UserName"] = Thread.CurrentPrincipal.Identity.Name;
 }
Beispiel #59
0
 /// <summary>
 /// Sets the <see cref="Headers.DeferredUntil"/> header to the specified time
 /// </summary>
 public static void SetDeferHeaders(this TransportMessage message, DateTimeOffset approximateDeliveryTime, string destinationAddress)
 {
     InnerSetDeferHeaders(approximateDeliveryTime, message.Headers, destinationAddress);
 }
Beispiel #60
0
 public void FakeMessageBeeingPassedToTheFaultManager(TransportMessage transportMessage)
 {
     StartedMessageProcessing(this, new EventArgs());
     FinishedMessageProcessing(this, new EventArgs());
 }