Add retries to HttpClientSlim on macOS. (dotnet/extensions#1807)

\n\nCommit migrated from d4d110a838
This commit is contained in:
Justin Kotalik 2019-06-07 11:32:18 -07:00 committed by GitHub
parent 0dd632f52f
commit 3875b0f292
1 changed files with 54 additions and 20 deletions

View File

@ -8,6 +8,7 @@ using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
@ -23,6 +24,8 @@ namespace Microsoft.AspNetCore.Testing
=> await GetStringAsync(new Uri(requestUri), validateCertificate).ConfigureAwait(false);
public static async Task<string> GetStringAsync(Uri requestUri, bool validateCertificate = true)
{
return await RetryRequest(async () =>
{
using (var stream = await GetStream(requestUri, validateCertificate).ConfigureAwait(false))
{
@ -35,6 +38,7 @@ namespace Microsoft.AspNetCore.Testing
return await ReadResponse(stream).ConfigureAwait(false);
}
});
}
internal static string GetHost(Uri requestUri)
@ -61,6 +65,8 @@ namespace Microsoft.AspNetCore.Testing
=> await PostAsync(new Uri(requestUri), content, validateCertificate).ConfigureAwait(false);
public static async Task<string> PostAsync(Uri requestUri, HttpContent content, bool validateCertificate = true)
{
return await RetryRequest(async () =>
{
using (var stream = await GetStream(requestUri, validateCertificate))
{
@ -77,6 +83,7 @@ namespace Microsoft.AspNetCore.Testing
return await ReadResponse(stream).ConfigureAwait(false);
}
});
}
private static async Task<string> ReadResponse(Stream stream)
@ -94,6 +101,33 @@ namespace Microsoft.AspNetCore.Testing
}
}
private static async Task<string> RetryRequest(Func<Task<string>> retryBlock)
{
var retryCount = 1;
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
retryCount = 3;
}
for (var retry = 0; retry < retryCount; retry++)
{
try
{
return await retryBlock().ConfigureAwait(false);
}
catch (InvalidDataException)
{
if (retry == retryCount - 1)
{
throw;
}
}
}
// This will never be hit.
throw new NotSupportedException();
}
private static HttpStatusCode GetStatus(string response)
{
var statusStart = response.IndexOf(' ') + 1;