Skip to content

Commit

Permalink
Replaced EndpointBase.HandleResponseAsync() with .HandleAsync()
Browse files Browse the repository at this point in the history
  • Loading branch information
bastianeicher committed May 12, 2020
1 parent cb4bbdc commit 00f76a3
Show file tree
Hide file tree
Showing 16 changed files with 39 additions and 32 deletions.
13 changes: 10 additions & 3 deletions src/TypedRest.OAuth/OAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private async Task RequestAccessTokenAsync(CancellationToken cancellationToken)
if (_oAuthOptions.Audience != null)
request.Parameters[OidcConstants.TokenRequest.Audience] = _oAuthOptions.Audience;

var response = await _httpClient.Value.RequestClientCredentialsTokenAsync(request, cancellationToken).ConfigureAwait(false);
var response = await HandleAsync(() => _httpClient.Value.RequestClientCredentialsTokenAsync(request, cancellationToken)).ConfigureAwait(false);

if (response.Exception != null) throw response.Exception;
if (response.IsError) throw new AuthenticationException(response.Error);
Expand All @@ -75,11 +75,18 @@ private async Task RequestAccessTokenAsync(CancellationToken cancellationToken)

private async Task<string> DiscoverTokenEndpointAsync(CancellationToken cancellationToken)
{
var response = await _httpClient.Value.GetDiscoveryDocumentAsync(_oAuthOptions.Uri.OriginalString, cancellationToken);
var response = await HandleAsync(() => _httpClient.Value.GetDiscoveryDocumentAsync(_oAuthOptions.Uri.OriginalString, cancellationToken)).ConfigureAwait(false);
return response.TokenEndpoint;
}

private static async Task<TResponse> HandleAsync<TResponse>(Func<Task<TResponse>> request)
where TResponse : ProtocolResponse
{
var response = await request().ConfigureAwait(false);

if (response.Exception != null) throw response.Exception;
if (response.IsError) throw new AuthenticationException(response.Error);
return response.TokenEndpoint;
return response;
}

private async Task<HttpResponseMessage> SendAuthenticatedAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Expand Down
4 changes: 2 additions & 2 deletions src/TypedRest.Reactive/Endpoints/Reactive/PollingEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ public PollingEndpoint(IEndpoint referrer, string relativeUri, Predicate<TEntity
_endCondition = endCondition;
}

protected override async Task<HttpResponseMessage> HandleResponseAsync(Task<HttpResponseMessage> responseTask)
protected override async Task<HttpResponseMessage> HandleAsync(Func<Task<HttpResponseMessage>> request)
{
var response = await base.HandleResponseAsync(responseTask);
var response = await base.HandleAsync(request);
PollingInterval =
response.Headers.RetryAfter?.Delta ??
(response.Headers.RetryAfter?.Date - DateTime.UtcNow) ??
Expand Down
12 changes: 6 additions & 6 deletions src/TypedRest/Endpoints/EndpointBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ public void SetDefaultLinkTemplate(string rel, string? href)
/// <summary>
/// Handles various cross-cutting concerns regarding a response message such as discovering links and handling errors.
/// </summary>
/// <param name="responseTask">A response promise for a request that has started executing.</param>
/// <returns>The resolved <paramref name="responseTask"/>.</returns>
protected virtual async Task<HttpResponseMessage> HandleResponseAsync(Task<HttpResponseMessage> responseTask)
/// <param name="request">A callback that performs the actual HTTP request.</param>
/// <returns>The resolved <paramref name="request"/>.</returns>
protected virtual async Task<HttpResponseMessage> HandleAsync(Func<Task<HttpResponseMessage>> request)
{
var response = await responseTask.NoContext();
var response = await request().NoContext();

(_links, _linkTemplates) = await LinkHandler.HandleAsync(response).NoContext();

Expand Down Expand Up @@ -135,7 +135,7 @@ public Uri Link(string rel)
{
try
{
await HandleResponseAsync(HttpClient.HeadAsync(Uri)).NoContext();
await HandleAsync(() => HttpClient.HeadAsync(Uri)).NoContext();
}
catch (Exception ex)
{
Expand Down Expand Up @@ -170,7 +170,7 @@ public UriTemplate LinkTemplate(string rel)
{
try
{
await HandleResponseAsync(HttpClient.HeadAsync(Uri)).NoContext();
await HandleAsync(() => HttpClient.HeadAsync(Uri)).NoContext();
}
catch (Exception ex)
{
Expand Down
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/EntryEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@ public EntryEndpoint(Uri uri, ICredentials? credentials = null, MediaTypeFormatt
/// <exception cref="KeyNotFoundException"><see cref="HttpStatusCode.NotFound"/> or <see cref="HttpStatusCode.Gone"/></exception>
/// <exception cref="HttpRequestException">Other non-success status code.</exception>
public Task ReadMetaAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.GetAsync(Uri, cancellationToken));
=> HandleAsync(() => HttpClient.GetAsync(Uri, cancellationToken));
}
}
6 changes: 3 additions & 3 deletions src/TypedRest/Endpoints/Generic/CollectionEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public virtual async Task<PartialResponse<TEntity>> ReadRangeAsync(RangeItemHead
Headers = {Range = new RangeHeaderValue {Ranges = {range}, Unit = RangeUnit}}
};

var response = await HandleResponseAsync(HttpClient.SendAsync(request, cancellationToken)).NoContext();
var response = await HandleAsync(() => HttpClient.SendAsync(request, cancellationToken)).NoContext();
return new PartialResponse<TEntity>(
elements: await response.Content.ReadAsAsync<List<TEntity>>(Serializer, cancellationToken).NoContext(),
range: response.Content.Headers.ContentRange);
Expand All @@ -117,7 +117,7 @@ public virtual async ITask<TElementEndpoint> CreateAsync(TEntity entity, Cancell
{
if (entity == null) throw new ArgumentNullException(nameof(entity));

var response = await HandleResponseAsync(HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken)).NoContext();
var response = await HandleAsync(() => HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken)).NoContext();

var elementEndpoint = _getElementEndpoint(this, response.Headers.Location ?? Uri);
if (response.Content != null && elementEndpoint is ICachingEndpoint caching)
Expand All @@ -131,7 +131,7 @@ public virtual Task CreateAllAsync(IEnumerable<TEntity> entities, CancellationTo
{
if (entities == null) throw new ArgumentNullException(nameof(entities));

return HandleResponseAsync(HttpClient.PatchAsync(Uri, entities, Serializer, cancellationToken));
return HandleAsync(() => HttpClient.PatchAsync(Uri, entities, Serializer, cancellationToken));
}

public bool? SetAllAllowed => IsMethodAllowed(HttpMethod.Put);
Expand Down
4 changes: 2 additions & 2 deletions src/TypedRest/Endpoints/Generic/ElementEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public async Task<bool> ExistsAsync(CancellationToken cancellationToken = defaul
{
try
{
await HandleResponseAsync(HttpClient.HeadAsync(Uri, cancellationToken)).NoContext();
await HandleAsync(() => HttpClient.HeadAsync(Uri, cancellationToken)).NoContext();
}
catch (KeyNotFoundException)
{
Expand Down Expand Up @@ -82,7 +82,7 @@ public async Task<bool> ExistsAsync(CancellationToken cancellationToken = defaul
{
if (entity == null) throw new ArgumentNullException(nameof(entity));

var response = await HandleResponseAsync(HttpClient.PatchAsync(Uri, entity, Serializer, cancellationToken));
var response = await HandleAsync(() => HttpClient.PatchAsync(Uri, entity, Serializer, cancellationToken));
return response.Content == null
? default
: await response.Content.ReadAsAsync<TEntity>(Serializer, cancellationToken);
Expand Down
6 changes: 3 additions & 3 deletions src/TypedRest/Endpoints/Generic/EtagEndpointBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ protected async Task<HttpContent> GetContentAsync(CancellationToken cancellation
return cache.GetContent();
else
{
await HandleResponseAsync(Task.FromResult(response)).NoContext();
await HandleAsync(() => Task.FromResult(response)).NoContext();
if (response.Content == null) throw new KeyNotFoundException($"{Uri} returned no body.");

ResponseCache = new ResponseCache(response);
Expand All @@ -84,7 +84,7 @@ protected Task<HttpResponseMessage> PutContentAsync(HttpContent content, Cancell
if (cache?.ETag != null) request.Headers.IfMatch.Add(cache.ETag);

ResponseCache = null;
return HandleResponseAsync(HttpClient.SendAsync(request, cancellationToken));
return HandleAsync(() => HttpClient.SendAsync(request, cancellationToken));
}

/// <summary>
Expand All @@ -105,7 +105,7 @@ protected Task<HttpResponseMessage> DeleteContentAsync(CancellationToken cancell
if (cache?.ETag != null) request.Headers.IfMatch.Add(cache.ETag);

ResponseCache = null;
return HandleResponseAsync(HttpClient.SendAsync(request, cancellationToken));
return HandleAsync(() => HttpClient.SendAsync(request, cancellationToken));
}
}
}
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Generic/IndexerEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private void SetupElementHandling()
private static readonly Func<IEndpoint, Uri, TElementEndpoint> _getElementEndpoint = GetConstructor<TElementEndpoint>();

public Task ProbeAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.OptionsAsync(Uri, cancellationToken));
=> HandleAsync(() => HttpClient.OptionsAsync(Uri, cancellationToken));

public virtual TElementEndpoint this[string id]
{
Expand Down
8 changes: 4 additions & 4 deletions src/TypedRest/Endpoints/Raw/BlobEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ public BlobEndpoint(IEndpoint referrer, string relativeUri)
{}

public Task ProbeAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.OptionsAsync(Uri, cancellationToken));
=> HandleAsync(() => HttpClient.OptionsAsync(Uri, cancellationToken));

public bool? DownloadAllowed => IsMethodAllowed(HttpMethod.Get);

public async Task<Stream> DownloadAsync(CancellationToken cancellationToken = default)
{
var response = await HandleResponseAsync(HttpClient.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).NoContext();
var response = await HandleAsync(() => HttpClient.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).NoContext();
return await response.Content.ReadAsStreamAsync().NoContext();
}

Expand All @@ -48,12 +48,12 @@ public Task UploadFromAsync(Stream stream, string? mimeType = null, Cancellation
{
var content = new StreamContent(stream);
if (!string.IsNullOrEmpty(mimeType)) content.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
return HandleResponseAsync(HttpClient.PutAsync(Uri, content, cancellationToken));
return HandleAsync(() => HttpClient.PutAsync(Uri, content, cancellationToken));
}

public bool? DeleteAllowed => IsMethodAllowed(HttpMethod.Delete);

public Task DeleteAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.DeleteAsync(Uri, cancellationToken));
=> HandleAsync(() => HttpClient.DeleteAsync(Uri, cancellationToken));
}
}
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Raw/UploadEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public Task UploadFromAsync(Stream stream, string? fileName = null, string? mime
: new MultipartFormDataContent {{content, _formField, fileName}};
}

return HandleResponseAsync(HttpClient.PostAsync(Uri, content, cancellationToken));
return HandleAsync(() => HttpClient.PostAsync(Uri, content, cancellationToken));
}
}
}
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Rpc/ActionEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ public ActionEndpoint(IEndpoint referrer, string relativeUri)
{}

public Task InvokeAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, Uri), cancellationToken));
=> HandleAsync(() => HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, Uri), cancellationToken));
}
}
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Rpc/ConsumerEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public Task InvokeAsync(TEntity entity, CancellationToken cancellationToken = de
{
if (entity == null) throw new ArgumentNullException(nameof(entity));

return HandleResponseAsync(HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken));
return HandleAsync(() => HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken));
}
}
}
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Rpc/FunctionEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public async Task<TResult> InvokeAsync(TEntity entity, CancellationToken cancell
{
if (entity == null) throw new ArgumentNullException(nameof(entity));

var response = await HandleResponseAsync(HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken));
var response = await HandleAsync(() => HttpClient.PostAsync(Uri, entity, Serializer, cancellationToken));

return await response.Content.ReadAsAsync<TResult>(Serializer, cancellationToken);
}
Expand Down
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Rpc/ProducerEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public ProducerEndpoint(IEndpoint referrer, string relativeUri)

public async ITask<TResult> InvokeAsync(CancellationToken cancellationToken = default)
{
var response = await HandleResponseAsync(HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, Uri), cancellationToken));
var response = await HandleAsync(() => HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, Uri), cancellationToken));

return await response.Content.ReadAsAsync<TResult>(Serializer, cancellationToken);
}
Expand Down
2 changes: 1 addition & 1 deletion src/TypedRest/Endpoints/Rpc/RpcEndpointBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ protected RpcEndpointBase(IEndpoint referrer, string relativeUri)
{}

public Task ProbeAsync(CancellationToken cancellationToken = default)
=> HandleResponseAsync(HttpClient.OptionsAsync(Uri, cancellationToken));
=> HandleAsync(() => HttpClient.OptionsAsync(Uri, cancellationToken));

public bool? InvokeAllowed => IsMethodAllowed(HttpMethod.Post);
}
Expand Down
2 changes: 1 addition & 1 deletion src/UnitTests/Endpoints/CustomEndpointTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public CustomEndpoint(IEndpoint referrer, string relativeUri)
: base(referrer, relativeUri)
{}

public Task GetAsync() => HandleResponseAsync(HttpClient.GetAsync(Uri));
public Task GetAsync() => HandleAsync(() => HttpClient.GetAsync(Uri));

public new bool? IsMethodAllowed(HttpMethod method) => base.IsMethodAllowed(method);
}
Expand Down

0 comments on commit 00f76a3

Please sign in to comment.