This repository has been archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathHttpClientRequestAdapter.cs
540 lines (525 loc) · 31.4 KB
/
HttpClientRequestAdapter.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Abstractions.Store;
using Microsoft.Kiota.Abstractions.Authentication;
using System.Threading;
using System.Net;
using Microsoft.Kiota.Abstractions.Extensions;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware;
namespace Microsoft.Kiota.Http.HttpClientLibrary
{
/// <summary>
/// The <see cref="IRequestAdapter"/> implementation for sending requests.
/// </summary>
public class HttpClientRequestAdapter : IRequestAdapter, IDisposable
{
private readonly HttpClient client;
private readonly IAuthenticationProvider authProvider;
private IParseNodeFactory pNodeFactory;
private ISerializationWriterFactory sWriterFactory;
private readonly bool createdClient;
private readonly ObservabilityOptions obsOptions;
private readonly ActivitySource activitySource;
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientRequestAdapter"/> class.
/// <param name="authenticationProvider">The authentication provider.</param>
/// <param name="parseNodeFactory">The parse node factory.</param>
/// <param name="serializationWriterFactory">The serialization writer factory.</param>
/// <param name="httpClient">The native HTTP client.</param>
/// <param name="observabilityOptions">The observability options.</param>
/// </summary>
public HttpClientRequestAdapter(IAuthenticationProvider authenticationProvider, IParseNodeFactory? parseNodeFactory = null, ISerializationWriterFactory? serializationWriterFactory = null, HttpClient? httpClient = null, ObservabilityOptions? observabilityOptions = null)
{
authProvider = authenticationProvider ?? throw new ArgumentNullException(nameof(authenticationProvider));
createdClient = httpClient == null;
client = httpClient ?? KiotaClientFactory.Create();
pNodeFactory = parseNodeFactory ?? ParseNodeFactoryRegistry.DefaultInstance;
sWriterFactory = serializationWriterFactory ?? SerializationWriterFactoryRegistry.DefaultInstance;
obsOptions = observabilityOptions ?? new ObservabilityOptions();
activitySource = new(obsOptions.TracerInstrumentationName);
}
/// <summary>Factory to use to get a serializer for payload serialization</summary>
public ISerializationWriterFactory SerializationWriterFactory
{
get
{
return sWriterFactory;
}
}
/// <summary>
/// The base url for every request.
/// </summary>
public string? BaseUrl { get; set; }
private static readonly char[] charactersToDecodeForUriTemplate = new char[] { '$', '.', '-', '~' };
private static readonly Regex queryParametersCleanupRegex = new (@"\{\?[^\}]+}", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromMilliseconds(100));
private Activity? startTracingSpan(RequestInformation requestInfo, string methodName) {
var decodedUriTemplate = ParametersNameDecodingHandler.DecodeUriEncodedString(requestInfo.UrlTemplate, charactersToDecodeForUriTemplate);
var telemetryPathValue = queryParametersCleanupRegex.Replace(decodedUriTemplate!, string.Empty);
var span = activitySource?.StartActivity($"{methodName} - {telemetryPathValue}");
span?.SetTag("http.uri_template", decodedUriTemplate);
return span;
}
/// <summary>
/// Send a <see cref="RequestInformation"/> instance with a collection instance of <typeparam name="ModelType"></typeparam>
/// </summary>
/// <param name="requestInfo">The <see cref="RequestInformation"/> instance to send</param>
/// <param name="factory">The factory of the response model to deserialize the response into.</param>
/// <param name="errorMapping">The error factories mapping to use in case of a failed request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use for cancelling the request.</param>
public async Task<IEnumerable<ModelType>?> SendCollectionAsync<ModelType>(RequestInformation requestInfo, ParsableFactory<ModelType> factory, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default) where ModelType : IParsable
{
using var span = startTracingSpan(requestInfo, nameof(SendCollectionAsync));
var response = await GetHttpResponseMessage(requestInfo, cancellationToken, span);
requestInfo.Content?.Dispose();
var responseHandler = GetResponseHandler(requestInfo);
if(responseHandler == null)
{
try {
await ThrowIfFailedResponse(response, errorMapping, span);
if(shouldReturnNull(response)) return default;
var rootNode = await GetRootParseNode(response);
using var spanForDeserialization = activitySource?.StartActivity(nameof(IParseNode.GetCollectionOfObjectValues));
var result = rootNode?.GetCollectionOfObjectValues<ModelType>(factory);
SetResponseType(result, span);
return result;
} finally {
await DrainAsync(response);
}
}
else {
span?.AddEvent(new ActivityEvent(EventResponseHandlerInvokedKey));
return await responseHandler.HandleResponseAsync<HttpResponseMessage, IEnumerable<ModelType>>(response, errorMapping);
}
}
/// <summary>
/// Executes the HTTP request specified by the given RequestInformation and returns the deserialized primitive response model collection.
/// </summary>
/// <param name="requestInfo">The RequestInformation object to use for the HTTP request.</param>
/// <param name="errorMapping">The error factories mapping to use in case of a failed request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use for cancelling the request.</param>
/// <returns>The deserialized primitive response model collection.</returns>
public async Task<IEnumerable<ModelType>?> SendPrimitiveCollectionAsync<ModelType>(RequestInformation requestInfo, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default) {
using var span = startTracingSpan(requestInfo, nameof(SendPrimitiveCollectionAsync));
var response = await GetHttpResponseMessage(requestInfo, cancellationToken, span);
requestInfo.Content?.Dispose();
var responseHandler = GetResponseHandler(requestInfo);
if(responseHandler == null)
{
try {
await ThrowIfFailedResponse(response, errorMapping, span);
if(shouldReturnNull(response)) return default;
var rootNode = await GetRootParseNode(response);
using var spanForDeserialization = activitySource?.StartActivity(nameof(IParseNode.GetCollectionOfPrimitiveValues));
var result = rootNode?.GetCollectionOfPrimitiveValues<ModelType>();
SetResponseType(result, span);
return result;
} finally {
await DrainAsync(response);
}
}
else {
span?.AddEvent(new ActivityEvent(EventResponseHandlerInvokedKey));
return await responseHandler.HandleResponseAsync<HttpResponseMessage, IEnumerable<ModelType>>(response, errorMapping);
}
}
/// <summary>
/// The key for the tracing event raised when a response handler is called.
/// </summary>
public const string EventResponseHandlerInvokedKey = "com.microsoft.kiota.response_handler_invoked";
/// <summary>
/// Send a <see cref="RequestInformation"/> instance with an instance of <typeparam name="ModelType"></typeparam>
/// </summary>
/// <param name="requestInfo">The <see cref="RequestInformation"/> instance to send</param>
/// <param name="factory">The factory of the response model to deserialize the response into.</param>
/// <param name="errorMapping">The error factories mapping to use in case of a failed request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use for cancelling the request.</param>
/// <returns>The deserialized response model.</returns>
public async Task<ModelType?> SendAsync<ModelType>(RequestInformation requestInfo, ParsableFactory<ModelType> factory, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default) where ModelType : IParsable
{
using var span = startTracingSpan(requestInfo, nameof(SendAsync));
var response = await GetHttpResponseMessage(requestInfo, cancellationToken, span);
requestInfo.Content?.Dispose();
var responseHandler = GetResponseHandler(requestInfo);
if(responseHandler == null)
{
try {
await ThrowIfFailedResponse(response, errorMapping, span);
if(shouldReturnNull(response)) return default;
var rootNode = await GetRootParseNode(response);
if (rootNode == null) return default;
using var spanForDeserialization = activitySource?.StartActivity(nameof(IParseNode.GetObjectValue));
var result = rootNode.GetObjectValue<ModelType>(factory);
SetResponseType(result, span);
return result;
} finally {
if (typeof(ModelType) != typeof(Stream))
{
await DrainAsync(response);
}
}
}
else {
span?.AddEvent(new ActivityEvent(EventResponseHandlerInvokedKey));
return await responseHandler.HandleResponseAsync<HttpResponseMessage, ModelType>(response, errorMapping);
}
}
/// <summary>
/// Send a <see cref="RequestInformation"/> instance with a primitive instance of <typeparam name="ModelType"></typeparam>
/// </summary>
/// <param name="requestInfo">The <see cref="RequestInformation"/> instance to send</param>
/// <param name="errorMapping">The error factories mapping to use in case of a failed request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use for cancelling the request.</param>
/// <returns>The deserialized primitive response model.</returns>
public async Task<ModelType?> SendPrimitiveAsync<ModelType>(RequestInformation requestInfo, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default)
{
using var span = startTracingSpan(requestInfo, nameof(SendPrimitiveAsync));
var response = await GetHttpResponseMessage(requestInfo, cancellationToken, span);
requestInfo.Content?.Dispose();
var responseHandler = GetResponseHandler(requestInfo);
if(responseHandler == null)
{
try {
await ThrowIfFailedResponse(response, errorMapping, span);
if(shouldReturnNull(response)) return default;
var modelType = typeof(ModelType);
if(modelType == typeof(Stream))
{
var result = await response.Content.ReadAsStreamAsync();
if (result.Length == 0) {
result.Dispose();
return default;
}
SetResponseType(result, span);
return (ModelType)(result as object);
}
else
{
var rootNode = await GetRootParseNode(response);
object? result;
using var spanForDeserialization = activitySource?.StartActivity($"Get{modelType.Name.TrimEnd('?')}Value");
if(rootNode == null) {
result = null;
}
else if(modelType == typeof(bool?))
{
result = rootNode.GetBoolValue();
}
else if(modelType == typeof(byte?))
{
result = rootNode.GetByteValue();
}
else if(modelType == typeof(sbyte?))
{
result = rootNode.GetSbyteValue();
}
else if(modelType == typeof(string))
{
result = rootNode.GetStringValue();
}
else if(modelType == typeof(int?))
{
result = rootNode.GetIntValue();
}
else if(modelType == typeof(float?))
{
result = rootNode.GetFloatValue();
}
else if(modelType == typeof(long?))
{
result = rootNode.GetLongValue();
}
else if(modelType == typeof(double?))
{
result = rootNode.GetDoubleValue();
}
else if(modelType == typeof(decimal?))
{
result = rootNode.GetDecimalValue();
}
else if(modelType == typeof(Guid?))
{
result = rootNode.GetGuidValue();
}
else if(modelType == typeof(DateTimeOffset?))
{
result = rootNode.GetDateTimeOffsetValue();
}
else if(modelType == typeof(TimeSpan?))
{
result = rootNode.GetTimeSpanValue();
}
else if(modelType == typeof(Date?))
{
result = rootNode.GetDateValue();
}
else throw new InvalidOperationException("error handling the response, unexpected type");
SetResponseType(result, span);
return (ModelType)result!;
}
} finally {
if (typeof(ModelType) != typeof(Stream))
{
await DrainAsync(response);
}
}
}
else {
span?.AddEvent(new ActivityEvent(EventResponseHandlerInvokedKey));
return await responseHandler.HandleResponseAsync<HttpResponseMessage, ModelType>(response, errorMapping);
}
}
/// <summary>
/// Send a <see cref="RequestInformation"/> instance with an empty request body
/// </summary>
/// <param name="requestInfo">The <see cref="RequestInformation"/> instance to send</param>
/// <param name="errorMapping">The error factories mapping to use in case of a failed request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use for cancelling the request.</param>
/// <returns></returns>
public async Task SendNoContentAsync(RequestInformation requestInfo, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default)
{
using var span = startTracingSpan(requestInfo, nameof(SendNoContentAsync));
var response = await GetHttpResponseMessage(requestInfo, cancellationToken, span);
requestInfo.Content?.Dispose();
var responseHandler = GetResponseHandler(requestInfo);
if(responseHandler == null)
{
try {
await ThrowIfFailedResponse(response, errorMapping, span);
} finally {
await DrainAsync(response);
}
}
else {
span?.AddEvent(new ActivityEvent(EventResponseHandlerInvokedKey));
await responseHandler.HandleResponseAsync<HttpResponseMessage, object>(response, errorMapping);
}
}
private void SetResponseType(object? result, Activity? activity) {
if (result != null) {
activity?.SetTag("com.microsoft.kiota.response.type", result.GetType().FullName);
}
}
private async Task DrainAsync(HttpResponseMessage response)
{
if(response.Content != null)
{
using var discard = await response.Content.ReadAsStreamAsync();
response.Content.Dispose();
}
response.Dispose();
}
private bool shouldReturnNull(HttpResponseMessage response)
{
return response.StatusCode == HttpStatusCode.NoContent || response.Content == null;
}
/// <summary>
/// The attribute name used to indicate whether an error code mapping was found.
/// </summary>
public const string ErrorMappingFoundAttributeName = "com.microsoft.kiota.error.mapping_found";
/// <summary>
/// The attribute name used to indicate whether the error response contained a body.
/// </summary>
public const string ErrorBodyFoundAttributeName = "com.microsoft.kiota.error.body_found";
private async Task ThrowIfFailedResponse(HttpResponseMessage response, Dictionary<string, ParsableFactory<IParsable>>? errorMapping, Activity? activityForAttributes)
{
using var span = activitySource?.StartActivity(nameof(ThrowIfFailedResponse));
if(response.IsSuccessStatusCode) return;
activityForAttributes?.SetStatus(ActivityStatusCode.Error, "received_error_response");
var statusCodeAsInt = (int)response.StatusCode;
var statusCodeAsString = statusCodeAsInt.ToString();
ParsableFactory<IParsable>? errorFactory;
if(errorMapping == null ||
!errorMapping.TryGetValue(statusCodeAsString, out errorFactory) &&
!(statusCodeAsInt >= 400 && statusCodeAsInt < 500 && errorMapping.TryGetValue("4XX", out errorFactory)) &&
!(statusCodeAsInt >= 500 && statusCodeAsInt < 600 && errorMapping.TryGetValue("5XX", out errorFactory)))
{
activityForAttributes?.SetTag(ErrorMappingFoundAttributeName, false);
throw new ApiException($"The server returned an unexpected status code and no error factory is registered for this code: {statusCodeAsString}") {
ResponseStatusCode = statusCodeAsInt,
};
}
activityForAttributes?.SetTag(ErrorMappingFoundAttributeName, true);
var rootNode = await GetRootParseNode(response);
activityForAttributes?.SetTag(ErrorBodyFoundAttributeName, rootNode != null);
var spanForDeserialization = activitySource?.StartActivity(nameof(IParseNode.GetObjectValue));
var result = rootNode?.GetObjectValue(errorFactory);
SetResponseType(result, activityForAttributes);
spanForDeserialization?.Dispose();
if(result is not Exception ex)
throw new ApiException($"The server returned an unexpected status code and the error registered for this code failed to deserialize: {statusCodeAsString}") {
ResponseStatusCode = statusCodeAsInt,
};
if(result is ApiException apiEx)
apiEx.ResponseStatusCode = statusCodeAsInt;
throw ex;
}
private static IResponseHandler? GetResponseHandler(RequestInformation requestInfo)
{
return requestInfo.GetRequestOption<ResponseHandlerOption>()?.ResponseHandler;
}
private async Task<IParseNode?> GetRootParseNode(HttpResponseMessage response)
{
using var span = activitySource?.StartActivity(nameof(GetRootParseNode));
var responseContentType = response.Content?.Headers?.ContentType?.MediaType?.ToLowerInvariant();
if(string.IsNullOrEmpty(responseContentType))
return null;
using var contentStream = await (response.Content?.ReadAsStreamAsync() ?? Task.FromResult(Stream.Null));
var rootNode = pNodeFactory.GetRootParseNode(responseContentType!, contentStream);
return rootNode;
}
private const string ClaimsKey = "claims";
private const string BearerAuthenticationScheme = "Bearer";
private static Func<AuthenticationHeaderValue, bool> filterAuthHeader = static x => x.Scheme.Equals(BearerAuthenticationScheme, StringComparison.OrdinalIgnoreCase);
private async Task<HttpResponseMessage> GetHttpResponseMessage(RequestInformation requestInfo, CancellationToken cancellationToken, Activity? activityForAttributes, string? claims = default)
{
using var span = activitySource?.StartActivity(nameof(GetHttpResponseMessage));
if(requestInfo == null)
throw new ArgumentNullException(nameof(requestInfo));
SetBaseUrlForRequestInformation(requestInfo);
var additionalAuthenticationContext = string.IsNullOrEmpty(claims) ? null : new Dictionary<string, object> { { ClaimsKey, claims! } };
await authProvider.AuthenticateRequestAsync(requestInfo, additionalAuthenticationContext, cancellationToken);
using var message = GetRequestMessageFromRequestInformation(requestInfo, activityForAttributes);
var response = await this.client.SendAsync(message,cancellationToken);
if(response == null)
{
var ex = new InvalidOperationException("Could not get a response after calling the service");
throw ex;
}
if (response.Headers.TryGetValues("Content-Length", out var contentLengthValues) &&
contentLengthValues.Any() &&
contentLengthValues.First() is string firstContentLengthValue &&
int.TryParse(firstContentLengthValue, out var contentLength))
{
activityForAttributes?.SetTag("http.response_content_length", contentLength);
}
if (response.Headers.TryGetValues("Content-Type", out var contentTypeValues) &&
contentTypeValues.Any() &&
contentTypeValues.First() is string firstContentTypeValue)
{
activityForAttributes?.SetTag("http.response_content_type", firstContentTypeValue);
}
activityForAttributes?.SetTag("http.status_code", (int)response.StatusCode);
activityForAttributes?.SetTag("http.flavor", $"{response.Version.Major}.{response.Version.Minor}");
return await RetryCAEResponseIfRequired(response, requestInfo, cancellationToken, claims, activityForAttributes);
}
private static readonly Regex caeValueRegex = new("\"([^\"]*)\"", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
/// <summary>
/// The key for the event raised by tracing when an authentication challenge is received
/// </summary>
public const string AuthenticateChallengedEventKey = "com.microsoft.kiota.authenticate_challenge_received";
private async Task<HttpResponseMessage> RetryCAEResponseIfRequired(HttpResponseMessage response, RequestInformation requestInfo, CancellationToken cancellationToken, string? claims, Activity? activityForAttributes)
{
using var span = activitySource?.StartActivity(nameof(RetryCAEResponseIfRequired));
if(response.StatusCode == HttpStatusCode.Unauthorized &&
string.IsNullOrEmpty(claims) && // avoid infinite loop, we only retry once
(requestInfo.Content?.CanSeek ?? true) &&
response.Headers.WwwAuthenticate?.FirstOrDefault(filterAuthHeader) is AuthenticationHeaderValue authHeader &&
authHeader.Parameter?.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(static x => x.Trim())
.FirstOrDefault(static x => x.StartsWith(ClaimsKey, StringComparison.OrdinalIgnoreCase)) is string rawResponseClaims &&
caeValueRegex.Match(rawResponseClaims) is Match claimsMatch &&
claimsMatch.Groups.Count > 1 &&
claimsMatch.Groups[1].Value is string responseClaims)
{
span?.AddEvent(new ActivityEvent(AuthenticateChallengedEventKey));
activityForAttributes?.SetTag("http.retry_count", 1);
requestInfo.Content?.Seek(0, SeekOrigin.Begin);
await DrainAsync(response);
return await GetHttpResponseMessage(requestInfo, cancellationToken, activityForAttributes, responseClaims);
}
return response;
}
private void SetBaseUrlForRequestInformation(RequestInformation requestInfo)
{
IDictionaryExtensions.AddOrReplace(requestInfo.PathParameters, "baseurl", BaseUrl!);
}
/// <inheritdoc/>
public async Task<T?> ConvertToNativeRequestAsync<T>(RequestInformation requestInfo, CancellationToken cancellationToken = default)
{
await authProvider.AuthenticateRequestAsync(requestInfo, null, cancellationToken);
if (GetRequestMessageFromRequestInformation(requestInfo, null) is T result)
return result;
else throw new InvalidOperationException($"Could not convert the request information to a {typeof(T).Name}");
}
private HttpRequestMessage GetRequestMessageFromRequestInformation(RequestInformation requestInfo, Activity? activityForAttributes)
{
using var span = activitySource?.StartActivity(nameof(GetRequestMessageFromRequestInformation));
SetBaseUrlForRequestInformation(requestInfo);// this method can also be called from a different context so ensure the baseUrl is added.
activityForAttributes?.SetTag("http.method", requestInfo.HttpMethod.ToString());
var requestUri = requestInfo.URI;
activityForAttributes?.SetTag("http.host", requestUri.Host);
activityForAttributes?.SetTag("http.scheme", requestUri.Scheme);
if (obsOptions.IncludeEUIIAttributes)
activityForAttributes?.SetTag("http.uri", requestUri.ToString());
var message = new HttpRequestMessage
{
Method = new HttpMethod(requestInfo.HttpMethod.ToString().ToUpperInvariant()),
RequestUri = requestUri,
};
if(requestInfo.RequestOptions.Any())
requestInfo.RequestOptions.ToList().ForEach(x => IDictionaryExtensions.TryAdd(message.Properties,x.GetType().FullName!, x));
IDictionaryExtensions.TryAdd(message.Properties!, typeof(ObservabilityOptions).FullName, obsOptions);
if(requestInfo.Content != null && requestInfo.Content != Stream.Null )
message.Content = new StreamContent(requestInfo.Content);
if(requestInfo.Headers?.Any() ?? false)
foreach(var header in requestInfo.Headers)
if(!message.Headers.TryAddWithoutValidation(header.Key, header.Value) && message.Content != null)
message.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);// Try to add the headers we couldn't add to the HttpRequestMessage before to the HttpContent
if (message.Content != null) {
if (message.Content.Headers.TryGetValues("Content-Length", out var contentLenValues) &&
contentLenValues.Any() &&
contentLenValues.First() is string contentLenValue &&
int.TryParse(contentLenValue, out var contentLenValueInt))
activityForAttributes?.SetTag("http.request_content_length", contentLenValueInt);
if (message.Content.Headers.TryGetValues("Content-Type", out var contentTypeValues) &&
contentTypeValues.Any() &&
contentTypeValues.First() is string contentTypeValue)
activityForAttributes?.SetTag("http.request_content_type", contentTypeValue);
}
return message;
}
/// <summary>
/// Enable the backing store with the provided <see cref="IBackingStoreFactory"/>
/// </summary>
/// <param name="backingStoreFactory">The <see cref="IBackingStoreFactory"/> to use</param>
public void EnableBackingStore(IBackingStoreFactory backingStoreFactory)
{
pNodeFactory = ApiClientBuilder.EnableBackingStoreForParseNodeFactory(pNodeFactory) ?? throw new InvalidOperationException("Could not enable backing store for the parse node factory");
sWriterFactory = ApiClientBuilder.EnableBackingStoreForSerializationWriterFactory(sWriterFactory) ?? throw new InvalidOperationException("Could not enable backing store for the serializer writer factory");
if(backingStoreFactory != null)
BackingStoreFactorySingleton.Instance = backingStoreFactory;
}
/// <summary>
/// Dispose/cleanup the client
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose/cleanup the client
/// </summary>
protected virtual void Dispose(bool disposing)
{
// Cleanup
if(createdClient)
{
activitySource?.Dispose();
client?.Dispose();
}
}
}
}