예제 #1
0
        /// <summary>
        /// Executes a <see cref="IViewQuery"/> asynchronously against a View.
        /// </summary>
        /// <typeparam name="T">The Type parameter of the result returned by the query.</typeparam>
        /// <param name="query">The <see cref="IViewQuery"/> to execute on.</param>
        /// <returns>A <see cref="Task{T}"/> that can be awaited on for the results.</returns>
        public override async Task <IViewResult <T> > ExecuteAsync <T>(IViewQueryable query)
        {
            var uri        = query.RawUri();
            var viewResult = new StreamingViewResult <T>();

            try
            {
                var response = await HttpClient.GetAsync(uri).ContinueOnAnyContext();

                viewResult = new StreamingViewResult <T>(
                    response.IsSuccessStatusCode,
                    response.StatusCode,
                    Success,
                    await response.Content.ReadAsStreamAsync().ContinueOnAnyContext()
                    );
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e =>
                {
                    ProcessError(e, viewResult);
                    Log.Error(uri.ToString(), e);
                    return(true);
                });
            }
            catch (TaskCanceledException e)
            {
                const string error = "The request has timed out.";
                ProcessError(e, error, viewResult);
                Log.Error(uri.ToString(), e);
            }
            return(viewResult);
        }
예제 #2
0
        /// <summary>
        /// Executes a <see cref="IViewQuery"/> asynchronously against a View.
        /// </summary>
        /// <typeparam name="T">The Type parameter of the result returned by the query.</typeparam>
        /// <param name="query">The <see cref="IViewQuery"/> to execute on.</param>
        /// <returns>A <see cref="Task{T}"/> that can be awaited on for the results.</returns>
        public override async Task <IViewResult <T> > ExecuteAsync <T>(IViewQueryable query)
        {
            var uri        = query.RawUri();
            var viewResult = new StreamingViewResult <T>();
            var body       = query.CreateRequestBody();

            try
            {
                Log.Debug("Sending view request to: {0}", uri.ToString());

                var content  = new StringContent(body, Encoding.UTF8, MediaType.Json);
                var response = await HttpClient.PostAsync(uri, content).ContinueOnAnyContext();

                if (response.IsSuccessStatusCode)
                {
                    viewResult = new StreamingViewResult <T>(
                        response.IsSuccessStatusCode,
                        response.StatusCode,
                        Success,
                        await response.Content.ReadAsStreamAsync().ContinueOnAnyContext()
                        );
                }
                else
                {
                    viewResult = new StreamingViewResult <T>
                    {
                        Success    = false,
                        StatusCode = response.StatusCode,
                        Message    = response.ReasonPhrase
                    };
                }
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e =>
                {
                    ProcessError(e, viewResult);
                    Log.Error(uri.ToString(), e);
                    return(true);
                });
            }
            catch (TaskCanceledException e)
            {
                const string error = "The request has timed out.";
                ProcessError(e, error, viewResult);
                Log.Error(uri.ToString(), e);
            }
            catch (HttpRequestException e)
            {
                ProcessError(e, viewResult);
                Log.Error(uri.ToString(), e);
            }

            UpdateLastActivity();

            return(viewResult);
        }
예제 #3
0
        public async Task <IViewResult <TKey, TValue> > ExecuteAsync <TKey, TValue>(IViewQuery query)
        {
            using var rootSpan = _tracer.RootSpan(RequestTracing.ServiceIdentifier.View, OperationNames.ViewQuery)
                                 .WithTag(CouchbaseTags.Service, RequestTracing.ServiceIdentifier.View)
                                 .WithLocalAddress();

            using var encodingSpan = rootSpan.StartPayloadEncoding();
            var uri = query.RawUri();

            rootSpan.WithRemoteAddress(uri);

            ViewResultBase <TKey, TValue> viewResult;

            var body = query.CreateRequestBody();

            try
            {
                _logger.LogDebug("Sending view request to: {uri}", _redactor.SystemData(uri));
                var content = new StringContent(body, Encoding.UTF8, MediaType.Json);
                encodingSpan.Dispose();

                using var dispatchSpan = rootSpan.StartDispatch();
                var response = await HttpClient.PostAsync(uri, content).ConfigureAwait(false);

                dispatchSpan.Dispose();

                var serializer = query.Serializer ?? _serializer;
                if (response.IsSuccessStatusCode)
                {
                    if (serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);
                }
                else
                {
                    if (serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);

                    if (viewResult.ShouldRetry())
                    {
                        UpdateLastActivity();
                        return(viewResult);
                    }

                    if (viewResult.ViewNotFound())
                    {
                        throw new ViewNotFoundException(uri.ToString())
                              {
                                  Context = new ViewContextError
                                  {
                                      DesignDocumentName = query.DesignDocName,
                                      ViewName           = query.ViewName,
                                      ClientContextId    = query.ClientContextId,
                                      HttpStatus         = response.StatusCode,
                                      Errors             = viewResult.Message
                                  }
                              };
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                _logger.LogDebug(LoggingEvents.ViewEvent, e, "View request timeout.");
                throw new AmbiguousTimeoutException("The view query was timed out via the Token.", e)
                      {
                          Context = new ViewContextError
                          {
                              DesignDocumentName = query.DesignDocName,
                              ViewName           = query.ViewName,
                              ClientContextId    = query.ClientContextId,
                              HttpStatus         = HttpStatusCode.RequestTimeout
                          }
                      };
            }
            catch (HttpRequestException e)
            {
                _logger.LogDebug(LoggingEvents.QueryEvent, e, "View request cancelled.");
                throw new RequestCanceledException("The view query was canceled.", e)
                      {
                          Context = new ViewContextError
                          {
                              DesignDocumentName = query.DesignDocName,
                              ViewName           = query.ViewName,
                              ClientContextId    = query.ClientContextId,
                              HttpStatus         = HttpStatusCode.RequestTimeout
                          }
                      };
            }

            UpdateLastActivity();
            return(viewResult);
        }
예제 #4
0
        public async Task <IViewResult <TKey, TValue> > ExecuteAsync <TKey, TValue>(IViewQuery query)
        {
            using var rootSpan = RootSpan(OuterRequestSpans.ServiceSpan.ViewQuery, query);
            rootSpan.WithLocalAddress()
            .WithOperation(query);

            var uri = query.RawUri();

            rootSpan.WithRemoteAddress(uri);

            using var encodingSpan = rootSpan.EncodingSpan();

            ViewResultBase <TKey, TValue> viewResult;

            var body = query.CreateRequestBody();

            try
            {
                _logger.LogDebug("Sending view request to: {uri}", _redactor.SystemData(uri));
                var content = new StringContent(body, Encoding.UTF8, MediaType.Json);
                encodingSpan.Dispose();

                using var dispatchSpan = rootSpan.DispatchSpan(query);

                using var httpClient = CreateHttpClient();
                // set timeout to infinite so we can stream results without the connection
                // closing part way through
                httpClient.Timeout = Timeout.InfiniteTimeSpan;

                var response = await httpClient.PostAsync(uri, content).ConfigureAwait(false);

                dispatchSpan.Dispose();

                var serializer = query.Serializer ?? _serializer;
                if (response.IsSuccessStatusCode)
                {
                    if (serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);
                }
                else
                {
                    if (serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);

                    if (viewResult.ShouldRetry())
                    {
                        viewResult.NoRetryException = new CouchbaseException()
                        {
                            Context = new ViewContextError
                            {
                                DesignDocumentName = query.DesignDocName,
                                ViewName           = query.ViewName,
                                ClientContextId    = query.ClientContextId,
                                HttpStatus         = response.StatusCode,
                                Errors             = viewResult.Message
                            }
                        };
                        UpdateLastActivity();
                        return(viewResult);
                    }

                    if (viewResult.ViewNotFound())
                    {
                        throw new ViewNotFoundException("The queried view is not found on the server.")
                              {
                                  Context = new ViewContextError
                                  {
                                      DesignDocumentName = query.DesignDocName,
                                      ViewName           = query.ViewName,
                                      ClientContextId    = query.ClientContextId,
                                      HttpStatus         = response.StatusCode,
                                      Errors             = viewResult.Message
                                  }
                              };
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                //treat as an orphaned response
                rootSpan.LogOrphaned();

                _logger.LogDebug(LoggingEvents.ViewEvent, e, "View request timeout.");
                throw new AmbiguousTimeoutException("The view query was timed out via the Token.", e)
                      {
                          Context = new ViewContextError
                          {
                              DesignDocumentName = query.DesignDocName,
                              ViewName           = query.ViewName,
                              ClientContextId    = query.ClientContextId,
                              HttpStatus         = HttpStatusCode.RequestTimeout
                          }
                      };
            }
            catch (HttpRequestException e)
            {
                //treat as an orphaned response
                rootSpan.LogOrphaned();

                _logger.LogDebug(LoggingEvents.QueryEvent, e, "View request cancelled.");
                throw new RequestCanceledException("The view query was canceled.", e)
                      {
                          Context = new ViewContextError
                          {
                              DesignDocumentName = query.DesignDocName,
                              ViewName           = query.ViewName,
                              ClientContextId    = query.ClientContextId,
                              HttpStatus         = HttpStatusCode.RequestTimeout
                          }
                      };
            }

            UpdateLastActivity();
            return(viewResult);
        }
예제 #5
0
        /// <summary>
        /// Executes a <see cref="IViewQuery"/> asynchronously against a View.
        /// </summary>
        /// <typeparam name="T">The Type parameter of the result returned by the query.</typeparam>
        /// <param name="query">The <see cref="IViewQuery"/> to execute on.</param>
        /// <returns>A <see cref="Task{T}"/> that can be awaited on for the results.</returns>
        public override async Task <IViewResult <T> > ExecuteAsync <T>(IViewQueryable query)
        {
            var uri        = query.RawUri();
            var viewResult = new StreamingViewResult <T>();

            string body;

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

            try
            {
                Log.Debug("Sending view request to: {0}", uri.ToString());

                var content = new StringContent(body, Encoding.UTF8, MediaType.Json);

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

                if (response.IsSuccessStatusCode)
                {
                    viewResult = new StreamingViewResult <T>(
                        response.IsSuccessStatusCode,
                        response.StatusCode,
                        Success,
                        await response.Content.ReadAsStreamAsync().ContinueOnAnyContext(),
                        ClientConfiguration.Tracer.BuildSpan(query, CouchbaseOperationNames.ResponseDecoding).Start()
                        );
                }
                else
                {
                    viewResult = new StreamingViewResult <T>
                    {
                        Success    = false,
                        StatusCode = response.StatusCode,
                        Message    = response.ReasonPhrase
                    };
                }
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e =>
                {
                    ProcessError(e, viewResult);
                    Log.Error(uri.ToString(), e);
                    return(true);
                });
            }
            catch (OperationCanceledException e)
            {
                var operationContext = OperationContext.CreateViewContext(query.BucketName, uri?.Authority);
                if (_viewTimeout.HasValue)
                {
                    operationContext.TimeoutMicroseconds = (uint)_viewTimeout.Value;
                }

                ProcessError(e, operationContext.ToString(), viewResult);
                Log.Error(uri.ToString(), e);
            }
            catch (HttpRequestException e)
            {
                ProcessError(e, viewResult);
                Log.Error(uri.ToString(), e);
            }

            UpdateLastActivity();

            return(viewResult);
        }
예제 #6
0
        /// <inheritdoc />
        public async Task <IViewResult <TKey, TValue> > ExecuteAsync <TKey, TValue>(IViewQueryable query)
        {
            var uri = query.RawUri();
            ViewResultBase <TKey, TValue> viewResult;

            var body = query.CreateRequestBody();

            try
            {
                Log.LogDebug("Sending view request to: {0}", uri.ToString());
                var content  = new StringContent(body, Encoding.UTF8, MediaType.Json);
                var response = await HttpClient.PostAsync(uri, content).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    if (_serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            Success,
                            await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
                            _serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);
                }
                else
                {
                    if (_serializer is IStreamingTypeDeserializer streamingTypeDeserializer)
                    {
                        viewResult = new StreamingViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            streamingTypeDeserializer
                            );
                    }
                    else
                    {
                        viewResult = new BlockViewResult <TKey, TValue>(
                            response.StatusCode,
                            await response.Content.ReadAsStringAsync().ConfigureAwait(false),
                            _serializer
                            );
                    }

                    await viewResult.InitializeAsync().ConfigureAwait(false);

                    if (viewResult.ShouldRetry())
                    {
                        UpdateLastActivity();
                        return(viewResult);
                    }

                    if (viewResult.ViewNotFound())
                    {
                        throw new ViewNotFoundException(uri.ToString());
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                Log.LogDebug(LoggingEvents.ViewEvent, e, "View request timeout.");
                throw new AmbiguousTimeoutException("The view query was timed out via the Token.", e);
            }
            catch (HttpRequestException e)
            {
                Log.LogDebug(LoggingEvents.QueryEvent, e, "View request cancelled.");
                throw new RequestCanceledException("The view query was canceled.", e);
            }

            UpdateLastActivity();
            return(viewResult);
        }