Skip to content

Commit

Permalink
Allow configurable timeout for URI health-checks
Browse files Browse the repository at this point in the history
  • Loading branch information
West Damron committed Feb 6, 2019
1 parent 80043fa commit e17d9f4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/HealthChecks.Uris/UriHealthCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,19 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
requestMessage.Headers.Add(header.Name, header.Value);
}

var response = await httpClient.SendAsync(requestMessage);
HttpResponseMessage response;
if (_options.Timeout != TimeSpan.Zero)
{
using (var timeoutSource = new CancellationTokenSource(_options.Timeout))
using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken))
{
response = await httpClient.SendAsync(requestMessage, linkedSource.Token);
}
}
else
{
response = await httpClient.SendAsync(requestMessage, cancellationToken);
}

if (!((int)response.StatusCode >= expectedCodes.Min && (int)response.StatusCode <= expectedCodes.Max))
{
Expand Down
17 changes: 17 additions & 0 deletions src/HealthChecks.Uris/UriHealthCheckOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public interface IUriOptions
IUriOptions UseGet();
IUriOptions UsePost();
IUriOptions UseHttpMethod(HttpMethod methodToUse);
IUriOptions UseTimeout(TimeSpan timeout);
IUriOptions ExpectHttpCode(int codeToExpect);
IUriOptions ExpectHttpCodes(int minCodeToExpect, int maxCodeToExpect);
IUriOptions AddCustomHeader(string name, string value);
Expand All @@ -18,6 +19,8 @@ public class UriOptions : IUriOptions
{
public HttpMethod HttpMethod { get; private set; }

public TimeSpan Timeout { get; private set; }

public (int Min, int Max)? ExpectedHttpCodes { get; private set; }

public Uri Uri { get; }
Expand Down Expand Up @@ -68,6 +71,12 @@ IUriOptions IUriOptions.UseHttpMethod(HttpMethod methodToUse)
HttpMethod = methodToUse;
return this;
}

IUriOptions IUriOptions.UseTimeout(TimeSpan timeout)
{
Timeout = timeout;
return this;
}
}

public class UriHealthCheckOptions
Expand All @@ -78,6 +87,8 @@ public class UriHealthCheckOptions

internal HttpMethod HttpMethod { get; private set; }

internal TimeSpan Timeout { get; private set; }

internal (int Min, int Max) ExpectedHttpCodes { get; private set; }

public UriHealthCheckOptions()
Expand All @@ -104,6 +115,12 @@ public UriHealthCheckOptions UseHttpMethod(HttpMethod methodToUse)
return this;
}

public UriHealthCheckOptions UseTimeout(TimeSpan timeout)
{
Timeout = timeout;
return this;
}

public UriHealthCheckOptions AddUri(Uri uriToAdd, Action<IUriOptions> setup = null)
{
var uri = new UriOptions(uriToAdd);
Expand Down

0 comments on commit e17d9f4

Please sign in to comment.