Exemplo n.º 1
0
        /// <summary>
        /// Handles the group communication message.
        /// </summary>
        private void Handle(NsMessage <GeneralGroupCommunicationMessage> value, bool isRegistration = false)
        {
            // This is mainly used to handle the case should ObserverContainer
            // decide to trigger handlers concurrently for a single message.
            if (isRegistration)
            {
                // Process the registration message
                _registrationMessage = value;
            }
            else if (_registrationMessage != null && value == _registrationMessage)
            {
                // This means that we've already processed the message.
                // Ignore this message and discard the reference.
                _registrationMessage = null;
                return;
            }

            var gcMessage = value.Data.First();

            IObserver <NsMessage <GeneralGroupCommunicationMessage> > observer;

            if (!_observers.TryGetValue(NodeObserverIdentifier.FromMessage(gcMessage), out observer))
            {
                throw new InvalidOperationException();
            }

            observer.OnNext(value);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Serialize the NsMessage.
        /// </summary>
        /// <param name="obj">The object to serialize</param>
        /// <returns>The serialized object in byte array form</returns>
        public byte[] Encode(NsMessage <T> obj)
        {
            NsMessageProto proto = NsMessageProto.Create(obj, _codec);

            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(stream, proto);
                return(stream.ToArray());
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Add data into the queue.
 /// </summary>
 /// <param name="value"></param>
 public void OnNext(NsMessage <GeneralGroupCommunicationMessage> value)
 {
     foreach (var data in value.Data)
     {
         var gcMessage = data as GroupCommunicationMessage <T>;
         if (gcMessage != null && gcMessage.Data != null && gcMessage.Data.Length > 0)
         {
             _nodeStruct.AddData(gcMessage);
         }
     }
 }
Exemplo n.º 4
0
        public static NsMessageProto Create <T>(NsMessage <T> message, ICodec <T> codec)
        {
            NsMessageProto proto = new NsMessageProto();

            proto.SourceId = message.SourceId.ToString();
            proto.DestId   = message.DestId.ToString();

            foreach (T item in message.Data)
            {
                proto.Data.Add(codec.Encode(item));
            }

            return(proto);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Deserialize the byte array into NsMessage.
        /// </summary>
        /// <param name="data">The serialized byte array</param>
        /// <returns>The deserialized NsMessage</returns>
        public NsMessage <T> Decode(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                NsMessageProto proto = Serializer.Deserialize <NsMessageProto>(stream);

                IIdentifier   sourceId = _idFactory.Create(proto.SourceId);
                IIdentifier   destId   = _idFactory.Create(proto.DestId);
                NsMessage <T> message  = new NsMessage <T>(sourceId, destId);

                var messages = proto.Data.Select(byteArr => _codec.Decode(byteArr));
                message.Data.AddRange(messages);
                return(message);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Writes the class fields to the writer.
        /// </summary>
        /// <param name="obj">The object of type NsMessage<T></T> to be encoded</param>
        /// <param name="writer">The writer to which to write</param>
        public void Write(NsMessage <T> obj, IDataWriter writer)
        {
            byte[] encodedMetadata = GenerateMetaDataEncoding(obj);
            byte[] encodedInt      = BitConverter.GetBytes(encodedMetadata.Length);
            byte[] totalEncoding   = encodedInt.Concat(encodedMetadata).ToArray();
            writer.Write(totalEncoding, 0, totalEncoding.Length);

            Type messageType    = obj.Data[0].GetType();
            var  codecWriteFunc = _codecFunctionsCache.WriteFunction(messageType);

            foreach (var data in obj.Data)
            {
                codecWriteFunc(data, writer);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Writes the class fields to the writer.
        /// </summary>
        /// <param name="obj">The object of type NsMessage<T> to be encoded</param>
        /// <param name="writer">The writer to which to write</param>
        /// <param name="token">Cancellation token</param>
        public async Task WriteAsync(NsMessage <T> obj, IDataWriter writer, CancellationToken token)
        {
            byte[] encodedMetadata = GenerateMetaDataEncoding(obj);
            byte[] encodedInt      = BitConverter.GetBytes(encodedMetadata.Length);
            byte[] totalEncoding   = encodedInt.Concat(encodedMetadata).ToArray();
            await writer.WriteAsync(totalEncoding, 0, totalEncoding.Length, token);

            Type messageType = obj.Data[0].GetType();

            var codecWriteFunc = _codecFunctionsCache.WriteAsyncFunction(messageType);

            foreach (var data in obj.Data)
            {
                var asyncResult = codecWriteFunc.BeginInvoke(data, writer, token, null, null);
                await codecWriteFunc.EndInvoke(asyncResult);
            }
        }
Exemplo n.º 8
0
        private static byte[] GenerateMetaDataEncoding(NsMessage <T> obj)
        {
            List <byte[]> metadataBytes = new List <byte[]>();

            byte[] sourceBytes      = StringToBytes(obj.SourceId.ToString());
            byte[] dstBytes         = StringToBytes(obj.DestId.ToString());
            byte[] messageTypeBytes = StringToBytes(obj.Data[0].GetType().AssemblyQualifiedName);
            byte[] messageCount     = BitConverter.GetBytes(obj.Data.Count);

            metadataBytes.Add(BitConverter.GetBytes(sourceBytes.Length));
            metadataBytes.Add(BitConverter.GetBytes(dstBytes.Length));
            metadataBytes.Add(BitConverter.GetBytes(messageTypeBytes.Length));
            metadataBytes.Add(sourceBytes);
            metadataBytes.Add(dstBytes);
            metadataBytes.Add(messageTypeBytes);
            metadataBytes.Add(messageCount);

            return(metadataBytes.SelectMany(i => i).ToArray());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Instantiate the class from the reader.
        /// </summary>
        /// <param name="reader">The reader from which to read</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>The instance of type NsMessage<T> read from the reader</returns>
        public async Task <NsMessage <T> > ReadAsync(IDataReader reader, CancellationToken token)
        {
            int metadataSize = await reader.ReadInt32Async(token);

            byte[] metadata = new byte[metadataSize];
            await reader.ReadAsync(metadata, 0, metadataSize, token);

            var           res           = GenerateMetaDataDecoding(metadata);
            Type          messageType   = res.Item3;
            NsMessage <T> message       = res.Item1;
            var           codecReadFunc = _codecFunctionsCache.ReadAsyncFunction(messageType);
            int           messageCount  = res.Item2;

            for (int i = 0; i < messageCount; i++)
            {
                message.Data.Add(codecReadFunc(reader, token));
            }

            return(message);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Instantiate the class from the reader.
        /// </summary>
        /// <param name="reader">The reader from which to read</param>
        /// <returns>The instance of type NsMessage<T></T> read from the reader</returns>
        public NsMessage <T> Read(IDataReader reader)
        {
            int metadataSize = reader.ReadInt32();

            byte[] metadata = new byte[metadataSize];
            reader.Read(ref metadata, 0, metadataSize);
            var res = GenerateMetaDataDecoding(metadata);

            Type          messageType = res.Item3;
            NsMessage <T> message     = res.Item1;

            var codecReadFunc = _codecFunctionsCache.ReadFunction(messageType);
            int messageCount  = res.Item2;

            for (int i = 0; i < messageCount; i++)
            {
                message.Data.Add(codecReadFunc(reader));
            }

            return(message);
        }
Exemplo n.º 11
0
        private Tuple <NsMessage <T>, int, Type> GenerateMetaDataDecoding(byte[] obj)
        {
            int srcCount     = BitConverter.ToInt32(obj, 0);
            int dstCount     = BitConverter.ToInt32(obj, sizeof(int));
            int msgTypeCount = BitConverter.ToInt32(obj, 2 * sizeof(int));

            int    offset    = 3 * sizeof(int);
            string srcString = BytesToString(obj.Skip(offset).Take(srcCount).ToArray());

            offset += srcCount;
            string dstString = BytesToString(obj.Skip(offset).Take(dstCount).ToArray());

            offset += dstCount;
            Type msgType = Type.GetType(BytesToString(obj.Skip(offset).Take(msgTypeCount).ToArray()));

            offset += msgTypeCount;
            int messageCount = BitConverter.ToInt32(obj, offset);

            NsMessage <T> msg = new NsMessage <T>(_idFactory.Create(srcString), _idFactory.Create(dstString));

            return(new Tuple <NsMessage <T>, int, Type>(msg, messageCount, msgType));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Handles the incoming WritableNsMessage for this Task.
        /// Delegates the GeneralGroupCommunicationMessage to the correct
        /// WritableCommunicationGroupNetworkObserver.
        /// </summary>
        /// <param name="nsMessage"></param>
        public void OnNext(NsMessage <GeneralGroupCommunicationMessage> nsMessage)
        {
            if (nsMessage == null)
            {
                throw new ArgumentNullException("nsMessage");
            }

            try
            {
                GeneralGroupCommunicationMessage gcm = nsMessage.Data.First();
                _commGroupHandlers[gcm.GroupName].OnNext(gcm);
            }
            catch (InvalidOperationException)
            {
                LOGGER.Log(Level.Error, "Group Communication Network Handler received message with no data");
                throw;
            }
            catch (KeyNotFoundException)
            {
                LOGGER.Log(Level.Error, "Group Communication Network Handler received message for nonexistant group");
                throw;
            }
        }
        /// <summary>
        /// Handles the incoming NsMessage for this Task.
        /// Delegates the GroupCommunicationMessage to the correct 
        /// CommunicationGroupNetworkObserver.
        /// </summary>
        /// <param name="nsMessage"></param>
        public void OnNext(NsMessage<GroupCommunicationMessage> nsMessage)
        {
            if (nsMessage == null)
            {
                throw new ArgumentNullException("nsMessage");
            }

            try
            {
                GroupCommunicationMessage gcm = nsMessage.Data.First();
                _commGroupHandlers[gcm.GroupName].OnNext(gcm);
            }
            catch (InvalidOperationException)
            {
                LOGGER.Log(Level.Error, "Group Communication Network Handler received message with no data");
                throw;
            }
            catch (KeyNotFoundException)
            {
                LOGGER.Log(Level.Error, "Group Communication Network Handler received message for nonexistant group");
                throw;
            }
        }
Exemplo n.º 14
0
 public void OnNext(NsMessage <string> value)
 {
 }
Exemplo n.º 15
0
 public void OnNext(NsMessage <string> value)
 {
     _queue.Add(value.Data.First());
 }
Exemplo n.º 16
0
 /// <summary>
 /// This is called directly from the observer container with the registered IPEndpoint
 /// of the Task ID.
 /// </summary>
 public void OnNext(NsMessage <GeneralGroupCommunicationMessage> value)
 {
     Handle(value);
 }