Exemplo n.º 1
0
 internal CouchbaseHttpClient(ConfigContextBase context)
     : this(CreateClientHandler(context.ClientConfig, context.BucketConfig))
 {
     DefaultRequestHeaders.ExpectContinue = context.ClientConfig.Expect100Continue;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Executes a <see cref="IFtsQuery" /> request including any <see cref="ISearchParams" /> parameters asynchronously.
        /// </summary>
        /// <returns>A <see cref="ISearchQueryResult"/> wrapped in a <see cref="Task"/> for awaiting on.</returns>
        public async Task <ISearchQueryResult> QueryAsync(SearchQuery searchQuery)
        {
            var searchResult = new SearchQueryResult();
            var baseUri      = ConfigContextBase.GetSearchUri();
            var requestUri   = new Uri(baseUri, searchQuery.RelativeUri());

            string searchBody;

            using (ClientConfiguration.Tracer.BuildSpan(searchQuery, CouchbaseOperationNames.RequestEncoding).Start())
            {
                searchBody = searchQuery.ToJson();
            }

            try
            {
                using (var content = new StringContent(searchBody, Encoding.UTF8, MediaType.Json))
                {
                    HttpResponseMessage response;
                    using (ClientConfiguration.Tracer.BuildSpan(searchQuery, CouchbaseOperationNames.DispatchToServer).Start())
                    {
                        response = await HttpClient.PostAsync(requestUri, content).ContinueOnAnyContext();
                    }

                    using (ClientConfiguration.Tracer.BuildSpan(searchQuery, CouchbaseOperationNames.ResponseDecoding).Start())
                        using (var stream = await response.Content.ReadAsStreamAsync().ContinueOnAnyContext())
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                searchResult = DataMapper.Map <SearchQueryResult>(stream);
                            }
                            else
                            {
                                string responseContent;
                                using (var reader = new StreamReader(stream))
                                {
                                    responseContent = await reader.ReadToEndAsync().ContinueOnAnyContext();
                                }

                                if (response.Content.Headers.TryGetValues("Content-Type", out var values) &&
                                    values.Any(value => value.Contains(MediaType.Json)))
                                {
                                    // server 5.5+ responds with JSON content
                                    var result = JsonConvert.DeserializeObject <FailedSearchQueryResult>(responseContent);
                                    ProcessError(new HttpRequestException(result.Message), searchResult);
                                    searchResult.Errors.Add(result.Message);
                                }
                                else
                                {
                                    // use response content as raw string
                                    // ReSharper disable once UseStringInterpolation
                                    var message = string.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase);
                                    ProcessError(new HttpRequestException(message), searchResult);
                                    searchResult.Errors.Add(responseContent);
                                }

                                if (response.StatusCode == HttpStatusCode.NotFound)
                                {
                                    baseUri.IncrementFailed();
                                }
                            }
                        }
                }
                baseUri.ClearFailed();
            }
            catch (HttpRequestException e)
            {
                Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                baseUri.IncrementFailed();
                ProcessError(e, searchResult);
                Log.Error(e);
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e =>
                {
                    Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                    ProcessError(e, searchResult);
                    return(true);
                });
            }
            catch (Exception e)
            {
                Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                Log.Info(e);
                ProcessError(e, searchResult);
            }

            UpdateLastActivity();

            return(searchResult);
        }
Exemplo n.º 3
0
 public SearchClient(HttpClient httpClient, IDataMapper dataMapper, ConfigContextBase context)
     : base(httpClient, dataMapper, context)
 {
 }
        /// <summary>
        /// Executes a <see cref="IFtsQuery" /> request including any <see cref="ISearchParams" /> parameters asynchronously.
        /// </summary>
        /// <returns>A <see cref="ISearchQueryResult"/> wrapped in a <see cref="Task"/> for awaiting on.</returns>
        public async Task <ISearchQueryResult> QueryAsync(SearchQuery searchQuery)
        {
            var searchResult = new SearchQueryResult();
            var baseUri      = ConfigContextBase.GetSearchUri();
            var requestUri   = new Uri(baseUri, searchQuery.RelativeUri());
            var searchBody   = searchQuery.ToJson();

            try
            {
                using (var content = new StringContent(searchBody, Encoding.UTF8, MediaType.Json))
                    using (var response = await HttpClient.PostAsync(requestUri, content).ContinueOnAnyContext())
                        using (var stream = await response.Content.ReadAsStreamAsync().ContinueOnAnyContext())
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                searchResult = DataMapper.Map <SearchQueryResult>(stream);
                            }
                            else
                            {
                                // ReSharper disable once UseStringInterpolation
                                var message = string.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase);
                                ProcessError(new HttpRequestException(message), searchResult);

                                using (var reader = new StreamReader(stream))
                                {
                                    searchResult.Errors.Add(await reader.ReadToEndAsync().ContinueOnAnyContext());
                                }
                                if (response.StatusCode == HttpStatusCode.NotFound)
                                {
                                    baseUri.IncrementFailed();
                                }
                            }
                        }
                baseUri.ClearFailed();
            }
            catch (HttpRequestException e)
            {
                Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                baseUri.IncrementFailed();
                ProcessError(e, searchResult);
                Log.Error(e);
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e =>
                {
                    Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                    ProcessError(e, searchResult);
                    return(true);
                });
            }
            catch (Exception e)
            {
                Log.Info("Search failed {0}: {1}{2}", baseUri, Environment.NewLine, User(searchBody));
                Log.Info(e);
                ProcessError(e, searchResult);
            }

            UpdateLastActivity();

            return(searchResult);
        }
Exemplo n.º 5
0
        public Server(IIOService ioService, IViewClient viewClient, IViewClient streamingViewClient, IQueryClient queryClient, IQueryClient streamingQueryClient, ISearchClient searchClient,
                      IAnalyticsClient analyticsClient, INodeAdapter nodeAdapter, ITypeTranscoder transcoder, ConfigContextBase context)
        {
            if (ioService != null)
            {
                _ioService = ioService;
                _ioService.ConnectionPool.Owner = this;
            }
            _nodeAdapter         = nodeAdapter;
            _clientConfiguration = context.ClientConfig;
            _bucketConfiguration = context.ClientConfig.BucketConfigs[context.BucketConfig.Name];
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;
            _bucketConfig        = context.BucketConfig;

            //services that this node is responsible for
            IsMgmtNode      = _nodeAdapter.MgmtApi > 0;
            IsDataNode      = _nodeAdapter.KeyValue > 0;
            IsQueryNode     = _nodeAdapter.N1QL > 0;
            IsIndexNode     = _nodeAdapter.IndexAdmin > 0;
            IsViewNode      = _nodeAdapter.Views > 0;
            IsSearchNode    = _nodeAdapter.IsSearchNode;
            IsAnalyticsNode = _nodeAdapter.IsAnalyticsNode;

            //View and query clients
            ViewClient            = viewClient;
            _streamingViewClient  = streamingViewClient;
            QueryClient           = queryClient;
            SearchClient          = searchClient;
            _streamingQueryClient = streamingQueryClient;
            AnalyticsClient       = analyticsClient;

            CachedViewBaseUri  = UrlUtil.GetViewBaseUri(_nodeAdapter, _bucketConfiguration);
            CachedQueryBaseUri = UrlUtil.GetN1QLBaseUri(_nodeAdapter, _bucketConfiguration);

            if (IsDataNode || IsQueryNode)
            {
                _lastIOErrorCheckedTime = DateTime.Now;

                //On initialization, data nodes are authenticated, so they can start in a down state.
                //If the node is down immediately start the timer, otherwise disable it.
                if (IsDataNode)
                {
                    _isDown = _ioService.ConnectionPool.InitializationFailed;
                }

                Log.Info("Initialization {0} for node {1}", _isDown ? "failed" : "succeeded", EndPoint);

                //timer and node status
                _heartBeatTimer = new Timer(_heartBeatTimer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
                if (_isDown)
                {
                    StartHeartbeatTimer();
                }
            }
        }
Exemplo n.º 6
0
 public QueryClient(HttpClient httpClient, IDataMapper dataMapper, ConcurrentDictionary <string, QueryPlan> queryCache, ConfigContextBase context)
     : base(httpClient, dataMapper, context)
 {
     _queryCache = queryCache;
 }
Exemplo n.º 7
0
 public Server(IIOService ioService, INodeAdapter nodeAdapter, ITypeTranscoder transcoder, ConcurrentDictionary <string, QueryPlan> queryCache, ConfigContextBase context) :
     this(ioService,
          new ViewClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, context.ClientConfig.ViewRequestTimeout)
 }, new JsonDataMapper(context), context),
          new StreamingViewClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, context.ClientConfig.ViewRequestTimeout)
 }, new JsonDataMapper(context), context),
          new QueryClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, (int)context.ClientConfig.QueryRequestTimeout)
 }, new JsonDataMapper(context), queryCache, context),
          new StreamingQueryClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, (int)context.ClientConfig.QueryRequestTimeout)
 }, new JsonDataMapper(context), queryCache, context),
          new SearchClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, (int)context.ClientConfig.SearchRequestTimeout)
 }, new SearchDataMapper(), context),
          new AnalyticsClient(new CouchbaseHttpClient(context)
 {
     Timeout = new TimeSpan(0, 0, 0, 0, (int)context.ClientConfig.QueryRequestTimeout)
 }, new JsonDataMapper(context), context),
          nodeAdapter, transcoder, context)
 {
 }
Exemplo n.º 8
0
 public Server(IIOService ioService, INodeAdapter nodeAdapter, ITypeTranscoder transcoder, ConfigContextBase context) :
     this(ioService, null, null, null, null, null, null, nodeAdapter, transcoder, context)
 {
 }
 public JsonDataMapper(ConfigContextBase context)
     : this(context.ClientConfig)
 {
 }
Exemplo n.º 10
0
        public Server(IIOService ioService, IViewClient viewClient, IViewClient streamingViewClient, IQueryClient queryClient, IQueryClient streamingQueryClient, ISearchClient searchClient,
                      IAnalyticsClient analyticsClient, INodeAdapter nodeAdapter, ITypeTranscoder transcoder, ConfigContextBase context)
        {
            if (ioService != null)
            {
                _ioService = ioService;
                _ioService.ConnectionPool.Owner = this;
            }

            _clientConfiguration = context.ClientConfig;
            _bucketConfiguration = context.ClientConfig.BucketConfigs[context.BucketConfig.Name];
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;

            //set all properties based off the nodes and nodeExt adapter
            LoadNodeAdapter(nodeAdapter, context.BucketConfig.Rev);

            //View and query clients
            ViewClient            = viewClient;
            _streamingViewClient  = streamingViewClient;
            QueryClient           = queryClient;
            SearchClient          = searchClient;
            _streamingQueryClient = streamingQueryClient;
            AnalyticsClient       = analyticsClient;

            if (IsDataNode || IsQueryNode)
            {
                _lastIOErrorCheckedTime = DateTime.Now;

                //On initialization, data nodes are authenticated, so they can start in a down state.
                //If the node is down immediately start the timer, otherwise disable it.
                if (IsDataNode)
                {
                    _isDown = _ioService.ConnectionPool.InitializationFailed;
                }

                Log.Info("Initialization {0} for node {1}", _isDown ? "failed" : "succeeded", EndPoint);

                //timer and node status
                _heartBeatTimer = new Timer(_heartBeatTimer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
                if (_isDown)
                {
                    StartHeartbeatTimer();
                }
            }
        }
Exemplo n.º 11
0
 public StreamingQueryClient(HttpClient httpClient, IDataMapper dataMapper,
                             ConcurrentDictionary <string, QueryPlan> queryCache, ConfigContextBase context)
     : base(httpClient, dataMapper, queryCache, context)
 {
     HttpClient.Timeout = Timeout.InfiniteTimeSpan;
 }