/
ClientDiagnostics.cs
220 lines (187 loc) · 8.42 KB
/
ClientDiagnostics.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#nullable enable
namespace Azure.Core.Pipeline
{
internal class ClientDiagnostics : DiagnosticScopeFactory
{
private const string DefaultMessage = "Service request failed.";
private readonly HttpMessageSanitizer _sanitizer;
public ClientDiagnostics(ClientOptions options)
: this(options.GetType().Namespace!,
GetResourceProviderNamespace(options.GetType().Assembly),
options.Diagnostics)
{
}
public ClientDiagnostics(string optionsNamespace, string? providerNamespace, DiagnosticsOptions diagnosticsOptions)
: base(optionsNamespace, providerNamespace, diagnosticsOptions.IsDistributedTracingEnabled)
{
_sanitizer = CreateMessageSanitizer(diagnosticsOptions);
}
internal static HttpMessageSanitizer CreateMessageSanitizer(DiagnosticsOptions diagnostics)
{
return new HttpMessageSanitizer(
diagnostics.LoggedQueryParameters.ToArray(),
diagnostics.LoggedHeaderNames.ToArray());
}
/// <summary>
/// Partial method that can optionally be defined to extract the error
/// message, code, and details in a service specific manner.
/// </summary>
/// <param name="content">The error content.</param>
/// <param name="responseHeaders">The response headers.</param>
/// <param name="additionalInfo">Additional error details.</param>
protected virtual ResponseError? ExtractFailureContent(
string? content,
ResponseHeaders responseHeaders,
ref IDictionary<string, string>? additionalInfo)
{
return ExtractAzureErrorContent(content);
}
internal static ResponseError? ExtractAzureErrorContent(string? content)
{
try
{
// Optimistic check for JSON object we expect
if (content == null ||
!content.StartsWith("{", StringComparison.OrdinalIgnoreCase)) return null;
return JsonSerializer.Deserialize<ErrorResponse>(content)?.Error;
}
catch (Exception)
{
// Ignore any failures - unexpected content will be
// included verbatim in the detailed error message
}
return null;
}
public async ValueTask<RequestFailedException> CreateRequestFailedExceptionAsync(Response response, ResponseError? error = null, IDictionary<string, string>? additionalInfo = null, Exception? innerException = null)
{
var content = await ReadContentAsync(response, true).ConfigureAwait(false);
error ??= ExtractFailureContent(content, response.Headers, ref additionalInfo);
return CreateRequestFailedExceptionWithContent(response, error, content, additionalInfo, innerException);
}
public RequestFailedException CreateRequestFailedException(Response response, ResponseError? error = null, IDictionary<string, string>? additionalInfo = null, Exception? innerException = null)
{
string? content = ReadContentAsync(response, false).EnsureCompleted();
error ??= ExtractFailureContent(content, response.Headers, ref additionalInfo);
return CreateRequestFailedExceptionWithContent(response, error, content, additionalInfo, innerException);
}
private RequestFailedException CreateRequestFailedExceptionWithContent(
Response response,
ResponseError? error = null,
string? content = null,
IDictionary<string, string>? additionalInfo = null,
Exception? innerException = null)
{
var formatMessage = CreateRequestFailedMessageWithContent(response, error, content, additionalInfo, _sanitizer);
var exception = new RequestFailedException(response.Status, formatMessage, error?.Code, innerException);
if (additionalInfo != null)
{
foreach (KeyValuePair<string, string> keyValuePair in additionalInfo)
{
exception.Data.Add(keyValuePair.Key, keyValuePair.Value);
}
}
return exception;
}
public async ValueTask<string> CreateRequestFailedMessageAsync(Response response, ResponseError? error, IDictionary<string, string>? additionalInfo, bool async)
{
var content = await ReadContentAsync(response, async).ConfigureAwait(false);
return CreateRequestFailedMessageWithContent(response, error, content, additionalInfo, _sanitizer);
}
internal static string CreateRequestFailedMessageWithContent(Response response, ResponseError? error, string? content, IDictionary<string, string>? additionalInfo, HttpMessageSanitizer sanitizer)
{
StringBuilder messageBuilder = new StringBuilder();
messageBuilder
.AppendLine(error?.Message ?? DefaultMessage)
.Append("Status: ")
.Append(response.Status.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(response.ReasonPhrase))
{
messageBuilder.Append(" (")
.Append(response.ReasonPhrase)
.AppendLine(")");
}
else
{
messageBuilder.AppendLine();
}
if (!string.IsNullOrWhiteSpace(error?.Code))
{
messageBuilder.Append("ErrorCode: ")
.Append(error?.Code)
.AppendLine();
}
if (additionalInfo != null && additionalInfo.Count > 0)
{
messageBuilder
.AppendLine()
.AppendLine("Additional Information:");
foreach (KeyValuePair<string, string> info in additionalInfo)
{
messageBuilder
.Append(info.Key)
.Append(": ")
.AppendLine(info.Value);
}
}
if (content != null)
{
messageBuilder
.AppendLine()
.AppendLine("Content:")
.AppendLine(content);
}
messageBuilder
.AppendLine()
.AppendLine("Headers:");
foreach (HttpHeader responseHeader in response.Headers)
{
string headerValue = sanitizer.SanitizeHeader(responseHeader.Name, responseHeader.Value);
messageBuilder.AppendLine($"{responseHeader.Name}: {headerValue}");
}
return messageBuilder.ToString();
}
internal static async ValueTask<string?> ReadContentAsync(Response response, bool async)
{
string? content = null;
if (response.ContentStream != null &&
ContentTypeUtilities.TryGetTextEncoding(response.Headers.ContentType, out var encoding))
{
using (var streamReader = new StreamReader(response.ContentStream, encoding))
{
content = async ? await streamReader.ReadToEndAsync().ConfigureAwait(false) : streamReader.ReadToEnd();
}
}
return content;
}
internal static string? GetResourceProviderNamespace(Assembly assembly)
{
foreach (var customAttribute in assembly.GetCustomAttributes(true))
{
// Weak bind internal shared type
var attributeType = customAttribute.GetType();
if (attributeType.Name == "AzureResourceProviderNamespaceAttribute")
{
return attributeType.GetProperty("ResourceProviderNamespace")?.GetValue(customAttribute) as string;
}
}
return null;
}
private class ErrorResponse
{
[JsonPropertyName("error")]
public ResponseError? Error { get; set; }
}
}
}