Skip to content

Commit

Permalink
Add DeserializationTimeout to ApiEndpoint (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
evgenyvalavin authored Jun 15, 2023
1 parent 0964a2a commit 0129c82
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
6 changes: 3 additions & 3 deletions samples/Arbus.Network.Demo/GetAllOrdersApiEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Arbus.Network.Demo;

public class GetAllOrdersApiEndpoint : ApiEndpoint<OrdersResponseDto>
{
public override string Uri => "https://example.com/api/v1/orders";

public override HttpMethod Method => HttpMethod.Get;
public GetAllOrdersApiEndpoint() : base(HttpMethod.Get, "https://example.com/api/v1/orders")
{
}
}
20 changes: 16 additions & 4 deletions src/Arbus.Network/Abstractions/ApiEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@ public abstract class ApiEndpoint
/// <summary>
/// Relative Uri if HttpClientContext.GetBaseUri() returns not null. Absolute Uri otherwise.
/// </summary>
public abstract string Uri { get; }
public string Uri { get; }

public abstract HttpMethod Method { get; }
public HttpMethod Method { get; }

public virtual TimeSpan Timeout => _defaultTimeout;

public CancellationToken? CancellationToken { get; set; }

public ApiEndpoint(HttpMethod method, string uri)
{
Method = method;
Uri = uri;
}

public virtual HttpRequestMessage CreateRequest(Uri? baseUri)
{
var requestUri = CreateRequestUri(baseUri);
Expand Down Expand Up @@ -95,7 +101,13 @@ public virtual async Task<Exception> HandleAnyResponse(HttpResponseMessage respo

public abstract class ApiEndpoint<TResponse> : ApiEndpoint
{
private static readonly TimeSpan _maxDeserializationTime = TimeSpan.FromSeconds(5);
private static readonly TimeSpan _defaultDeserializationTimeout = TimeSpan.FromSeconds(100);

public virtual TimeSpan DeserializationTimeout => _defaultDeserializationTimeout;

public ApiEndpoint(HttpMethod method, string uri) : base(method, uri)
{
}

public virtual ValueTask<TResponse> GetResponse(HttpResponseMessage responseMessage)
=> FromJson<TResponse>(responseMessage.Content);
Expand All @@ -104,7 +116,7 @@ public static async ValueTask<T> FromJson<T>(HttpContent content, CancellationTo
{
using var responseStream = await GetStream(content, cancellationToken).ConfigureAwait(false);

using var tokenSource = new CancellationTokenSource(_maxDeserializationTime);
using var tokenSource = new CancellationTokenSource(_defaultDeserializationTimeout);
cancellationToken = tokenSource.Token;

return await Deserialize<T>(responseStream, cancellationToken.Value).ConfigureAwait(false)
Expand Down

0 comments on commit 0129c82

Please sign in to comment.