コード例 #1
0
ファイル: VkApi.cs プロジェクト: baguwka/vkpostorganizer
        public async Task <string> ExecuteMethodAsync(string method, [NotNull] QueryParameters query, CancellationToken ct)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var uri             = buildCompleteUri(method, query);
            var uriWithoutToken = removeQueryStringByKey(uri, "access_token");

            logger.Debug($"{uriWithoutToken}");

            var key = uri.ToString();

            //защита от множества запросов за короткое время, что бы они возможно получили данные из кэша
            if (_requestLog.ContainsKey(key))
            {
                DateTimeOffset lastLog;
                if (_requestLog.TryGetValue(key, out lastLog))
                {
                    var timeSpan = DateTimeOffset.Now - lastLog;
                    if (timeSpan < TimeSpan.FromSeconds(1))
                    {
                        logger.Debug($"Запрос \"{uriWithoutToken}\"выполнялся совсем недавно. Инициирована задержка на 1 секунду.");
                        await Task.Delay(TimeSpan.FromSeconds(1), ct);
                    }
                    else
                    {
                        _requestLog.TryRemove(key, out lastLog);
                    }
                }
            }
            else
            {
                _requestLog.TryAdd(key, DateTimeOffset.Now);
            }

            if (_responseCache.ContainsKey(key))
            {
                VkApiResponseInfo responseInfo;
                var result = _responseCache.TryGetValue(key, out responseInfo);
                if (result)
                {
                    var timeSpan = DateTimeOffset.Now - responseInfo.StoredAt;
                    if (timeSpan < TimeSpan.FromSeconds(5))
                    {
                        logger.Debug($"Ответ на запрос \"{uriWithoutToken}\" будет извлечен из кеша.");
                        return(responseInfo.Response);
                    }
                    else
                    {
                        _responseCache.TryRemove(key, out responseInfo);
                    }
                }
            }

            return(await _rateLimiter.Perform(() => callAsync(uri, ct), ct).ConfigureAwait(false));
        }
コード例 #2
0
ファイル: PipeDriveClient.cs プロジェクト: r8zr/PipeDriveApi
        public async Task ExecuteRequestAsync(IRestRequest request)
        {
            await _TimeContraint.Perform(async() =>
            {
                request.JsonSerializer = PipeDriveJsonSerializer.Default;
                request.SetQueryParameter("api_token", _ApiToken);

                Debug.WriteLine($"{DateTime.UtcNow:s} {request.Method} {request.Resource}");
                var response = await _Client.ExecuteTaskAsync(request);
                if (response.ResponseStatus != ResponseStatus.Completed)
                {
                    throw response.ErrorException;
                }
            });
        }
コード例 #3
0
        public async Task LogAsync(HistoryPost data)
        {
            if (!_settings.History.Use || !Utils.UrlHelper.IsUriIsValid(_settings.History.Uri))
            {
                return;
            }

            var uriBuilder = new UriBuilder(_settings.History.Uri)
            {
                Path = "posts"
            };

            var uri = uriBuilder.Uri;

            //await ensureDataBase(data);

            var serialized = JsonConvert.SerializeObject(data);
            var content    = new StringContent(serialized, Encoding.UTF8, "application/json");

            try {
                var result = await _rateLimiter.Perform(() => _httpClient.PostAsync(uri, content));

                Debug.WriteLine($"--- HISTORY PUBLISHED AT {DateTimeOffset.Now.Ticks}");
                if (result.IsSuccessStatusCode)
                {
                    var contentResult = result.Content.ReadAsStringAsync();
                }
            }
            catch (OperationCanceledException) {
                //ignore
            }
        }
コード例 #4
0
ファイル: CryptoService.cs プロジェクト: ia03/NadekoBot
        public async Task <CryptoCoin> CryptoCoin(int id)
        {
            string key  = "crypto_coin" + id;
            var    r    = _cache.Redis.GetDatabase();
            string coin = await r.StringGetAsync(key).ConfigureAwait(false);

            if (coin == null)
            {
                await _cryptoLock.WaitAsync().ConfigureAwait(false);

                try
                {
                    coinid = id;
                    await ratelimit.Perform(SetCoinData);

                    coin = CryptoCoinData;
                }
                finally
                {
                    _cryptoLock.Release();
                }
                await r.StringSetAsync(key, coin, TimeSpan.FromMinutes(30)).ConfigureAwait(false);
            }

            return(JsonConvert.DeserializeObject <CryptoCoin>(coin));
        }
コード例 #5
0
        public Uri GetProxy(Uri url)
        {
            Task t = ratelimit.Perform(() => null);

            t.Start();
            t.Wait();
            return(url);
        }
コード例 #6
0
        private async Task <IRestResponse> GetResponse(IRestRequest request, CancellationToken cancellationToken, IRestClient client = null)
        {
            client = client ?? Client;
            var response = await TimeLimiter.Perform(async() => await ExecuteBasic(client, request, cancellationToken), cancellationToken);

            if (response.ErrorException != null)
            {
                throw new WebClientException(_ErrorMessage, response.ErrorException);
            }

            return(response);
        }
コード例 #7
0
        private async Task <IRestResponse <T> > GetResponse <T>(IRestRequest request, CancellationToken cancellationToken, IRestClient client = null)
        {
            request.JsonSerializer = NewtonsoftJsonSerializer.Default;
            client = client ?? Client;
            var response = await TimeLimiter.Perform(async() => await ExecuteBasic <T>(client, request, cancellationToken), cancellationToken);

            if (response.ErrorException != null)
            {
                throw new WebClientException(_ErrorMessage, response.ErrorException);
            }

            CheckCallResult(response.StatusCode, client, request);

            return(response);
        }
コード例 #8
0
        public static async Task <string> GetHtml(Uri searchUri, CancellationToken token)
        {
            async Task <string> HttpResponse()
            {
                var response = await ClientInstance.Value.GetAsync(searchUri, token);

                if (!ResponseIsValid(response))
                {
                    throw new Exception("Invalid HTML response");
                }

                return(await response.Content.ReadAsStringAsync());
            }

            return(await TimeConstraint.Perform(HttpResponse, token));
        }
コード例 #9
0
ファイル: JsApi.cs プロジェクト: baguwka/vkpostorganizer
        public async Task <string> CallAsync(string path, QueryParameters query, CancellationToken ct)
        {
            var uri = buildUri(path, query);

            logger.Debug($"Запрос к json серверу. Итоговый url - {uri}");
            try {
                var response = await _rateLimiter.Perform(() => _httpClient.GetAsync(uri, ct), ct).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    logger.Error($"Ошибка при обрещении к Json Server. Http Status Code - {response.StatusCode}, url - {uri}");
                    throw new JsonServerException($"Ошибка при обращении к Json Server. Http status code - {response.StatusCode}");
                }

                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                checkForErrors(result);

                return(result);
            }

            // Httpclient timeout
            catch (TaskCanceledException ex) {
                _timeoutRetry++;
                if (!ct.IsCancellationRequested)
                {
                    logger.Error($"Превышено время ожидания, url - {uri}");
                    if (_timeoutRetry > 2)
                    {
                        //var error = "";
                        //if (_httpClientHandler.UseProxy) {
                        //   error = "Проверьте настройки прокси сервера и перезапустите приложение.";
                        //}
                        logger.Error(ex, $"Превышено время ожидания, соединение не удалось, url - {uri}");
                        throw new JsonServerException(
                                  $"Соеденение не удалось.\nПроверьте настройки прокси сервера и перезапустите приложение.\n{ex.Message}",
                                  ex);
                    }

                    return(await CallAsync(path, query, ct).ConfigureAwait(false));
                }

                //it's not timeout
                logger.Debug($"Операция отменена для url - {uri}");
                throw;
            }
        }
コード例 #10
0
        public async Task Perform_CallFuncAndIAwaitableConstraintMethods()
        {
            await _TimeConstraint.Perform(_FuncTask);

            CheckSequence();
        }
コード例 #11
0
ファイル: RequestsManager.cs プロジェクト: zHaytam/PsawSharp
 internal async Task <JToken> PerformGet(string route, List <string> args = null)
 {
     return(await _timeLimiter.Perform(() => ExecuteGet(route, args)));
 }