Esempio n. 1
0
        public void ExpectType(RedisMessage expectedType)
        {
            RedisMessage type = ReadType();

            if ((int)type == -1)
            {
                throw new EndOfStreamException($"Unexpected end of stream: expected type '{expectedType}'");
            }
            if (type != expectedType)
            {
                throw new RedisProtocolException($"Unexpected response type:{type} (expecting {expectedType})");
            }
        }
        public void ExpectType(RedisMessage expectedType)
        {
            RedisMessage type = ReadType();

            if ((int)type == -1)
            {
                throw new EndOfStreamException("Unexpected end of stream; expected type '" + expectedType + "'");
            }
            if (type != expectedType)
            {
                throw new RedisProtocolException(String.Format("Unexpected response type: {0} (expecting {1})", type, expectedType));
            }
        }
Esempio n. 3
0
        public void SendMessage(RedisChannels channel, RedisMessage message = null)
        {
            message = message ?? new DefaultRedisMessage();


#if log
            Console.WriteLine("Sending Message: " + channel + "    " + str);
            Console.WriteLine();
#endif

            database.ListLeftPush($"{channel}-bl", ObjectToByteArray(message));
            subscriber.Publish(channel.ToString(), "");
        }
Esempio n. 4
0
        public void ExpectType(RedisMessage expectedType)
        {
            RedisMessage type = ReadType();

            if ((int)type == -1)
            {
                var alldata = _io.ReadAll();
                try { _io.Dispose(); } catch { }
                throw new EndOfStreamException($"Unexpected end of stream; expected type '{expectedType}'; data = '{Encoding.UTF8.GetString(alldata)}'");
            }
            if (type != expectedType)
            {
                throw new RedisProtocolException($"Unexpected response type: {type} (expecting {expectedType})");
            }
        }
Esempio n. 5
0
            public override string Parse(RedisReader reader)
            {
                RedisMessage type = reader.ReadType();

                if ((int)type == -1)
                {
                    return(String.Empty);
                }
                else if (type == RedisMessage.Error)
                {
                    throw new RedisException(reader.ReadStatus(false));
                }

                throw new RedisProtocolException("Unexpected type: " + type);
            }
Esempio n. 6
0
        private static string ParseStream(Stream stream)
        {
            RedisMessage type = RedisReader.ReadType(stream);

            if (type == RedisMessage.Status)
            {
                return(RedisReader.ReadStatus(stream, false));
            }

            object[] result = RedisReader.ReadMultiBulk(stream, false);
            if (result != null)
            {
                throw new RedisProtocolException("Expecting null MULTI BULK response. Received: " + result.ToString());
            }
            return(null);
        }
Esempio n. 7
0
        public Task <RedisMessage> AskQuestion(RedisChannels channelEnum, RedisMessage message = null)
        {
            var channel = channelEnum.ToString();

            message = message ?? new DefaultRedisMessage();


#if log
            Console.WriteLine("Asking Question: " + channel + "    " + str);
            Console.WriteLine();
#endif
            database.ListLeftPush($"{channel}-bl", ObjectToByteArray(message));
            subscriber.Publish(channel, "");

            return(lateTaskManager.Build(message.Guid));
        }
Esempio n. 8
0
            public override string Parse(RedisReader reader)
            {
                RedisMessage type = reader.ReadType();

                if (type == RedisMessage.Status)
                {
                    return(reader.ReadStatus(false));
                }

                object[] result = reader.ReadMultiBulk(false);
                if (result != null && result.Length > 0)
                {
                    throw new RedisProtocolException("Expecting null MULTI BULK response for command '" + this.Command + "'. Received: " + String.Join(", ", result));
                }

                return(null);
            }
Esempio n. 9
0
 public override string Parse(RedisReader reader)
 {
     if (IsNullable)
     {
         RedisMessage type = reader.ReadType();
         if (type == RedisMessage.Bulk)
         {
             return(reader.ReadBulkString(false));
         }
         reader.ReadMultiBulk(false);
         return(null);
     }
     else
     {
         return(reader.ReadBulkString());
     }
 }
Esempio n. 10
0
            public override string Parse(RedisReader reader)
            {
                RedisMessage type = reader.ReadType();

                if (type == RedisMessage.Status)
                {
                    return(reader.ReadStatus(false));
                }

                object[] result = reader.ReadMultiBulk(false);
                if (result != null)
                {
                    throw new RedisProtocolException("Expecting null MULTI BULK response. Received: " + result.ToString());
                }

                return(null);
            }
Esempio n. 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="serverUuid"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool SendDataToServer(Guid serverUuid, RedisMessage message)
 {
     if (message == null)
     {
         return(true);
     }
     message.ServerUUID = ServerUuid;
     if (serverUuid == ServerUuid)
     {
         if (message.IsFromRedis)
         {
             return(false);
         }
         OnRedisMessageComing(message);
         return(true);
     }
     redisClient.PublisMessage(serverUuid.ToString("n"), message.Serialize());
     return(true);
 }
Esempio n. 12
0
        /// <summary>
        /// Read response from server into a stream
        /// </summary>
        /// <param name="destination">The stream that will contain the contents of the server response.</param>
        /// <param name="bufferSize">Size of internal buffer used to copy streams</param>
        public void Read(Stream destination, int bufferSize)
        {
            using (new ActivityTracer("Read response to stream"))
            {
                ActivityTracer.Verbose("Buffer size is {0}", bufferSize);
                RedisMessage type = RedisReader.ReadType(_stream);

                if (type == RedisMessage.Error)
                {
                    throw new RedisException(RedisReader.ReadStatus(_stream, false));
                }

                if (type != RedisMessage.Bulk)
                {
                    throw new InvalidOperationException("Cannot stream from non-bulk response. Received: " + type);
                }

                RedisReader.ReadBulk(_stream, destination, bufferSize, false);
            }
        }
        public void TestLoggingLine_MockDispatcher()
        {
            var mock = new Mock <IMessageDispatcher>();

            RedisMessage msg = new RedisMessage("", "");

            codeHooks = new CodeHooks(mock.Object);

            mock.Setup(x => x.DispatchMessage(It.IsAny <RedisMessage>())).Callback((RedisMessage pmsg) => msg = pmsg);

            codeHooks.LogLineRun(System.Guid.NewGuid(), 95, "testDate");

            mock.Verify(x => x.DispatchMessage(It.IsAny <RedisMessage>()), Times.Once());

            string tid = Thread.CurrentThread.ManagedThreadId.ToString();

            Assert.IsTrue(msg.GetKey().Contains("CODE_RUN_EVENTS"));
            Assert.IsTrue(msg.GetMessage().Contains("95"));
            Assert.IsTrue(msg.GetMessage().Contains("testDate"));
            Assert.IsTrue(msg.GetMessage().Contains("LINE_EXEC"));
            Assert.IsTrue(msg.GetMessage().Contains(tid));
        }
Esempio n. 14
0
        public override string Parse(RedisReader reader)
        {
            if (IsEmpty)
            {
                RedisMessage type = reader.ReadType();
                if ((int)type == -1)
                {
                    return(string.Empty);
                }
                else if (type == RedisMessage.Error)
                {
                    throw new RedisException(reader.ReadStatus(false));
                }

                throw new RedisProtocolException($"Unexpected type: {type}");
            }
            else if (IsNullable)
            {
                RedisMessage type = reader.ReadType();
                if (type == RedisMessage.Status)
                {
                    return(reader.ReadStatus(false));
                }

                object[] result = reader.ReadMultiBulk(false);
                if (result != null)
                {
                    throw new RedisProtocolException($"Expecting null MULTI BULK response. Received: {result.ToString()}");
                }

                return(null);
            }
            else
            {
                return(reader.ReadStatus());
            }
        }
        public void TestRegesteringProject()
        {
            SourceCodeInfo sourceCode = new SourceCodeInfo(GitTests.RepoPath);

            sourceCode.AddCodeFile("ClassA.cs");

            var          mock = new Mock <IMessageDispatcher>();
            RedisMessage msg  = new RedisMessage("", "");

            mock.Setup(x => x.DispatchMessage(It.IsAny <RedisMessage>())).Callback((RedisMessage pmsg) => msg = pmsg);
            var codeHooks = new CodeHooks(mock.Object);

            CodeRegisterer codeRegisterer = new CodeRegisterer(codeHooks);

            codeRegisterer.SendCodeContentsToServer(sourceCode);


            mock.Verify(x => x.DispatchMessage(It.IsAny <RedisMessage>()), Times.AtLeast(1));

            Assert.IsTrue(msg.GetKey().Contains("CODE_RUN_EVENTS"));
            Assert.IsTrue(msg.GetMessage().Contains("ADD_SOURCE_FILE"));
            Assert.IsTrue(msg.GetMessage().Contains("ClassA.cs"));
            Assert.IsTrue(msg.GetMessage().Contains("MethodA_1"));
        }
Esempio n. 16
0
        public void ExpectType(RedisMessage expectedType)
        {
            RedisMessage type = ReadType();

            if ((int)type == -1)
            {
                using (var ms = new MemoryStream())
                {
                    var ns = _io.NetworkStream as NetworkStream;
                    if (ns != null)
                    {
                        try
                        {
                            var data = new byte[1024];
                            while (ns.DataAvailable && ns.CanRead)
                            {
                                var numBytesRead = ns.Read(data, 0, data.Length);
                                if (numBytesRead <= 0)
                                {
                                    break;
                                }
                                ms.Write(data, 0, numBytesRead);
                            }
                        }
                        catch { }
                    }

                    try { _stream.Close(); } catch { }
                    throw new EndOfStreamException($"Unexpected end of stream; expected type '{expectedType}'; data = '{Encoding.UTF8.GetString(ms.ToArray())}'");
                }
            }
            if (type != expectedType)
            {
                throw new RedisProtocolException($"Unexpected response type: {type} (expecting {expectedType})");
            }
        }
    void __actionDataChannel()
    {
        string[] a;
        byte[]   buf;
        string   s;
        int      len;
        int      pos;

        while (true)
        {
            if (__queue.Count == 0)
            {
                __event.WaitOne();
            }

            len = 0;
            pos = 0;

            lock (__queue) buf = __queue.Dequeue();
            len = buf.Length;
            if (buf.Length > BUFFER_HEADER_MAX_SIZE)
            {
                len = BUFFER_HEADER_MAX_SIZE;
            }

            s = Encoding.ASCII.GetString(buf, 0, len);
            a = s.Split(new string[] { MESSAGE_SPLIT_END }, StringSplitOptions.None);
            if (a.Length > 2)
            {
                for (int i = 0; i < a.Length - 1; i++)
                {
                    pos += a[i].Length + MESSAGE_SPLIT_END.Length;
                }
                pos += a[a.Length - 1].Split('\r')[0].Length + 2;

                if (pos <= buf.Length - 2)
                {
                    len = buf.Length - pos - 2;
                    byte[] bs = new byte[len];
                    for (int i = pos; i < buf.Length - 2; i++)
                    {
                        bs[i - pos] = buf[i];
                    }

                    a = a[a.Length - 2].Split(new string[] { MESSAGE_SPLIT_BEGIN }, StringSplitOptions.None);
                    string channel = a[a.Length - 1];

                    RedisMessage                 noti;
                    Action <RedisMessage>        call = null;
                    IDictionary <string, object> para = null;

                    if (!string.IsNullOrEmpty(channel))
                    {
                        string channelKey = "<{" + channel.ToUpper() + "}>";
                        if (channelKey != __MONITOR_CHANNEL)
                        {
                            lock (__channels) if (__channels.ContainsKey(channelKey))
                                {
                                    __channels.TryGetValue(channelKey, out call);
                                }
                            lock (__paramenters) if (__paramenters.ContainsKey(channelKey))
                                {
                                    __paramenters.TryGetValue(channelKey, out para);
                                }
                        }

                        noti = new RedisMessage(channel, bs, para);

                        if (call != null)
                        {
                            var ta = new Thread(new ParameterizedThreadStart((o) =>
                            {
                                lock (call)
                                    call((RedisMessage)o);
                            }));
                            ta.IsBackground = true;
                            ta.Start(noti);
                        }

                        if (__actionMonitor != null)
                        {
                            var tm = new Thread(new ParameterizedThreadStart((o) =>
                            {
                                lock (__lockMonitor)
                                    __actionMonitor((RedisMessage)o);
                            }));
                            tm.IsBackground = true;
                            tm.Start(noti);
                        }
                    }
                }
            }
        }
    }
        public void Create_Null_Message_Expired_True()
        {
            var test = new RedisMessage("1", null, true);

            Assert.True(test.Expired);
        }
Esempio n. 19
0
 public static void ExpectType(Stream stream, RedisMessage expectedType)
 {
     RedisMessage type = ReadType(stream);
     if (type != expectedType)
         throw new RedisProtocolException(String.Format("Unexpected response type: {0} (expecting {1})", type, expectedType));
 }
        public void Create_Null_Message_OK()
        {
            var test = new RedisMessage(null, null, false);

            Assert.Null(test.Message);
        }
        private void SendImpl(IEnumerator<IGrouping<string, Message>> enumerator, TaskCompletionSource<object> taskCompletionSource)
        {
            if (!enumerator.MoveNext()) {
                taskCompletionSource.TrySetResult(null);
            }
            else {
                IGrouping<string, Message> group = enumerator.Current;

                // Get the channel index we're going to use for this message
                int index = Math.Abs(group.Key.GetHashCode()) % _keys.Length;

                string key = _keys[index];

                // Increment the channel number
                _connection.Strings.Increment(_db, key)
                                   .Then((id, k) => {
                                       var message = new RedisMessage(id, group.ToArray());

                                       return _connection.Publish(k, message.GetBytes());
                                   }, key)
                                   .Then((enumer, tcs) => SendImpl(enumer, tcs), enumerator, taskCompletionSource)
                                   .ContinueWithNotComplete(taskCompletionSource);
            }
        }
Esempio n. 22
0
 public async Task PublishAsync(RedisMessage msg)
 {
     await _subscriber.PublishAsync(msg.Topic, msg.Payload);
 }
Esempio n. 23
0
 public void ExpectType(RedisMessage expectedType)
 {
     RedisMessage type = ReadType();
     if ((int)type == -1)
         throw new EndOfStreamException("Unexpected end of stream; expected type '" + expectedType + "'");
     if (type != expectedType)
         throw new RedisProtocolException(String.Format("Unexpected response type: {0} (expecting {1})", type, expectedType));
 }
        public void Create_Null_Message_Expired_False()
        {
            var test = new RedisMessage("1", null, false);

            Assert.False(test.Expired);
        }
Esempio n. 25
0
 private static void OnRedisMessageComing(RedisMessage message)
 {
     message.IsFromRedis = true;
     RedisMessageComing?.Invoke(null, message);
 }
Esempio n. 26
0
        /// <summary>
        /// Read server response bytes into buffer and advance the server response stream (requires Buffering=true)
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        public int Read(byte[] buffer, int offset, int count)
        {
            using (new ActivityTracer("Read response to buffer"))
            {
                ActivityTracer.Verbose("Offset={0}; Count={1}", offset, count);
                if (offset > buffer.Length || count > buffer.Length)
                {
                    throw new InvalidOperationException("Buffer offset or count is larger than buffer");
                }

                if (!Buffering)
                {
                    ActivityTracer.Verbose("Not buffering; zeroing out buffer");
                    for (int i = offset; i < count; i++)
                    {
                        buffer[i] = 0;
                    }
                    return(0);
                }

                if (_bytesRemaining == 0)
                {
                    RedisMessage type = RedisReader.ReadType(_stream);

                    if (type == RedisMessage.Error)
                    {
                        throw new RedisException(RedisReader.ReadStatus(_stream, false));
                    }

                    if (type != RedisMessage.Bulk)
                    {
                        throw new InvalidOperationException("Cannot buffer from non-bulk response. Received: " + type);
                    }

                    _bytesRemaining = RedisReader.ReadInt(_stream, false);
                }

                ActivityTracer.Verbose("Bytes remaining: {0}", _bytesRemaining);

                int bytes_to_read = count;
                if (bytes_to_read > _bytesRemaining)
                {
                    bytes_to_read = (int)_bytesRemaining;
                }

                int bytes_read = 0;
                while (bytes_read < bytes_to_read)
                {
                    bytes_read += _stream.Read(buffer, offset + bytes_read, bytes_to_read - bytes_read);
                }

                _bytesRemaining -= bytes_read;

                if (_bytesRemaining == 0)
                {
                    RedisReader.ReadCRLF(_stream);
                    Buffering = false;
                }

                return(bytes_read);
            }
        }