Skip to content

Commit

Permalink
Cache request values when hosting metrics are enabled (#55351)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK committed Apr 26, 2024
1 parent eb18cb2 commit c157c5c
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 34 deletions.
2 changes: 1 addition & 1 deletion src/Hosting/Hosting/src/Internal/HostingApplication.cs
Expand Up @@ -162,7 +162,7 @@ public void Reset()
HasDiagnosticListener = false;
MetricsEnabled = false;
EventLogEnabled = false;
MetricsTagsFeature?.TagsList.Clear();
MetricsTagsFeature?.Reset();
}
}
}
19 changes: 11 additions & 8 deletions src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs
Expand Up @@ -60,6 +60,10 @@ public void BeginRequest(HttpContext httpContext, HostingApplication.Context con
context.MetricsTagsFeature ??= new HttpMetricsTagsFeature();
httpContext.Features.Set<IHttpMetricsTagsFeature>(context.MetricsTagsFeature);

context.MetricsTagsFeature.Method = httpContext.Request.Method;
context.MetricsTagsFeature.Protocol = httpContext.Request.Protocol;
context.MetricsTagsFeature.Scheme = httpContext.Request.Scheme;

startTimestamp = Stopwatch.GetTimestamp();

// To keep the hot path short we defer logging in this function to non-inlines
Expand Down Expand Up @@ -152,19 +156,18 @@ public void RequestEnd(HttpContext httpContext, Exception? exception, HostingApp
{
var endpoint = HttpExtensions.GetOriginalEndpoint(httpContext);
var route = endpoint?.Metadata.GetMetadata<IRouteDiagnosticsMetadata>()?.Route;
var customTags = context.MetricsTagsFeature?.TagsList;

Debug.Assert(context.MetricsTagsFeature != null, "MetricsTagsFeature should be set if MetricsEnabled is true.");

_metrics.RequestEnd(
httpContext.Request.Protocol,
httpContext.Request.IsHttps,
httpContext.Request.Scheme,
httpContext.Request.Method,
httpContext.Request.Host,
context.MetricsTagsFeature.Protocol!,
context.MetricsTagsFeature.Scheme!,
context.MetricsTagsFeature.Method!,
route,
httpContext.Response.StatusCode,
reachedPipelineEnd,
exception,
customTags,
context.MetricsTagsFeature.TagsList,
startTimestamp,
currentTimestamp);
}
Expand Down Expand Up @@ -372,7 +375,7 @@ private void RecordRequestStartEventLog(HttpContext httpContext)
[MethodImpl(MethodImplOptions.NoInlining)]
private void RecordRequestStartMetrics(HttpContext httpContext)
{
_metrics.RequestStart(httpContext.Request.IsHttps, httpContext.Request.Scheme, httpContext.Request.Method, httpContext.Request.Host);
_metrics.RequestStart(httpContext.Request.Scheme, httpContext.Request.Method);
}

[MethodImpl(MethodImplOptions.NoInlining)]
Expand Down
30 changes: 5 additions & 25 deletions src/Hosting/Hosting/src/Internal/HostingMetrics.cs
Expand Up @@ -33,18 +33,18 @@ public HostingMetrics(IMeterFactory meterFactory)
}

// Note: Calling code checks whether counter is enabled.
public void RequestStart(bool isHttps, string scheme, string method, HostString host)
public void RequestStart(string scheme, string method)
{
// Tags must match request end.
var tags = new TagList();
InitializeRequestTags(ref tags, isHttps, scheme, method, host);
InitializeRequestTags(ref tags, scheme, method);
_activeRequestsCounter.Add(1, tags);
}

public void RequestEnd(string protocol, bool isHttps, string scheme, string method, HostString host, string? route, int statusCode, bool unhandledRequest, Exception? exception, List<KeyValuePair<string, object?>>? customTags, long startTimestamp, long currentTimestamp)
public void RequestEnd(string protocol, string scheme, string method, string? route, int statusCode, bool unhandledRequest, Exception? exception, List<KeyValuePair<string, object?>>? customTags, long startTimestamp, long currentTimestamp)
{
var tags = new TagList();
InitializeRequestTags(ref tags, isHttps, scheme, method, host);
InitializeRequestTags(ref tags, scheme, method);

// Tags must match request start.
if (_activeRequestsCounter.Enabled)
Expand Down Expand Up @@ -100,30 +100,10 @@ public void Dispose()

public bool IsEnabled() => _activeRequestsCounter.Enabled || _requestDuration.Enabled;

private static void InitializeRequestTags(ref TagList tags, bool isHttps, string scheme, string method, HostString host)
private static void InitializeRequestTags(ref TagList tags, string scheme, string method)
{
tags.Add("url.scheme", scheme);
tags.Add("http.request.method", ResolveHttpMethod(method));

_ = isHttps;
_ = host;
// TODO: Support configuration for enabling host header annotations
/*
if (host.HasValue)
{
tags.Add("server.address", host.Host);
// Port is parsed each time it's accessed. Store part in local variable.
if (host.Port is { } port)
{
// Add port tag when not the default value for the current scheme
if ((isHttps && port != 443) || (!isHttps && port != 80))
{
tags.Add("server.port", port);
}
}
}
*/
}

private static readonly object[] BoxedStatusCodes = new object[512];
Expand Down
15 changes: 15 additions & 0 deletions src/Hosting/Hosting/src/Internal/HttpMetricsTagsFeature.cs
Expand Up @@ -10,4 +10,19 @@ internal sealed class HttpMetricsTagsFeature : IHttpMetricsTagsFeature
ICollection<KeyValuePair<string, object?>> IHttpMetricsTagsFeature.Tags => TagsList;

public List<KeyValuePair<string, object?>> TagsList { get; } = new List<KeyValuePair<string, object?>>();

// Cache request values when request starts. These are used when writing metrics when the request ends.
// This ensures that the tags match between the start and end of the request. Important for up/down counters.
public string? Method { get; set; }
public string? Scheme { get; set; }
public string? Protocol { get; set; }

public void Reset()
{
TagsList.Clear();

Method = null;
Scheme = null;
Protocol = null;
}
}
59 changes: 59 additions & 0 deletions src/Hosting/Hosting/test/HostingApplicationDiagnosticsTests.cs
Expand Up @@ -174,6 +174,65 @@ public void MetricsEnabled()
Assert.False(context.EventLogEnabled);
}

[Fact]
public void Metrics_RequestChanges_OriginalValuesUsed()
{
// Arrange
var hostingEventSource = new HostingEventSource(Guid.NewGuid().ToString());

var testMeterFactory = new TestMeterFactory();
using var activeRequestsCollector = new MetricCollector<long>(testMeterFactory, HostingMetrics.MeterName, "http.server.active_requests");
using var requestDurationCollector = new MetricCollector<double>(testMeterFactory, HostingMetrics.MeterName, "http.server.request.duration");

// Act
var hostingApplication = CreateApplication(out var features, eventSource: hostingEventSource, meterFactory: testMeterFactory, configure: c =>
{
c.Request.Protocol = "1.1";
c.Request.Scheme = "http";
c.Request.Method = "POST";
c.Request.Host = new HostString("localhost");
c.Request.Path = "/hello";
c.Request.ContentType = "text/plain";
c.Request.ContentLength = 1024;
});
var context = hostingApplication.CreateContext(features);

Assert.Collection(activeRequestsCollector.GetMeasurementSnapshot(),
m =>
{
Assert.Equal(1, m.Value);
Assert.Equal("http", m.Tags["url.scheme"]);
Assert.Equal("POST", m.Tags["http.request.method"]);
});

context.HttpContext.Request.Protocol = "HTTP/2";
context.HttpContext.Request.Method = "PUT";
context.HttpContext.Request.Scheme = "https";
context.HttpContext.Features.GetRequiredFeature<IHttpMetricsTagsFeature>().Tags.Add(new KeyValuePair<string, object>("custom.tag", "custom.value"));

hostingApplication.DisposeContext(context, null);

// Assert
Assert.Collection(activeRequestsCollector.GetMeasurementSnapshot(),
m =>
{
Assert.Equal(1, m.Value);
Assert.Equal("http", m.Tags["url.scheme"]);
Assert.Equal("POST", m.Tags["http.request.method"]);
},
m =>
{
Assert.Equal(-1, m.Value);
Assert.Equal("http", m.Tags["url.scheme"]);
Assert.Equal("POST", m.Tags["http.request.method"]);
});

Assert.Empty(context.MetricsTagsFeature.TagsList);
Assert.Null(context.MetricsTagsFeature.Scheme);
Assert.Null(context.MetricsTagsFeature.Method);
Assert.Null(context.MetricsTagsFeature.Protocol);
}

[Fact]
public void DisposeContextDoesNotThrowWhenContextScopeIsNull()
{
Expand Down

0 comments on commit c157c5c

Please sign in to comment.