/// <summary>
        /// Executes the <see cref="IQueryRequest"/> using HTTP POST to the Couchbase Server asynchronously.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of each row returned by the query.</typeparam>
        /// <param name="queryRequest">The query request.</param>
        /// <param name="cancellationToken">Token which can cancel the query.</param>
        /// <returns></returns>
        /// <remarks>The format for the querying is JSON</remarks>
        protected virtual async Task<IQueryResult<T>> ExecuteQueryAsync<T>(IQueryRequest queryRequest, CancellationToken cancellationToken)
        {
            var queryResult = new QueryResult<T>();

            FailureCountingUri baseUri;
            if (!TryGetQueryUri(out baseUri))
            {
                Log.Error(ExceptionUtil.EmptyUriTryingSubmitN1qlQuery);
                ProcessError(new InvalidOperationException(ExceptionUtil.EmptyUriTryingSubmitN1QlQuery), queryResult);
                return queryResult;
            }

            ApplyCredentials(queryRequest);

            using (var content = new StringContent(queryRequest.GetFormValuesAsJson(), System.Text.Encoding.UTF8, MediaType.Json))
            {
                try
                {
                    using (var timer = new QueryTimer(queryRequest, new CommonLogStore(Log), ClientConfiguration.EnableQueryTiming))
                    {
                        Log.Trace("Sending query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                        var request = await HttpClient.PostAsync(baseUri, content, cancellationToken).ContinueOnAnyContext();
                        using (var response = await request.Content.ReadAsStreamAsync().ContinueOnAnyContext())
                        {
                            queryResult = GetDataMapper(queryRequest).Map<QueryResultData<T>>(response).ToQueryResult();
                            queryResult.Success = queryResult.Status == QueryStatus.Success;
                            queryResult.HttpStatusCode = request.StatusCode;
                            Log.Trace("Received query cid{0}: {1}", queryResult.ClientContextId, queryResult.ToString());
                            timer.ClusterElapsedTime = queryResult.Metrics.ElaspedTime;
                        }
                    }
                    baseUri.ClearFailed();
                }
                catch (HttpRequestException e)
                {
                    Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    baseUri.IncrementFailed();
                    ProcessError(e, queryResult);
                    Log.Error(e);
                }
                catch (AggregateException ae)
                {
                    ae.Flatten().Handle(e =>
                    {
                        Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                        ProcessError(e, queryResult);
                        return true;
                    });
                }
                catch (Exception e)
                {
                    Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    Log.Info(e);
                    ProcessError(e, queryResult);
                }
            }

            return queryResult;
        }
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (ResponseStream != null)
     {
         ResponseStream.Dispose();
     }
     if (QueryTimer != null)
     {
         QueryTimer.Dispose();
     }
 }
Beispiel #3
0
        /// <summary>
        /// Executes the <see cref="IQueryRequest"/> using HTTP POST to the Couchbase Server asynchronously.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of each row returned by the query.</typeparam>
        /// <param name="queryRequest">The query request.</param>
        /// <returns></returns>
        /// <remarks>The format for the querying is JSON</remarks>
        protected virtual async Task <IQueryResult <T> > ExecuteQueryAsync <T>(IQueryRequest queryRequest)
        {
            ApplyCredentials(queryRequest);
            var baseUri     = ConfigContextBase.GetQueryUri();
            var queryResult = new QueryResult <T>();

            using (var content = new StringContent(queryRequest.GetFormValuesAsJson(), System.Text.Encoding.UTF8, MediaType.Json))
            {
                try
                {
                    using (var timer = new QueryTimer(queryRequest, new CommonLogStore(Log), ClientConfig.EnableQueryTiming))
                    {
                        Log.TraceFormat("Sending query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                        var request = await HttpClient.PostAsync(baseUri, content).ContinueOnAnyContext();

                        using (var response = await request.Content.ReadAsStreamAsync().ContinueOnAnyContext())
                        {
                            queryResult                = GetDataMapper(queryRequest).Map <QueryResultData <T> >(response).ToQueryResult();
                            queryResult.Success        = queryResult.Status == QueryStatus.Success;
                            queryResult.HttpStatusCode = request.StatusCode;
                            Log.TraceFormat("Received query cid{0}: {1}", queryResult.ClientContextId, queryResult.ToString());

                            timer.ClusterElapsedTime = queryResult.Metrics.ElaspedTime;
                        }
                    }
                    baseUri.ClearFailed();
                }
                catch (HttpRequestException e)
                {
                    Log.InfoFormat("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    baseUri.IncrementFailed();
                    ProcessError(e, queryResult);
                    Log.Error(e);
                }
                catch (AggregateException ae)
                {
                    ae.Flatten().Handle(e =>
                    {
                        Log.InfoFormat("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                        ProcessError(e, queryResult);
                        return(true);
                    });
                }
                catch (Exception e)
                {
                    Log.InfoFormat("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    Log.Info(e);
                    ProcessError(e, queryResult);
                }
            }

            return(queryResult);
        }
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (_reader != null)
     {
         _reader.Close(); // also closes underlying stream
         _reader = null;
     }
     if (QueryTimer != null)
     {
         QueryTimer.Dispose();
         QueryTimer = null;
     }
 }
        public void When_EnableQueryTiming_Is_True_And_LogLevel_Is_Not_Configured_Nothing_Is_Logged()
        {
            var queryRequest = new QueryRequest(Statement);
            var log = new FakeLog("mylogger", LogLevel.Off, true, true, true, LogDateFormat);
            using (var timer = new QueryTimer(queryRequest, new CommonLogStore(log), true))
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                timer.ClusterElapsedTime = ServerElapsedTime;
            }

            var logOutput = log.LogStore.ToString();
            Assert.IsEmpty(logOutput);
        }
        public void When_EnableQueryTiming_Is_True_And_LogLevel_Configured_QueryTiming_Is_Logged()
        {
            var queryRequest = new QueryRequest(Statement);
            var log = new FakeLog("mylogger", LogLevel.Debug, true, true, true, LogDateFormat);
            using (var timer = new QueryTimer(queryRequest, new CommonLogStore(log), true))
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(25));
                timer.ClusterElapsedTime = ServerElapsedTime;
            }

            var logOutput = log.LogStore.ToString();
            Assert.IsTrue(logOutput.Contains("[INFO]"));
            Assert.IsTrue(logOutput.Contains("Query Timing"));
            Assert.IsTrue(logOutput.Contains(ServerElapsedTime));
            Assert.IsTrue(logOutput.Contains(Statement));
        }
Beispiel #7
0
        /// <summary>
        /// Executes the <see cref="IQueryRequest"/> using HTTP POST to the Couchbase Server asynchronously.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of each row returned by the query.</typeparam>
        /// <param name="queryRequest">The query request.</param>
        /// <param name="cancellationToken">Token which can cancel the query.</param>
        /// <returns></returns>
        /// <remarks>The format for the querying is JSON</remarks>
        protected virtual async Task <IQueryResult <T> > ExecuteQueryAsync <T>(IQueryRequest queryRequest, CancellationToken cancellationToken)
        {
            var queryResult = new QueryResult <T>();

            if (!TryGetQueryUri(out var baseUri))
            {
                Log.Error(ExceptionUtil.EmptyUriTryingSubmitN1qlQuery);
                ProcessError(new InvalidOperationException(ExceptionUtil.EmptyUriTryingSubmitN1QlQuery), queryResult);
                return(queryResult);
            }

            ApplyCredentials(queryRequest);

            if (Log.IsDebugEnabled)
            {
                //need to remove the brackets or else string.format will fail in Log.Debug
                var req = queryRequest.ToString();
                Log.Debug(req.Replace("{", "").Replace("}", ""));
            }

            string body;

            using (ClientConfiguration.Tracer.BuildSpan(queryRequest, CouchbaseOperationNames.RequestEncoding).Start())
            {
                body = queryRequest.GetFormValuesAsJson();
            }

            using (var content = new StringContent(body, System.Text.Encoding.UTF8, MediaType.Json))
            {
                try
                {
                    using (var timer = new QueryTimer(queryRequest, new CommonLogStore(Log), ClientConfiguration.EnableQueryTiming))
                    {
                        Log.Trace("Sending query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);

                        HttpResponseMessage response;
                        using (ClientConfiguration.Tracer.BuildSpan(queryRequest, CouchbaseOperationNames.DispatchToServer).Start())
                        {
                            response = await HttpClient.PostAsync(baseUri, content, cancellationToken).ContinueOnAnyContext();
                        }

                        using (var span = ClientConfiguration.Tracer.BuildSpan(queryRequest, CouchbaseOperationNames.ResponseDecoding).Start())
                            using (var stream = await response.Content.ReadAsStreamAsync().ContinueOnAnyContext())
                            {
                                queryResult                = GetDataMapper(queryRequest).Map <QueryResultData <T> >(stream).ToQueryResult();
                                queryResult.Success        = queryResult.Status == QueryStatus.Success;
                                queryResult.HttpStatusCode = response.StatusCode;
                                Log.Trace("Received query cid{0}: {1}", queryResult.ClientContextId, queryResult.ToString());
                                timer.ClusterElapsedTime = queryResult.Metrics.ElaspedTime;

                                span.SetPeerLatencyTag(queryResult.Metrics.ElaspedTime);
                            }
                    }
                    baseUri.ClearFailed();
                }
                catch (HttpRequestException e)
                {
                    Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    baseUri.IncrementFailed();
                    ProcessError(e, queryResult);
                    Log.Error(e);
                }
                catch (AggregateException ae)
                {
                    ae.Flatten().Handle(e =>
                    {
                        Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                        ProcessError(e, queryResult);
                        return(true);
                    });
                }
                catch (Exception e)
                {
                    Log.Info("Failed query cid{0}: {1}", queryRequest.CurrentContextId, baseUri);
                    Log.Info(e);
                    ProcessError(e, queryResult);
                }
            }

            UpdateLastActivity();

            return(queryResult);
        }