This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
HttpSymbolStore.cs
304 lines (268 loc) · 10.8 KB
/
HttpSymbolStore.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.SymbolStore.SymbolStores
{
/// <summary>
/// Basic http symbol store. The request can be authentication with a PAT for VSTS symbol stores.
/// </summary>
public class HttpSymbolStore : SymbolStore
{
private readonly HttpClient _client;
private readonly HttpClient _authenticatedClient;
private bool _clientFailure;
/// <summary>
/// For example, https://dotnet.myget.org/F/dev-feed/symbols.
/// </summary>
public Uri Uri { get; }
/// <summary>
/// Get or set the request timeout. Default 4 minutes.
/// </summary>
public TimeSpan Timeout
{
get
{
return _client.Timeout;
}
set
{
_client.Timeout = value;
if (_authenticatedClient != null)
{
_authenticatedClient.Timeout = value;
}
}
}
/// <summary>
/// The number of retries to do on a retryable status or socket error
/// </summary>
public int RetryCount { get; set; }
/// <summary>
/// Create an instance of a http symbol store
/// </summary>
/// <param name="backingStore">next symbol store or null</param>
/// <param name="symbolServerUri">symbol server url</param>
/// <param name="personalAccessToken">optional PAT or null if no authentication</param>
public HttpSymbolStore(ITracer tracer, SymbolStore backingStore, Uri symbolServerUri, string personalAccessToken = null)
: base(tracer, backingStore)
{
Uri = symbolServerUri ?? throw new ArgumentNullException(nameof(symbolServerUri));
if (!symbolServerUri.IsAbsoluteUri || symbolServerUri.IsFile)
{
throw new ArgumentException(nameof(symbolServerUri));
}
// Normal unauthenticated client
_client = new HttpClient {
Timeout = TimeSpan.FromMinutes(4)
};
// If PAT, create authenticated client
if (!string.IsNullOrEmpty(personalAccessToken))
{
var handler = new HttpClientHandler() {
AllowAutoRedirect = false
};
var client = new HttpClient(handler) {
Timeout = TimeSpan.FromMinutes(4)
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken))));
_authenticatedClient = client;
}
}
/// <summary>
/// Resets the sticky client failure flag. This client instance will now
/// attempt to download again instead of automatically failing.
/// </summary>
public void ResetClientFailure()
{
_clientFailure = false;
}
protected override async Task<SymbolStoreFile> GetFileInner(SymbolStoreKey key, CancellationToken token)
{
Uri uri = GetRequestUri(key.Index);
bool needsChecksumMatch = key.PdbChecksums.Any();
if (needsChecksumMatch)
{
string checksumHeader = string.Join(";", key.PdbChecksums);
HttpClient client = _authenticatedClient ?? _client;
Tracer.Information($"SymbolChecksum: {checksumHeader}");
client.DefaultRequestHeaders.Add("SymbolChecksum", checksumHeader);
}
Stream stream = await GetFileStream(key.FullPathName, uri, token);
if (stream != null)
{
if (needsChecksumMatch)
{
ChecksumValidator.Validate(Tracer, stream, key.PdbChecksums);
}
return new SymbolStoreFile(stream, uri.ToString());
}
return null;
}
protected Uri GetRequestUri(string index)
{
// Escape everything except the forward slashes (/) in the index
index = string.Join("/", index.Split('/').Select(part => Uri.EscapeDataString(part)));
if (!Uri.TryCreate(Uri, index, out Uri requestUri))
{
throw new ArgumentException(nameof(index));
}
if (requestUri.IsFile)
{
throw new ArgumentException(nameof(index));
}
return requestUri;
}
protected async Task<Stream> GetFileStream(string path, Uri requestUri, CancellationToken token)
{
// Just return if previous failure
if (_clientFailure)
{
return null;
}
string fileName = Path.GetFileName(path);
HttpClient client = _authenticatedClient ?? _client;
int retries = 0;
while(true)
{
bool retryable;
string message;
try
{
// Can not dispose the response (like via using) on success because then the content stream
// is disposed and it is returned by this function.
HttpResponseMessage response = await client.GetAsync(requestUri, token);
if (response.StatusCode == HttpStatusCode.OK)
{
return await response.Content.ReadAsStreamAsync();
}
if (response.StatusCode == HttpStatusCode.Found)
{
Uri location = response.Headers.Location;
response.Dispose();
response = await _client.GetAsync(location, token);
if (response.StatusCode == HttpStatusCode.OK)
{
return await response.Content.ReadAsStreamAsync();
}
}
HttpStatusCode statusCode = response.StatusCode;
string reasonPhrase = response.ReasonPhrase;
response.Dispose();
// The GET failed
if (statusCode == HttpStatusCode.NotFound)
{
Tracer.Error("Not Found: {0} - '{1}'", fileName, requestUri.AbsoluteUri);
break;
}
retryable = IsRetryableStatus(statusCode);
// Build the status code error message
message = string.Format("{0} {1}: {2} - '{3}'", (int)statusCode, reasonPhrase, fileName, requestUri.AbsoluteUri);
}
catch (HttpRequestException ex)
{
SocketError socketError = SocketError.Success;
retryable = false;
Exception innerException = ex.InnerException;
while (innerException != null)
{
if (innerException is SocketException se)
{
socketError = se.SocketErrorCode;
retryable = IsRetryableSocketError(socketError);
break;
}
innerException = innerException.InnerException;
}
// Build the socket error message
message = string.Format($"HttpSymbolStore: {fileName} retryable {retryable} socketError {socketError} '{requestUri.AbsoluteUri}' {ex}");
}
// If the status code or socket error isn't some temporary or retryable condition, mark failure
if (!retryable)
{
MarkClientFailure();
Tracer.Error(message);
break;
}
else
{
Tracer.Warning(message);
}
// Retry the operation?
if (retries++ >= RetryCount)
{
break;
}
Tracer.Information($"HttpSymbolStore: retry #{retries}");
// Delay for a while before doing the retry
await Task.Delay(TimeSpan.FromMilliseconds((Math.Pow(2, retries) * 100) + new Random().Next(200)));
}
return null;
}
public override void Dispose()
{
_client.Dispose();
if (_authenticatedClient != null)
{
_authenticatedClient.Dispose();
}
base.Dispose();
}
private HashSet<HttpStatusCode> s_retryableStatusCodes = new HashSet<HttpStatusCode>
{
HttpStatusCode.RequestTimeout,
HttpStatusCode.InternalServerError,
HttpStatusCode.BadGateway,
HttpStatusCode.ServiceUnavailable,
HttpStatusCode.GatewayTimeout,
};
/// <summary>
/// Returns true if the http status code is temporary or retryable condition.
/// </summary>
protected bool IsRetryableStatus(HttpStatusCode status) => s_retryableStatusCodes.Contains(status);
private HashSet<SocketError> s_retryableSocketErrors = new HashSet<SocketError>
{
SocketError.ConnectionReset,
SocketError.ConnectionAborted,
SocketError.Shutdown,
SocketError.TimedOut,
SocketError.TryAgain,
};
protected bool IsRetryableSocketError(SocketError se) => s_retryableSocketErrors.Contains(se);
/// <summary>
/// Marks this client as a failure where any subsequent calls to
/// GetFileStream() will return null.
/// </summary>
protected void MarkClientFailure()
{
_clientFailure = true;
}
public override bool Equals(object obj)
{
if (obj is HttpSymbolStore store)
{
return Uri.Equals(store.Uri);
}
return false;
}
public override int GetHashCode()
{
return Uri.GetHashCode();
}
public override string ToString()
{
return $"Server: {Uri}";
}
}
}