Ejemplo n.º 1
0
        public void RegisteringCallbackPoint_SetsCallbackIdentityAndCallbackReceiverIdentity()
        {
            var message = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();

            var callbackReceiverIdentity     = Guid.NewGuid().ToByteArray();
            var callbackReceiverNodeIdentity = Guid.NewGuid().ToByteArray();
            var callbackMessageIdentifier    = new MessageIdentifier(Guid.NewGuid().ToByteArray(),
                                                                     Randomizer.UInt16(),
                                                                     Guid.NewGuid().ToByteArray());
            var callbackKey = Randomizer.Int32();

            message.RegisterCallbackPoint(callbackReceiverNodeIdentity,
                                          callbackReceiverIdentity,
                                          callbackMessageIdentifier,
                                          callbackKey);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            CollectionAssert.Contains(message.CallbackPoint, callbackMessageIdentifier);
            CollectionAssert.AreEqual(callbackReceiverIdentity, message.CallbackReceiverIdentity);
            CollectionAssert.AreEqual(callbackReceiverNodeIdentity, message.CallbackReceiverNodeIdentity);
            CollectionAssert.IsEmpty(message.ReceiverIdentity);
        }
Ejemplo n.º 2
0
        public Task <IMessage> HandleMultipartMessage(ISession session, MultipartMessage message)
        {
            _logger.Verbose(
                $"Handling {nameof(MultipartMessage)} " +
                $"(MultipartMessageId={message.MultipartMessageId}, " +
                $"Offset={message.Offset}, " +
                $"Length={message.Length}, " +
                $"TotalLength={message.TotalLength}, " +
                $"Data='{BitConverter.ToString(message.Data)}')."
                );
            bool isNewMultipartMessageWaiter = false;
            var  multipartMessageWaiter      = _multipartMessageWaiters.GetOrAdd(message.MultipartMessageId, key =>
            {
                isNewMultipartMessageWaiter = true;
                return(new MultipartMessageWaiter(
                           message.MultipartMessageId,
                           message.TotalLength,
                           this
                           ));
            });

            multipartMessageWaiter.AddMessage(message);
            if (isNewMultipartMessageWaiter)
            {
                return(multipartMessageWaiter.Wait());
            }
            return(Task.FromResult <IMessage>(null));
        }
Ejemplo n.º 3
0
 public void AddMessage(MultipartMessage message)
 {
     if (message.MultipartMessageId != _multipartMessageId)
     {
         return;
     }
     if (_receivedLength >= _totalLength)
     {
         return;
     }
     if (!_messages.TryAdd(message.Offset, message))
     {
         return;
     }
     if (Interlocked.Add(ref _receivedLength, message.Length) >= _totalLength)
     {
         var buffer = new GrowingSpanBuffer(stackalloc byte[(int)_totalLength]);
         foreach (var kvp in _messages.OrderBy(kvp => kvp.Key))
         {
             buffer.WriteBytes(kvp.Value.Data);
         }
         var bufferReader = new SpanBufferReader(buffer.Data);
         var fullMessage  = _service._messageReader.ReadFrom(ref bufferReader, 0x00);
         Complete(fullMessage);
     }
 }
Ejemplo n.º 4
0
        public void SendMessage(IMessage message)
        {
            var multipart = new MultipartMessage((Message)message);
            var frames    = (IList <byte[]>)multipart.Frames;
            var msg       = new Msg();

            try
            {
                var framesCount = frames.Count;
                for (var i = 0; i < framesCount;)
                {
                    var buffer = frames[i];
                    msg.InitGC(buffer, buffer.Length);
                    var sendingTimeout1 = config.SendTimeout;
                    if (!socket.TrySend(ref msg, sendingTimeout1, ++i < framesCount))
                    {
                        throw new TimeoutException($"Sending timed out after {sendingTimeout1.TotalMilliseconds} ms!");
                    }
                }
                SendRate?.Increment();
            }
            finally
            {
                msg.Close();
            }
        }
Ejemplo n.º 5
0
        public void MessageDistribution_IsConsistentlyTransferredViaMultipartMessage(DistributionPattern distributionPattern)
        {
            var message = Message.Create(new SimpleMessage(), distributionPattern).As <Message>();

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(distributionPattern, message.Distribution);
        }
Ejemplo n.º 6
0
        public void MessageTraceOptions_IsConsistentlyTransferredViaMultipartMessage(MessageTraceOptions routeOptions)
        {
            var message = (Message)Message.CreateFlowStartMessage(new SimpleMessage());

            message.TraceOptions = routeOptions;

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(routeOptions, message.TraceOptions);
        }
Ejemplo n.º 7
0
        public void SecurityDomain_IsConsistentlyTransferredViaMultipartMessage()
        {
            var securityDomain = Guid.NewGuid().ToString();
            var message        = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();

            message.SetDomain(securityDomain);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(securityDomain, message.Domain);
        }
Ejemplo n.º 8
0
        public void ReceiverNode_IsConsistentlyTransferredViaMultipartMessage()
        {
            var message      = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();
            var receiverNode = ReceiverIdentifier.Create();

            message.SetReceiverNode(receiverNode);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            CollectionAssert.AreEqual(receiverNode.Identity, message.ReceiverNodeIdentity);
        }
Ejemplo n.º 9
0
        public void CorrelationId_IsConsistentlyTransferredViaMultipartMessage()
        {
            var message       = (Message)Message.CreateFlowStartMessage(new SimpleMessage());
            var correlationId = Guid.NewGuid().ToByteArray();

            message.SetCorrelationId(correlationId);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            CollectionAssert.AreEqual(correlationId, message.CorrelationId);
        }
Ejemplo n.º 10
0
        public void MessageTTL_IsConsistentlyTransferredViaMultipartMessage()
        {
            var ttl     = TimeSpan.FromSeconds(Randomizer.Int32(2, 60));
            var message = (Message)Message.CreateFlowStartMessage(new SimpleMessage());

            message.TTL = ttl;

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(ttl, message.TTL);
        }
Ejemplo n.º 11
0
        public void ParseMessageWithBinaryData()
        {
            string boundary = "-----Test";

            byte[] requestData;
            using (MemoryStream stream = new MemoryStream())
            {
                using (MultipartStreamWriter writer = new MultipartStreamWriter(
                           stream,
                           boundary,
                           Encoding.UTF8))
                {
                    writer.WritePart("text/plain", "my text", Encoding.UTF8);
                    writer.WritePart("application/xml", "<tag/>", Encoding.UTF8);

                    byte[] pdfData = File.ReadAllBytes(@"..\..\..\samples\pdf-test.pdf");

                    List <HeaderField> headers = new List <HeaderField>();
                    headers.Add(new HeaderField("Content-type", "application/pdf"));
                    headers.Add(new HeaderField("Content-id", "PDF"));
                    writer.WritePart(headers, pdfData);

                    writer.WriteCloseDelimiter();
                }

                requestData = stream.ToArray();
            }

            log.DebugFormat("Message body: {0}", Encoding.UTF8.GetString(requestData));

            string requestContentType = string.Format(
                CultureInfo.InvariantCulture,
                "multipart/mixed;boundary=\"{0}\"",
                boundary);

            MultipartMessage message = StartReading(requestContentType, requestData);

            Assert.IsTrue(message.IsMultipart);
            Assert.AreEqual(MultipartMessage.MediaTypeMultipartMixed, message.MediaType);

            MultipartMessagePart part;

            part = reader.ReadNextPart();
            part = reader.ReadNextPart();
            part = reader.ReadNextPart();

            Assert.AreEqual("application/pdf", part.GetHeader("content-type").FieldValue);
            File.WriteAllBytes("test.pdf", part.Data);

            Assert.IsNull(reader.ReadNextPart());
        }
Ejemplo n.º 12
0
        public void MessageWireFormatVersion_IsConsistentlyTransferredViaMultipartMessage()
        {
            const int wireMessageFormat = 5;

            var message = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();

            Assert.AreEqual(wireMessageFormat, message.WireFormatVersion);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(wireMessageFormat, message.WireFormatVersion);
        }
Ejemplo n.º 13
0
        public void MessagePartition_IsConsistentlyTransferredViaMultipartMessage()
        {
            var message = (Message)Message.CreateFlowStartMessage(new SimpleMessage
            {
                Partition = Guid.NewGuid().ToByteArray()
            });
            var partition = message.Partition;

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.IsTrue(Unsafe.ArraysEqual(partition, message.Partition));
        }
Ejemplo n.º 14
0
        public void MessageContent_IsConsistentlyTransferredViaMultipartMessage()
        {
            var messageText = Guid.NewGuid().ToString();
            var message     = (Message)Message.CreateFlowStartMessage(new SimpleMessage {
                Content = messageText
            });

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(messageText, message.GetPayload <SimpleMessage>().Content);
            Assert.IsTrue(message.Equals(MessageIdentifier.Create <SimpleMessage>()));
        }
Ejemplo n.º 15
0
        public void MessageHops_AreConsistentlyTransferredViaMultipartMessage()
        {
            var message = (Message)Message.CreateFlowStartMessage(new SimpleMessage());

            message.AddHop();
            message.AddHop();
            var hops = message.Hops;

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(hops, message.Hops);
        }
Ejemplo n.º 16
0
        public void MessageSignature_IsConsistentlyTransferredViaMultipartMessage()
        {
            var simpleMessage  = new SimpleMessage();
            var securityDomain = securityProvider.GetDomain(simpleMessage.Identity);
            var message        = Message.CreateFlowStartMessage(simpleMessage).As <Message>();

            message.SetDomain(securityDomain);
            message.SignMessage(securityProvider);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            message.VerifySignature(securityProvider);
        }
Ejemplo n.º 17
0
        public void CallbackKey_IsConsistentlyTransferredViaMultipartMessage()
        {
            var message     = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();
            var callbackKey = Randomizer.Int32(1, Int32.MaxValue);
            var callbackMessageIdentifier = MessageIdentifier.Create <SimpleMessage>();

            message.RegisterCallbackPoint(Guid.NewGuid().ToByteArray(),
                                          Guid.NewGuid().ToByteArray(),
                                          callbackMessageIdentifier,
                                          callbackKey);
            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            Assert.AreEqual(callbackKey, message.CallbackKey);
        }
Ejemplo n.º 18
0
        public void ParseMessageWithTwoParts()
        {
            string contentType = "multipart/mixed; boundary=\"abcd\"";
            string content     = "\r\n--abcd\r\nContent-Type: application/xml;charset=UTF-8\r\n\r\n<movie>...</movie>\r\n--abcd\r\n\r\nplain text\r\n--abcd--";

            MultipartMessage message = ParseMessage(contentType, content);

            Assert.IsTrue(message.IsMultipart);
            Assert.AreEqual(MultipartMessage.MediaTypeMultipartMixed, message.MediaType);
            Assert.AreEqual("abcd", message.Boundary);
            Assert.AreEqual(2, message.Parts.Count);

            MultipartMessagePart part = message.Parts[0];

            Assert.IsTrue(part.HasHeader("content-type"));
            Assert.AreEqual("application/xml", part.GetHeader("content-type").FieldValue);
            Assert.AreEqual("<movie>...</movie>", Encoding.UTF8.GetString(part.Data));
        }
Ejemplo n.º 19
0
        public void ParseMessageWithBoundaryWithoutQuotes()
        {
            string contentType = "multipart/mixed; boundary=abcd";
            string content     = "\r\n--abcd\r\nContent-Type: application/xml;charset=UTF-8\r\n\r\n<movie>...</movie>\r\n--abcd--";

            MultipartMessage message = StartReading(contentType, content);

            Assert.IsTrue(message.IsMultipart);
            Assert.AreEqual(MultipartMessage.MediaTypeMultipartMixed, message.MediaType);
            Assert.AreEqual("abcd", message.Boundary);

            MultipartMessagePart part = reader.ReadNextPart();

            Assert.IsTrue(part.HasHeader("content-type"));
            Assert.AreEqual("application/xml", part.GetHeader("content-type").FieldValue);
            Assert.AreEqual("<movie>...</movie>", Encoding.UTF8.GetString(part.Data));

            Assert.IsNull(reader.ReadNextPart());
        }
Ejemplo n.º 20
0
        public void MessageRouting_IsConsistentlyTransferredViaMultipartMessage()
        {
            var message = (Message)Message.CreateFlowStartMessage(new SimpleMessage());

            message.TraceOptions = MessageTraceOptions.Routing;
            var socketEnpoints = new[]
            {
                new SocketEndpoint(new Uri("tcp://localhost:40"), Guid.NewGuid().ToByteArray()),
                new SocketEndpoint(new Uri("tcp://localhost:40"), Guid.NewGuid().ToByteArray())
            };

            foreach (var socketEndpoint in socketEnpoints)
            {
                message.PushRouterAddress(socketEndpoint);
            }

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            CollectionAssert.AreEquivalent(socketEnpoints, message.GetMessageRouting());
        }
Ejemplo n.º 21
0
        public void IfCallbackIdentityIsEqualToMessageIdentity_ReceiverIdentitiesAreSetToCallbackReceiverIdentities()
        {
            var message = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>();

            var callbackReceiverIdentity     = Guid.NewGuid().ToByteArray();
            var callbackReceiverNodeIdentity = Guid.NewGuid().ToByteArray();
            var callbackMessageIdentifier    = MessageIdentifier.Create <SimpleMessage>();
            var callbackKey = Randomizer.Int32();

            message.RegisterCallbackPoint(callbackReceiverNodeIdentity,
                                          callbackReceiverIdentity,
                                          callbackMessageIdentifier,
                                          callbackKey);

            var multipart = new MultipartMessage(message);

            message = Message.FromMultipartMessage(multipart);

            CollectionAssert.Contains(message.CallbackPoint, callbackMessageIdentifier);
            CollectionAssert.AreEqual(callbackReceiverIdentity, message.CallbackReceiverIdentity);
            CollectionAssert.AreEqual(callbackReceiverIdentity, message.ReceiverIdentity);
            CollectionAssert.AreEqual(callbackReceiverNodeIdentity, message.CallbackReceiverNodeIdentity);
            CollectionAssert.AreEqual(callbackReceiverNodeIdentity, message.ReceiverNodeIdentity);
        }
Ejemplo n.º 22
0
        public void WriteMessageAsAWhole()
        {
            string boundary = "-----Test";

            MultipartMessage message = new MultipartMessage(HeaderField.Parse("Content-type: multipart/mixed; boundary=-----Test"));

            MultipartMessagePart part;

            part = new MultipartMessagePart();
            part.AddHeader(new HeaderField("Content-Type", "text/plain"));
            part.Data = Encoding.UTF8.GetBytes("my text");
            message.AddPart(part);

            part = new MultipartMessagePart();
            part.AddHeader(new HeaderField("Content-Type", "application/xml"));
            part.Data = Encoding.UTF8.GetBytes("<tag/>");
            message.AddPart(part);

            using (MemoryStream stream = new MemoryStream())
            {
                long writtenBytes;
                using (MultipartStreamWriter writer = new MultipartStreamWriter(
                           stream,
                           boundary,
                           Encoding.UTF8))
                {
                    writer.WriteWholeMessage(message);
                    writtenBytes = writer.BytesWritten;
                }

                byte[] bytes = stream.ToArray();
                Assert.AreEqual(bytes.Length, writtenBytes);
                string result = Encoding.UTF8.GetString(bytes);
                Assert.AreEqual("\r\n-------Test\r\nContent-Type: text/plain\r\n\r\nmy text\r\n-------Test\r\nContent-Type: application/xml\r\n\r\n<tag/>\r\n-------Test--", result);
            }
        }
Ejemplo n.º 23
0
        public void ProcessMultipartMessage(ref byte[] data)
        {
            // create the multipart message
             byte[] partData = new byte[data.Length - MultipartHeaderLength];
             for (int i = 0; i < partData.Length; i++)
             {
            partData[i] = data[i + MultipartHeaderLength];
             }

             MultipartMessage message = new MultipartMessage()
             {
            Data = partData,
            MessageID = BitConverter.ToUInt32(data, OffsetMultipartMessageID - MessageHeaderLength),
            PartIndex = BitConverter.ToUInt16(data, OffsetMultipartPartIndex - MessageHeaderLength),
            PartCount = BitConverter.ToUInt16(data, OffsetMultipartPartCount - MessageHeaderLength)
             };

             Console.WriteLine("< !MULTIPART-COMPRESSED!: {0} ({1} / {2})", message.MessageID, message.PartIndex + 1, message.PartCount);

             // lock this crucial part to preven conflicts
             lock (_MultipartMessageLock)
             {
            // add the message to the list
            if (!_MultipartMessageCache.ContainsKey(message.MessageID))
            {
               _MultipartMessageCache.Add(message.MessageID, new List<MultipartMessage>());
            }
            List<MultipartMessage> messages = _MultipartMessageCache[message.MessageID];
            messages.Add(message);

            if (messages.Count == message.PartCount)
            {
               // all parts have arrived
               // sort the list
               messages.Sort();

               // write the parts into a stream
               MemoryStream inData = new MemoryStream();
               foreach (MultipartMessage part in messages)
               {
                  inData.Write(part.Data, 0, part.Data.Length);
               }
               inData.Position = 0;

               // decompress the stream
               MemoryStream outData = new MemoryStream();
               Decoder decompressor = new Decoder();

               // Read the decoder properties
               byte[] properties = new byte[5];
               inData.Read(properties, 0, 5);

               // Read in the decompress file size.
               byte[] dataLengthBytes = new byte[8];
               inData.Read(dataLengthBytes, 0, 8);
               long dataLength = BitConverter.ToInt64(dataLengthBytes, 0);

               decompressor.SetDecoderProperties(properties);
               decompressor.Code(inData, outData, inData.Length, dataLength, null);
               outData.Position = 0;

               // extract the actual message data
               byte messageCode = (byte)outData.ReadByte();
               byte[] messageLengthData = new byte[4];
               outData.Read(messageLengthData, 0, 4);
               int messageLength = BitConverter.ToInt32(messageLengthData, 0);
               byte[] messageData = new byte[messageLength];
               outData.Read(messageData, 0, messageLength);

               // close the streams
               inData.Close();
               outData.Close();

               // fire the completed multipart message callback
               _CompletedReceivedMultipartCallback(this, ref messageCode, ref messageData);
            }
             }
        }