-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adjust System.Net.Http metrics #89809
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
eee946f
adjust System.Net.Http metrics to the new spec
antonfirsov 709d058
Merge branch 'main' into adjust-http-metrics-02
antonfirsov df18ba5
also adjust descriptions
antonfirsov 8f43983
simpler comment
antonfirsov cea486e
_idleSinceTickCount init should not depend on metrics
antonfirsov 1260105
PATCH RequestMetrics_EmitNormalizedMethodTags for wasm
antonfirsov 29ded04
fix typo
antonfirsov 5687758
Merge branch 'main' into adjust-http-metrics-02
antonfirsov ce3eb0c
add an assertion to guard the HttpRequestError mapping
antonfirsov 653c6e7
disable RequestMetrics_EmitNormalizedMethodTags on browser completely
antonfirsov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Collections.Generic; | ||
using System.Diagnostics; | ||
using System.Diagnostics.Metrics; | ||
using System.Threading; | ||
|
@@ -11,8 +12,7 @@ namespace System.Net.Http.Metrics | |
internal sealed class MetricsHandler : HttpMessageHandlerStage | ||
{ | ||
private readonly HttpMessageHandler _innerHandler; | ||
private readonly UpDownCounter<long> _currentRequests; | ||
private readonly Counter<long> _failedRequests; | ||
private readonly UpDownCounter<long> _activeRequests; | ||
private readonly Histogram<double> _requestsDuration; | ||
|
||
public MetricsHandler(HttpMessageHandler innerHandler, IMeterFactory? meterFactory, out Meter meter) | ||
|
@@ -22,21 +22,18 @@ public MetricsHandler(HttpMessageHandler innerHandler, IMeterFactory? meterFacto | |
meter = meterFactory?.Create("System.Net.Http") ?? SharedMeter.Instance; | ||
|
||
// Meter has a cache for the instruments it owns | ||
_currentRequests = meter.CreateUpDownCounter<long>( | ||
"http-client-current-requests", | ||
_activeRequests = meter.CreateUpDownCounter<long>( | ||
"http.client.active_requests", | ||
description: "Number of outbound HTTP requests that are currently active on the client."); | ||
_failedRequests = meter.CreateCounter<long>( | ||
"http-client-failed-requests", | ||
description: "Number of outbound HTTP requests that have failed."); | ||
_requestsDuration = meter.CreateHistogram<double>( | ||
"http-client-request-duration", | ||
"http.client.request.duration", | ||
unit: "s", | ||
description: "The duration of outbound HTTP requests."); | ||
MihaZupan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
internal override ValueTask<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken) | ||
{ | ||
if (_currentRequests.Enabled || _failedRequests.Enabled || _requestsDuration.Enabled) | ||
if (_activeRequests.Enabled || _requestsDuration.Enabled) | ||
{ | ||
return SendAsyncWithMetrics(request, async, cancellationToken); | ||
} | ||
|
@@ -83,67 +80,90 @@ protected override void Dispose(bool disposing) | |
|
||
private (long StartTimestamp, bool RecordCurrentRequests) RequestStart(HttpRequestMessage request) | ||
{ | ||
bool recordCurrentRequests = _currentRequests.Enabled; | ||
bool recordCurrentRequests = _activeRequests.Enabled; | ||
long startTimestamp = Stopwatch.GetTimestamp(); | ||
|
||
if (recordCurrentRequests) | ||
{ | ||
TagList tags = InitializeCommonTags(request); | ||
_currentRequests.Add(1, tags); | ||
_activeRequests.Add(1, tags); | ||
} | ||
|
||
return (startTimestamp, recordCurrentRequests); | ||
} | ||
|
||
private void RequestStop(HttpRequestMessage request, HttpResponseMessage? response, Exception? exception, long startTimestamp, bool recordCurrentRequsts) | ||
private void RequestStop(HttpRequestMessage request, HttpResponseMessage? response, Exception? exception, long startTimestamp, bool recordCurrentRequests) | ||
{ | ||
TagList tags = InitializeCommonTags(request); | ||
|
||
if (recordCurrentRequsts) | ||
if (recordCurrentRequests) | ||
{ | ||
_currentRequests.Add(-1, tags); | ||
_activeRequests.Add(-1, tags); | ||
} | ||
|
||
bool recordRequestDuration = _requestsDuration.Enabled; | ||
bool recordFailedRequests = _failedRequests.Enabled && response is null; | ||
if (!_requestsDuration.Enabled) | ||
{ | ||
return; | ||
} | ||
|
||
HttpMetricsEnrichmentContext? enrichmentContext = null; | ||
if (recordRequestDuration || recordFailedRequests) | ||
if (response is not null) | ||
{ | ||
if (response is not null) | ||
{ | ||
tags.Add("status-code", GetBoxedStatusCode((int)response.StatusCode)); | ||
tags.Add("protocol", GetProtocolName(response.Version)); | ||
} | ||
enrichmentContext = HttpMetricsEnrichmentContext.GetEnrichmentContextForRequest(request); | ||
tags.Add("http.response.status_code", GetBoxedStatusCode((int)response.StatusCode)); | ||
tags.Add("network.protocol.version", GetProtocolVersionString(response.Version)); | ||
} | ||
else | ||
{ | ||
Debug.Assert(exception is not null); | ||
tags.Add("http.error.reason", GetErrorReason(exception)); | ||
} | ||
TimeSpan durationTime = Stopwatch.GetElapsedTime(startTimestamp, Stopwatch.GetTimestamp()); | ||
|
||
HttpMetricsEnrichmentContext? enrichmentContext = HttpMetricsEnrichmentContext.GetEnrichmentContextForRequest(request); | ||
if (enrichmentContext is null) | ||
{ | ||
if (recordRequestDuration) | ||
{ | ||
TimeSpan duration = Stopwatch.GetElapsedTime(startTimestamp, Stopwatch.GetTimestamp()); | ||
_requestsDuration.Record(duration.TotalSeconds, tags); | ||
} | ||
|
||
if (recordFailedRequests) | ||
{ | ||
_failedRequests.Add(1, tags); | ||
} | ||
_requestsDuration.Record(durationTime.TotalSeconds, tags); | ||
} | ||
else | ||
{ | ||
enrichmentContext.RecordWithEnrichment(request, response, exception, startTimestamp, tags, recordRequestDuration, recordFailedRequests, _requestsDuration, _failedRequests); | ||
enrichmentContext.RecordDurationWithEnrichment(request, response, exception, durationTime, tags, _requestsDuration); | ||
} | ||
} | ||
|
||
private static string GetErrorReason(Exception exception) | ||
{ | ||
if (exception is OperationCanceledException) | ||
{ | ||
return "cancellation"; | ||
} | ||
else if (exception is HttpRequestException e) | ||
{ | ||
Debug.Assert(Enum.GetValues<HttpRequestError>().Length == 12, "We need to extend the mapping in case new values are added to HttpRequestError."); | ||
return e.HttpRequestError switch | ||
antonfirsov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
HttpRequestError.NameResolutionError => "name_resolution_error", | ||
HttpRequestError.ConnectionError => "connection_error", | ||
HttpRequestError.SecureConnectionError => "secure_connection_error", | ||
HttpRequestError.HttpProtocolError => "http_protocol_error", | ||
HttpRequestError.ExtendedConnectNotSupported => "extended_connect_not_supported", | ||
HttpRequestError.VersionNegotiationError => "version_negotiation_error", | ||
HttpRequestError.UserAuthenticationError => "user_authentication_error", | ||
HttpRequestError.ProxyTunnelError => "proxy_tunnel_error", | ||
HttpRequestError.InvalidResponse => "invalid_response", | ||
HttpRequestError.ResponseEnded => "response_ended", | ||
HttpRequestError.ConfigurationLimitExceeded => "configuration_limit_exceeded", | ||
_ => "_OTHER" | ||
}; | ||
} | ||
return "_OTHER"; | ||
} | ||
|
||
private static string GetProtocolName(Version httpVersion) => (httpVersion.Major, httpVersion.Minor) switch | ||
private static string GetProtocolVersionString(Version httpVersion) => (httpVersion.Major, httpVersion.Minor) switch | ||
{ | ||
(1, 0) => "HTTP/1.0", | ||
(1, 1) => "HTTP/1.1", | ||
(2, 0) => "HTTP/2", | ||
(3, 0) => "HTTP/3", | ||
_ => $"HTTP/{httpVersion.Major}.{httpVersion.Minor}" | ||
(1, 0) => "1.0", | ||
(1, 1) => "1.1", | ||
(2, 0) => "2.0", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yup I will open a follow-up PR. |
||
(3, 0) => "3.0", | ||
_ => httpVersion.ToString() | ||
}; | ||
|
||
private static TagList InitializeCommonTags(HttpRequestMessage request) | ||
|
@@ -152,19 +172,26 @@ private static TagList InitializeCommonTags(HttpRequestMessage request) | |
|
||
if (request.RequestUri is Uri requestUri && requestUri.IsAbsoluteUri) | ||
{ | ||
tags.Add("scheme", requestUri.Scheme); | ||
tags.Add("host", requestUri.Host); | ||
tags.Add("url.scheme", requestUri.Scheme); | ||
tags.Add("server.address", requestUri.Host); | ||
// Add port tag when not the default value for the current scheme | ||
if (!requestUri.IsDefaultPort) | ||
{ | ||
tags.Add("port", requestUri.Port); | ||
tags.Add("server.port", requestUri.Port); | ||
} | ||
} | ||
tags.Add("method", request.Method.Method); | ||
tags.Add(GetMethodTag(request.Method)); | ||
|
||
return tags; | ||
} | ||
|
||
internal static KeyValuePair<string, object?> GetMethodTag(HttpMethod method) | ||
{ | ||
// Return canonical names for known methods and "_OTHER" for unknown ones. | ||
HttpMethod? known = HttpMethod.GetKnownMethod(method.Method); | ||
return new KeyValuePair<string, object?>("http.request.method", known?.Method ?? "_OTHER"); | ||
} | ||
|
||
private static object[]? s_boxedStatusCodes; | ||
|
||
private static object GetBoxedStatusCode(int statusCode) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
unit should be "{request}"