-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathHttpSymbolStore.cs
More file actions
322 lines (285 loc) · 12.4 KB
/
Copy pathHttpSymbolStore.cs
File metadata and controls
322 lines (285 loc) · 12.4 KB
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
// 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 or bearer token.
/// </summary>
public class HttpSymbolStore : SymbolStore
{
private readonly HttpClient _client;
private readonly Func<CancellationToken, ValueTask<AuthenticationHeaderValue>> _authenticationFunc;
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;
}
}
/// <summary>
/// The number of retries to do on a retryable status or socket error
/// </summary>
public int RetryCount { get; set; }
/// <summary>
/// Setups the underlying fields for HttpSymbolStore
/// </summary>
/// <param name="tracer">logger</param>
/// <param name="backingStore">next symbol store or null</param>
/// <param name="symbolServerUri">symbol server url</param>
/// <param name="authenticationFunc">function that returns the authentication value for a request</param>
public HttpSymbolStore(ITracer tracer, SymbolStore backingStore, Uri symbolServerUri, Func<CancellationToken, ValueTask<AuthenticationHeaderValue>> authenticationFunc)
: base(tracer, backingStore)
{
Uri = symbolServerUri ?? throw new ArgumentNullException(nameof(symbolServerUri));
if (!symbolServerUri.IsAbsoluteUri || symbolServerUri.IsFile)
{
throw new ArgumentException(null, nameof(symbolServerUri));
}
_authenticationFunc = authenticationFunc;
// Create client
_client = new HttpClient
{
Timeout = TimeSpan.FromMinutes(4)
};
// Force redirect logins to fail.
_client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
}
/// <summary>
/// Create an instance of a http symbol store
/// </summary>
/// <param name="tracer">logger</param>
/// <param name="backingStore">next symbol store or null</param>
/// <param name="symbolServerUri">symbol server url</param>
/// <param name="accessToken">optional Basic Auth PAT or null if no authentication</param>
public HttpSymbolStore(ITracer tracer, SymbolStore backingStore, Uri symbolServerUri, string accessToken = null)
: this(tracer, backingStore, symbolServerUri, string.IsNullOrEmpty(accessToken) ? null : GetAuthenticationFunc("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{accessToken}"))))
{
}
/// <summary>
/// Create an instance of a http symbol store with an authenticated client
/// </summary>
/// <param name="tracer">logger</param>
/// <param name="backingStore">next symbol store or null</param>
/// <param name="symbolServerUri">symbol server url</param>
/// <param name="scheme">The scheme information to use for the AuthenticationHeaderValue</param>
/// <param name="parameter">The parameter information to use for the AuthenticationHeaderValue</param>
public HttpSymbolStore(ITracer tracer, SymbolStore backingStore, Uri symbolServerUri, string scheme, string parameter)
: this(tracer, backingStore, symbolServerUri, GetAuthenticationFunc(scheme, parameter))
{
if (string.IsNullOrEmpty(scheme))
{
throw new ArgumentNullException(nameof(scheme));
}
if (string.IsNullOrEmpty(parameter))
{
throw new ArgumentNullException(nameof(parameter));
}
}
private static Func<CancellationToken, ValueTask<AuthenticationHeaderValue>> GetAuthenticationFunc(string scheme, string parameter)
{
AuthenticationHeaderValue authenticationValue = new(scheme, parameter);
return (_) => new ValueTask<AuthenticationHeaderValue>(authenticationValue);
}
/// <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);
Tracer.Information($"SymbolChecksum: {checksumHeader}");
_client.DefaultRequestHeaders.Add("SymbolChecksum", checksumHeader);
}
Stream stream = await GetFileStream(key.FullPathName, uri, token).ConfigureAwait(false);
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(message: null, paramName: nameof(index));
}
if (requestUri.IsFile)
{
throw new ArgumentException(message: null, paramName: 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);
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.
using HttpRequestMessage request = new(HttpMethod.Get, requestUri);
if (_authenticationFunc is not null)
{
request.Headers.Authorization = await _authenticationFunc(token).ConfigureAwait(false);
}
// Logged at Information level so CI runs surface every outgoing HTTP
// symbol-store fetch. If tests are supposed to be running with local-only
// symbol stores, grepping for "[HttpSymbolStore] GET" in the test output
// immediately reveals leaks back to public symbol servers.
Tracer.Information("[HttpSymbolStore] GET {0}", requestUri.AbsoluteUri);
using HttpResponseMessage response = await _client.SendAsync(request, token).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] buffer = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
return new MemoryStream(buffer);
}
HttpStatusCode statusCode = response.StatusCode;
string reasonPhrase = response.ReasonPhrase;
// 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)), token).ConfigureAwait(false);
}
return null;
}
public override void Dispose()
{
_client.Dispose();
base.Dispose();
}
private HashSet<HttpStatusCode> s_retryableStatusCodes = new()
{
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()
{
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}";
}
}
}