Exemple #1
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 (TaskCanceledException)
                {
                    var operationContext = new OperationContext("n1ql", queryRequest.CurrentContextId)
                    {
                        RemoteEndpoint = baseUri.Authority
                    };

                    Log.Info(operationContext.ToString());
                }
                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);
        }
        /// <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);

            if (Log.IsDebugEnabled)
            {
                Log.Debug(queryRequest.ToString());
            }

            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);
        }