Exemplo n.º 1
0
        private Queue <String> LoadUnexistentScripts(SocketReader reader, SocketWriter writer)
        {
            var loadQueue = new Queue <String>();

            // read results
            var result = RESPObject.Read(reader);
            var array  = result.Cast <RESPArray>();

            // if a script does not exists, send 'script load'
            for (int i = 0; i < array.Count; i++)
            {
                var found = array[i].Cast <RESPInteger>().Value != 0;
                if (!found)
                {
                    var digest = _procedures.Digests[i];
                    _logger.Info("Script with digest {0} not found, loading...", digest);
                    var load = GenerateLoadCommand(digest);
                    load.WriteTo(writer);
                    loadQueue.Enqueue(digest);
                }
            }

            writer.Flush();
            return(loadQueue);
        }
        protected override void ProcessResponse(RESPObject response)
        {
            if (response == null)
            {
                if (_current != null)
                {
                    _current.SetCancelled();
                    _current = null;
                }

                return;
            }

            if (_current == null && !_pending.TryDequeue(out _current))
            {
                throw new InvalidOperationException("Received command response but no token available.");
            }

            try
            {
                HandleResponseWithToken(response);
            }
            catch (OperationCanceledException)
            {
                _current.SetCancelled();
                throw;
            }
            catch (Exception ex)
            {
                _current.SetFaulted(ex);
                throw;
            }
        }
Exemplo n.º 3
0
        internal static Boolean Same(RESPObject item, String comparand)
        {
            Contract.Assert(item != null, "Item is null");
            Contract.Assert(item is RESPString, "Item is not RESPString");

            return(Same((RESPString)item, comparand));
        }
Exemplo n.º 4
0
        static void SetValue(String memberName, T instance, RESPObject obj, Setter <T> setter)
        {
            try
            {
                switch (obj.Header)
                {
                case RESPHeaders.Integer:
                    setter.NumericSetter(instance, obj.GetInt64());
                    break;

                case RESPHeaders.BulkString:
                case RESPHeaders.SimpleString:
                    setter.StringSetter(instance, obj.GetString());
                    break;

                case RESPHeaders.Error:
                    throw new RedisClientCommandException((RESPError)obj);

                default:
                    throw new RedisClientBindingException("The result includes a member of type '" + obj.GetType().Name + "', but that type cannot be bound to an object member.");
                }
            }
            catch (Exception ex)
            {
                throw new RedisClientBindingException(String.Format("Cannot set member '{0}'", memberName), ex);
            }
        }
Exemplo n.º 5
0
        public void HandleResponse(RESPObject response)
        {
            Contract.Assert(_tracker != null, "Subscription tracker is not set when calling RemoveChannelOperation.HandleResponse");
            Contract.Assert(response != null && response is RESPArray, "SubscriptionOperation cannot handle response: " + (response == null?"Null":response.GetType().Name));

            _tracker.Acknowledge((RESPArray)response);
        }
Exemplo n.º 6
0
        private Tuple <ICommandOperation, ISubscriptionOperation, RESPObject[]> Pack <T>(ExecutionPlan plan, T parameters)
            where T : class
        {
            var respCommand          = plan.Bind(parameters);
            var responsesPlaceholder = new RESPObject[respCommand.Length];

            ICommandOperation      commandOperation = null;
            ISubscriptionOperation subOp            = null;

            var hasSubscriptions = false;
            var hasCommands      = false;

            IdentifyOperationMainRoute(respCommand, ref hasCommands, ref hasSubscriptions);

            if (!hasCommands && !hasSubscriptions)
            {
                throw new RedisClientParsingException("The given RESP commands do not contain Redis commands.");
            }

            if (hasCommands)
            {
                commandOperation = new CommandOperation(respCommand, responsesPlaceholder, _procedures);
            }

            if (hasSubscriptions)
            {
                if (_subscriber == null)
                {
                    _subscriber = _subscribers.Provide();
                }
                subOp = new SubscriptionOperation(this, respCommand, responsesPlaceholder, _subscriber.Subscriptions);
            }

            return(new Tuple <ICommandOperation, ISubscriptionOperation, RESPObject[]>(commandOperation, subOp, responsesPlaceholder));
        }
Exemplo n.º 7
0
 static String GetPropertyName(RESPObject obj, Int32 index)
 {
     if (!RESPString.IsString(obj.Header))
     {
         throw new RedisClientBindingException("Element at index " + index + " must be an string in order to be a member name");
     }
     return(obj.GetString());
 }
Exemplo n.º 8
0
        internal RedisResultInspector(RESPObject response, Int32 lineNumber)
        {
            Contract.Assert(response != null, "Result instpector without response object.");
            Contract.Assert(lineNumber > 0, "Result inspectors start counting numbers from 1.");

            _response   = response;
            _lineNumber = lineNumber;
            RedisType   = GetRedisType();
        }
        public void HandleResponse(RESPObject response)
        {
            Contract.Assert(_tracker != null, "Subscription tracker is not set when calling RemoveChannelOperation.HandleResponse");

            var array = response.Cast <RESPArray>();

            _tracker.Acknowledge(array);
            IsCompleted = _tracker.IsCompleted;
        }
Exemplo n.º 10
0
 internal static Int64 GetInt64(this RESPObject obj)
 {
     if (obj.Header == RESPHeaders.Integer)
     {
         return(((RESPInteger)obj).Value);
     }
     else
     {
         throw new RedisClientCastException("Type '" + obj.GetType().Name + "' cannot be cast to 'Int64'");
     }
 }
Exemplo n.º 11
0
 internal static String GetString(this RESPObject obj)
 {
     if (RESPString.IsString(obj.Header))
     {
         return(obj.ToString());
     }
     else
     {
         throw new RedisClientCastException("Type '" + obj.GetType().Name + "' cannot be cast to 'String'");
     }
 }
Exemplo n.º 12
0
        internal Boolean IsMessage(RESPObject response, out RESPArray message)
        {
            message = null;

            if (response.Header != RESPHeaders.Array)
            {
                return(false);
            }

            message = response.Cast <RESPArray>();

            return(IsSubscriptionMessage(message.ElementAt <RESPBulkString>(0).Value.ToUpperInvariant()));
        }
 private void HandleResponseWithToken(RESPObject response)
 {
     _current.CommandOperation.HandleResponse(response);
     if (_current.CommandOperation.IsCompleted)
     {
         if (!_current.IsCancelled)
         {
             _connectionCancellation.Token.ThrowIfCancellationRequested();
             _current.SetCompleted();
         }
         _current = null;
     }
 }
        private void HandleResponseWithToken(RESPObject response)
        {
            Contract.Assert(_current.SubscriptionOperation != null, "A token without subscription reached the subscriber connection response handler.");

            if (!_current.SubscriptionOperation.IsCompleted)
            {
                _current.SubscriptionOperation.HandleResponse(response);
            }

            if (_current.SubscriptionOperation.IsCompleted)
            {
                _current.SetCompleted();
                _current = null;
            }
        }
Exemplo n.º 15
0
 private void ReadResults(SocketReader reader)
 {
     foreach (var command in _commands)
     {
         var response = RESPObject.Read(reader);
         _logger.Info(" <- Response for initialization command '{0}' is type '{1}'.", command.Header, response != null ? response.Header.ToString() : "<null>.");
         if (response == null)
         {
             throw new RedisClientSocketException("Initialization command did not return any response.");
         }
         if (response.Header == RESPHeaders.Error)
         {
             throw new RedisClientCommandException(response.Cast <RESPError>());
         }
     }
 }
Exemplo n.º 16
0
 internal static Double AsDouble(this RESPObject obj)
 {
     if (RESPString.IsString(obj.Header))
     {
         var val = obj.ToString();
         return(String.IsNullOrWhiteSpace(val) ? 0 : Double.Parse(val, RESPObject.FormatInfo));
     }
     else if (obj.Header == RESPHeaders.Integer)
     {
         return(((RESPInteger)obj).Value);
     }
     else
     {
         throw new RedisClientCastException("Type '" + obj.GetType().Name + "' cannot be formatted as 'Double'");
     }
 }
Exemplo n.º 17
0
        internal static TRESP Cast <TRESP>(this RESPObject obj)
            where TRESP : RESPObject
        {
            TRESP value = obj as TRESP;

            if (value == null)
            {
                if (obj.Header == RESPHeaders.Error)
                {
                    throw new RedisClientCommandException((RESPError)obj);
                }

                throw new RedisClientCastException("Object '" + obj.GetType().Name + "' cannot be casted to '" + typeof(TRESP).Name + "'");
            }
            return(value);
        }
Exemplo n.º 18
0
        private async Task ReadAsync(SocketReader reader)
        {
            try
            {
                while (!_connectionCancellation.IsCancellationRequested)
                {
                    _logger.Debug("{0} listening...", _code);
                    var resp = await RESPObject.ReadAsync(reader, _connectionCancellation.Token).ConfigureAwait(false);

                    _logger.Debug("{0} Received response of type {1}.", _code, resp.Header);
                    RegisterActivity();
                    ProcessResponse(resp);
                }
            }
            catch (OperationCanceledException) { }
            catch (ObjectDisposedException) { }
            catch (IOException) { }
        }
Exemplo n.º 19
0
        static int ZipUpResults(RESPObject[] results, Int32 index, RESPObject result)
        {
            var array = result.Cast <RESPArray>();

            results[index] = RESPSimpleString.OK;
            index--;
            var arrayIndex = array.Count - 1;

            while (index >= 0 && arrayIndex >= 0)
            {
                var element = results[index];
                if (RESPString.IsString(element.Header) && RESPString.Same(element, "QUEUED"))
                {
                    results[index] = array[arrayIndex];
                    arrayIndex--;
                }

                index--;
            }
            return(index);
        }
Exemplo n.º 20
0
        private void ValidateScriptLoadingResults(SocketReader reader, Queue <String> loadQueue)
        {
            // for loaded scripts, read responses and ensure
            // returned SHA1 fits the locally calculated one
            while (loadQueue.Any())
            {
                var digest = loadQueue.Dequeue();
                var result = RESPObject.Read(reader);

                if (result == null)
                {
                    throw new RedisClientParsingException("Cannot read responses.");
                }

                try
                {
                    var resultDigest = result.Cast <RESPString>().Value;
                    if (digest != resultDigest)
                    {
                        throw new RedisClientParsingException("Script digest differs.");
                    }

                    _logger.Info("Script with digest {0} loaded.", digest);
                }
                catch (RedisClientException rcex)
                {
                    _logger.Error(rcex, "Script with digest {0} failed to load.", digest);
                    _procedures.SetFaulted(digest, rcex);
                }
                catch (Exception cmdEx)
                {
                    _logger.Error(cmdEx, "Script with digest {0} failed to load.", digest);
                    _procedures.SetFaulted(digest, new RedisClientParsingException("Error validating script digest", cmdEx));
                }
            }
        }
Exemplo n.º 21
0
        public void HandleResponse(RESPObject response)
        {
            Contract.Assert(response.ToString() == "OK", "DiscardTransactionOperation handler trying to handle a non OK response. ");

            IsCompleted = true;
        }
Exemplo n.º 22
0
 internal static String AsString(this RESPObject obj)
 {
     return(obj.ToString());
 }
Exemplo n.º 23
0
        public void HandleResponse(RESPObject response)
        {
            Contract.Assert(response.ToString() == "PONG", "PingCommanderOperation handler trying to work out a non-ping response. ");

            IsCompleted = true;
        }
Exemplo n.º 24
0
 public void HandleResponse(RESPObject response)
 {
     _responses[_nextResponse] = response;
     PointToNextResponse();
 }
Exemplo n.º 25
0
 protected abstract void ProcessResponse(RESPObject response);