Beispiel #1
0
        public async Task SendAsync_SendsMessageOnTooManyRequestsWaitsRetriesThenSuccess()
        {
            var retryDeltaMilliseconds = 1000;
            var retryDelta             = System.TimeSpan.FromMilliseconds(retryDeltaMilliseconds);

            delay.DelayByTimeSpan(Arg.Any <System.TimeSpan>()).Returns(Task.CompletedTask);
            var successfulMessage       = new HttpRequestMessage();
            var tooManyRequestsResponse = new HttpResponseMessage {
                StatusCode = (HttpStatusCode)429
            };

            tooManyRequestsResponse.Headers.RetryAfter = new RetryConditionHeaderValue(retryDelta);
            var successResponse = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            };

            httpClient.SendAsync(Arg.Is(successfulMessage)).Returns(x => tooManyRequestsResponse, x => tooManyRequestsResponse, x => successResponse);

            var response = await _client.SendAsync(successfulMessage);

            await httpClient.Received(3).SendAsync(successfulMessage);

            await delay.Received(2).DelayByTimeSpan(retryDelta);

            Assert.Equal(successResponse, response);
        }
        public async Task <HttpResponseMessage> SendAsync(HttpRequestMessage message)
        {
            var response = await _httpClient.SendAsync(message);

            while ((int)response.StatusCode == HTTP_CODE_TOO_MANY_REQUESTS)
            {
                var retryAfter = response.Headers.RetryAfter.Delta ?? TimeSpan.FromSeconds(1);
                await _delay.DelayByTimeSpan(retryAfter);

                response = await _httpClient.SendAsync(message);
            }

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }

            var content = response.Content;

            throw (content != null) ?
                  new ContentManagementException(response, await response.Content.ReadAsStringAsync()) :
                  new ContentManagementException(response, "CM API returned server error.");
        }