forked from octokit/octokit.net
/
CachingHttpClient.cs
90 lines (78 loc) · 2.88 KB
/
CachingHttpClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Octokit.Internal;
namespace Octokit.Caching
{
public sealed class CachingHttpClient : IHttpClient
{
internal readonly IHttpClient _httpClient;
internal readonly IResponseCache _responseCache;
public CachingHttpClient(IHttpClient httpClient, IResponseCache responseCache)
{
Ensure.ArgumentNotNull(httpClient, nameof(httpClient));
Ensure.ArgumentNotNull(responseCache, nameof(responseCache));
_httpClient = httpClient is CachingHttpClient cachingHttpClient ? cachingHttpClient._httpClient : httpClient;
_responseCache = responseCache;
}
public async Task<IResponse> Send(IRequest request, CancellationToken cancellationToken, Func<object, object> preprocessResponseBody = null)
{
Ensure.ArgumentNotNull(request, nameof(request));
if (request.Method != HttpMethod.Get)
{
return await _httpClient.Send(request, cancellationToken, preprocessResponseBody);
}
var cachedResponse = await TryGetCachedResponse(request);
if (cachedResponse != null && !string.IsNullOrEmpty(cachedResponse.ApiInfo.Etag))
{
request.Headers["If-None-Match"] = cachedResponse.ApiInfo.Etag;
var conditionalResponse = await _httpClient.Send(request, cancellationToken);
if (conditionalResponse.StatusCode == HttpStatusCode.NotModified)
{
return cachedResponse;
}
_ = TrySetCachedResponse(request, conditionalResponse);
return conditionalResponse;
}
var response = await _httpClient.Send(request, cancellationToken);
_ = TrySetCachedResponse(request, response);
return response;
}
private async Task<IResponse> TryGetCachedResponse(IRequest request)
{
try
{
return (await _responseCache.GetAsync(request))?.ToResponse();
}
catch (Exception)
{
return null;
}
}
private async Task TrySetCachedResponse(IRequest request, IResponse response)
{
try
{
if(!response.IsSuccessStatusCode())
{
return;
}
await _responseCache.SetAsync(request, CachedResponse.V1.Create(response));
}
catch (Exception)
{
// ignored
}
}
public void SetRequestTimeout(TimeSpan timeout)
{
_httpClient.SetRequestTimeout(timeout);
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}