-
Notifications
You must be signed in to change notification settings - Fork 695
/
HttpSource.cs
416 lines (355 loc) · 14.8 KB
/
HttpSource.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Protocol.Core.Types;
namespace NuGet.Protocol
{
public class HttpSource : IDisposable
{
private readonly Func<Task<HttpHandlerResource>> _messageHandlerFactory;
private readonly Uri _sourceUri;
private HttpClient _httpClient;
private string _httpCacheDirectory;
private readonly PackageSource _packageSource;
private readonly IThrottle _throttle;
// Only one thread may re-create the http client at a time.
private readonly SemaphoreSlim _httpClientLock = new SemaphoreSlim(1, 1);
/// <summary>The retry handler to use for all HTTP requests.</summary>
/// <summary>This API is intended only for testing purposes and should not be used in product code.</summary>
public IHttpRetryHandler RetryHandler { get; set; } = new HttpRetryHandler();
public HttpSource(
PackageSource packageSource,
Func<Task<HttpHandlerResource>> messageHandlerFactory,
IThrottle throttle)
{
if (packageSource == null)
{
throw new ArgumentNullException(nameof(packageSource));
}
if (messageHandlerFactory == null)
{
throw new ArgumentNullException(nameof(messageHandlerFactory));
}
if (throttle == null)
{
throw new ArgumentNullException(nameof(throttle));
}
_packageSource = packageSource;
_sourceUri = packageSource.SourceUri;
_messageHandlerFactory = messageHandlerFactory;
_throttle = throttle;
}
/// <summary>
/// Caching Get request.
/// </summary>
public async Task<T> GetAsync<T>(
HttpSourceCachedRequest request,
Func<HttpSourceResult, Task<T>> processAsync,
ILogger log,
CancellationToken token)
{
var cacheResult = HttpCacheUtility.InitializeHttpCacheResult(
HttpCacheDirectory,
_sourceUri,
request.CacheKey,
request.CacheContext);
return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(
cacheResult.CacheFile,
action: async lockedToken =>
{
cacheResult.Stream = TryReadCacheFile(request.Uri, cacheResult.MaxAge, cacheResult.CacheFile);
if (cacheResult.Stream != null)
{
log.LogInformation(string.Format(CultureInfo.InvariantCulture, " " + Strings.Http_RequestLog, "CACHE", request.Uri));
// Validate the content fetched from the cache.
try
{
request.EnsureValidContents?.Invoke(cacheResult.Stream);
cacheResult.Stream.Seek(0, SeekOrigin.Begin);
var httpSourceResult = new HttpSourceResult(
HttpSourceResultStatus.OpenedFromDisk,
cacheResult.CacheFile,
cacheResult.Stream);
return await processAsync(httpSourceResult);
}
catch (Exception e)
{
cacheResult.Stream.Dispose();
cacheResult.Stream = null;
string message = string.Format(CultureInfo.CurrentCulture, Strings.Log_InvalidCacheEntry, request.Uri)
+ Environment.NewLine
+ ExceptionUtilities.DisplayMessage(e);
log.LogWarning(message);
}
}
Func<HttpRequestMessage> requestFactory = () =>
{
var requestMessage = HttpRequestMessageFactory.Create(HttpMethod.Get, request.Uri, log);
foreach (var acceptHeaderValue in request.AcceptHeaderValues)
{
requestMessage.Headers.Accept.Add(acceptHeaderValue);
}
return requestMessage;
};
Func<Task<ThrottledResponse>> throttledResponseFactory = () => GetThrottledResponse(
requestFactory,
request.RequestTimeout,
request.DownloadTimeout,
request.MaxTries,
log,
lockedToken);
using (var throttledResponse = await throttledResponseFactory())
{
if (request.IgnoreNotFounds && throttledResponse.Response.StatusCode == HttpStatusCode.NotFound)
{
var httpSourceResult = new HttpSourceResult(HttpSourceResultStatus.NotFound);
return await processAsync(httpSourceResult);
}
if (throttledResponse.Response.StatusCode == HttpStatusCode.NoContent)
{
// Ignore reading and caching the empty stream.
var httpSourceResult = new HttpSourceResult(HttpSourceResultStatus.NoContent);
return await processAsync(httpSourceResult);
}
throttledResponse.Response.EnsureSuccessStatusCode();
if (!request.CacheContext.DirectDownload)
{
await HttpCacheUtility.CreateCacheFileAsync(
cacheResult,
throttledResponse.Response,
request.EnsureValidContents,
lockedToken);
using (var httpSourceResult = new HttpSourceResult(
HttpSourceResultStatus.OpenedFromDisk,
cacheResult.CacheFile,
cacheResult.Stream))
{
return await processAsync(httpSourceResult);
}
}
else
{
// Note that we do not execute the content validator on the response stream when skipping
// the cache. We cannot seek on the network stream and it is not valuable to download the
// content twice just to validate the first time (considering that the second download could
// be different from the first thus rendering the first validation meaningless).
using (var stream = await throttledResponse.Response.Content.ReadAsStreamAsync())
using (var httpSourceResult = new HttpSourceResult(
HttpSourceResultStatus.OpenedFromNetwork,
cacheFileName: null,
stream: stream))
{
return await processAsync(httpSourceResult);
}
}
}
},
token: token);
}
public async Task<T> ProcessStreamAsync<T>(
HttpSourceRequest request,
Func<Stream, Task<T>> processAsync,
ILogger log,
CancellationToken token)
{
return await ProcessResponseAsync(
request,
async response =>
{
if ((request.IgnoreNotFounds && response.StatusCode == HttpStatusCode.NotFound) ||
response.StatusCode == HttpStatusCode.NoContent)
{
return await processAsync(null);
}
response.EnsureSuccessStatusCode();
var networkStream = await response.Content.ReadAsStreamAsync();
return await processAsync(networkStream);
},
log,
token);
}
public async Task<T> ProcessResponseAsync<T>(
HttpSourceRequest request,
Func<HttpResponseMessage, Task<T>> processAsync,
ILogger log,
CancellationToken token)
{
Func<Task<ThrottledResponse>> throttledResponseFactory = () => GetThrottledResponse(
request.RequestFactory,
request.RequestTimeout,
request.DownloadTimeout,
request.MaxTries,
log,
token);
using (var throttledResponse = await throttledResponseFactory())
{
return await processAsync(throttledResponse.Response);
}
}
public async Task<JObject> GetJObjectAsync(HttpSourceRequest request, ILogger log, CancellationToken token)
{
return await ProcessStreamAsync(
request,
processAsync: stream =>
{
if (stream == null)
{
return Task.FromResult<JObject>(null);
}
return stream.AsJObjectAsync();
},
log: log,
token: token);
}
private async Task<ThrottledResponse> GetThrottledResponse(
Func<HttpRequestMessage> requestFactory,
TimeSpan requestTimeout,
TimeSpan downloadTimeout,
int maxTries,
ILogger log,
CancellationToken cancellationToken)
{
await EnsureHttpClientAsync();
// Build the retriable request.
var request = new HttpRetryHandlerRequest(_httpClient, requestFactory)
{
RequestTimeout = requestTimeout,
DownloadTimeout = downloadTimeout,
MaxTries = maxTries
};
// Acquire the semaphore.
await _throttle.WaitAsync();
HttpResponseMessage response;
try
{
response = await RetryHandler.SendAsync(request, log, cancellationToken);
}
catch
{
// If the request fails, release the semaphore. If no exception is thrown by
// SendAsync, then the semaphore is released when the HTTP response message is
// disposed.
_throttle.Release();
throw;
}
return new ThrottledResponse(_throttle, response);
}
private async Task EnsureHttpClientAsync()
{
// Create the http client on the first call
if (_httpClient == null)
{
await _httpClientLock.WaitAsync();
try
{
// Double check
if (_httpClient == null)
{
_httpClient = await CreateHttpClientAsync();
}
}
finally
{
_httpClientLock.Release();
}
}
}
private async Task<HttpClient> CreateHttpClientAsync()
{
var httpHandler = await _messageHandlerFactory();
var httpClient = new HttpClient(httpHandler.MessageHandler)
{
Timeout = Timeout.InfiniteTimeSpan
};
// Set user agent
UserAgent.SetUserAgent(httpClient);
// Set accept-language header
string acceptLanguage = CultureInfo.CurrentUICulture.ToString();
if (!string.IsNullOrEmpty(acceptLanguage))
{
httpClient.DefaultRequestHeaders.AcceptLanguage.ParseAdd(acceptLanguage);
}
return httpClient;
}
public string HttpCacheDirectory
{
get
{
if (_httpCacheDirectory == null)
{
_httpCacheDirectory = SettingsUtility.GetHttpCacheFolder();
}
return _httpCacheDirectory;
}
set { _httpCacheDirectory = value; }
}
protected virtual Stream TryReadCacheFile(string uri, TimeSpan maxAge, string cacheFile)
{
return HttpCacheUtility.TryReadCacheFile(uri, maxAge, cacheFile);
}
public static HttpSource Create(SourceRepository source)
{
return Create(source, NullThrottle.Instance);
}
public static HttpSource Create(SourceRepository source, IThrottle throttle)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (throttle == null)
{
throw new ArgumentNullException(nameof(throttle));
}
Func<Task<HttpHandlerResource>> factory = () => source.GetResourceAsync<HttpHandlerResource>();
return new HttpSource(source.PackageSource, factory, throttle);
}
public void Dispose()
{
if (_httpClient != null)
{
_httpClient.Dispose();
}
_httpClientLock.Dispose();
}
private class ThrottledResponse : IDisposable
{
private IThrottle _throttle;
public ThrottledResponse(IThrottle throttle, HttpResponseMessage response)
{
if (throttle == null)
{
throw new ArgumentNullException(nameof(throttle));
}
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
_throttle = throttle;
Response = response;
}
public HttpResponseMessage Response { get; }
public void Dispose()
{
try
{
Response.Dispose();
}
finally
{
Interlocked.Exchange(ref _throttle, null)?.Release();
}
}
}
}
}