Skip to content

Blazor - rendering metrics and tracing #61609

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

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
cebb68e
rebase
pavelsavara Apr 23, 2025
6664645
Merge branch 'main' into blazor_metrics_feedback
pavelsavara Apr 23, 2025
0bcd459
more
pavelsavara Apr 24, 2025
2557f08
- remove FeatureSwitchDefinition for now
pavelsavara Apr 24, 2025
4c75495
whitespace
pavelsavara Apr 24, 2025
0f3d48a
navigation draft
pavelsavara Apr 24, 2025
cf15c8d
cleanup
pavelsavara Apr 24, 2025
550f633
cleanup
pavelsavara Apr 24, 2025
9ab8a84
more
pavelsavara Apr 25, 2025
0a4d488
IsAllDataRequested
pavelsavara Apr 25, 2025
cf2ab99
- ComponentsActivitySourceTest
pavelsavara Apr 28, 2025
44fa207
Update src/Components/Components/src/ComponentsMetrics.cs
pavelsavara Apr 30, 2025
105b02f
Update src/Components/Components/src/ComponentsMetrics.cs
pavelsavara Apr 30, 2025
63f8a69
Update src/Components/Components/src/ComponentsMetrics.cs
pavelsavara Apr 30, 2025
860931d
feedback
pavelsavara Apr 30, 2025
de22914
fix tests
pavelsavara Apr 30, 2025
5ca497d
update_parameters feedback
pavelsavara Apr 30, 2025
2ae95e0
Update src/Components/Components/src/ComponentsActivitySource.cs
pavelsavara May 2, 2025
b9331d9
Update src/Components/Components/src/ComponentsActivitySource.cs
pavelsavara May 2, 2025
96f1d6a
Update src/Components/Components/src/ComponentsActivitySource.cs
pavelsavara May 2, 2025
1c61f50
feedback
pavelsavara May 2, 2025
bda2aec
ActivityKind.Internal
pavelsavara May 6, 2025
84dbfd2
aspnetcore.components prefix for tags
pavelsavara May 6, 2025
3b475a4
- merge exception and duration metrics
pavelsavara May 7, 2025
2ea50aa
Event -> HandleEvent trace rename
pavelsavara May 7, 2025
971f484
remove aspnetcore.components.circuit.count
pavelsavara May 7, 2025
db97013
Improve descriptions
pavelsavara May 7, 2025
09986be
Merge branch 'main' into blazor_metrics_feedback
pavelsavara May 15, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 177 additions & 0 deletions src/Components/Components/src/ComponentsActivitySource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// This is instance scoped per renderer
/// </summary>
internal class ComponentsActivitySource
{
internal const string Name = "Microsoft.AspNetCore.Components";
internal const string OnCircuitName = $"{Name}.CircuitStart";
internal const string OnRouteName = $"{Name}.RouteChange";
internal const string OnEventName = $"{Name}.HandleEvent";

private ActivityContext _httpContext;
private ActivityContext _circuitContext;
private string? _circuitId;
private ActivityContext _routeContext;

private ActivitySource ActivitySource { get; } = new ActivitySource(Name);

public static ActivityContext CaptureHttpContext()
{
var parentActivity = Activity.Current;
if (parentActivity is not null && parentActivity.OperationName == "Microsoft.AspNetCore.Hosting.HttpRequestIn" && parentActivity.Recorded)
{
return parentActivity.Context;
}
return default;
}
Comment on lines +25 to +33
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Layering wise this shouldn't go here.

Microsoft.AspNetCore.Components shoudn't have a dependency on Microsoft.AspNetCore.Hosting

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please be more specific, what do you want to see instead ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you trying to get the activity of the current request here? There is a feature in the features collection for doing that: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.features.ihttpactivityfeature.activity?view=aspnetcore-9.0

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I get that from DI without passing HttpContext thru all SignalR layers ? Or from some TLS ?

Copy link
Member

@JamesNK JamesNK May 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It comes from HttpContext. It's in the features collection.


public Activity? StartCircuitActivity(string circuitId, ActivityContext httpContext)
{
_circuitId = circuitId;

var activity = ActivitySource.CreateActivity(OnCircuitName, ActivityKind.Internal, parentId: null, null, null);
if (activity is not null)
{
if (activity.IsAllDataRequested)
{
if (_circuitId != null)
{
activity.SetTag("aspnetcore.components.circuit.id", _circuitId);
}
if (httpContext != default)
{
activity.AddLink(new ActivityLink(httpContext));
}
}
activity.DisplayName = $"Circuit {circuitId ?? ""}";
activity.Start();
_circuitContext = activity.Context;
}
return activity;
}

public void FailCircuitActivity(Activity? activity, Exception ex)
{
_circuitContext = default;
if (activity != null && !activity.IsStopped)
{
activity.SetTag("error.type", ex.GetType().FullName);
activity.SetStatus(ActivityStatusCode.Error);
activity.Stop();
}
}

public Activity? StartRouteActivity(string componentType, string route)
{
if (_httpContext == default)
{
_httpContext = CaptureHttpContext();
}

var activity = ActivitySource.CreateActivity(OnRouteName, ActivityKind.Internal, parentId: null, null, null);
if (activity is not null)
{
if (activity.IsAllDataRequested)
{
if (_circuitId != null)
{
activity.SetTag("aspnetcore.components.circuit.id", _circuitId);
}
if (componentType != null)
{
activity.SetTag("aspnetcore.components.type", componentType);
}
if (route != null)
{
activity.SetTag("aspnetcore.components.route", route);
}
if (_httpContext != default)
{
activity.AddLink(new ActivityLink(_httpContext));
}
if (_circuitContext != default)
{
activity.AddLink(new ActivityLink(_circuitContext));
}
}

activity.DisplayName = $"Route {route ?? "[unknown path]"} -> {componentType ?? "[unknown component]"}";
activity.Start();
_routeContext = activity.Context;
}
return activity;
}
Comment on lines +35 to +110
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should go on the Server assembly.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we move it to different class/instance, we would not be able to use _circuitId and _circuitContext. And we would have to create lot of semi-public interfaces to pass that info between those classes. Are you sure it's worth it ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't the CircuitId on a parent activity? (like start circuit or something like that)

All the _httpContext, _circuitContext on that event is at the wrong level of abstraction. I don't know if it can be set on the parent activity and flowed into this one, but the route activity should not know about _circuitContext or _httpContext.

To put it in a different way, this method/class should not be responsible for resolving the parent activity to link to. That should be provided somehow. We might need public API for that.

We don't want to keep adding to this list when/if we add new render modes. For example, I imagine WebView migth also want to track its own parent activity and it would require us to add it here.


public Activity? StartEventActivity(string? componentType, string? methodName, string? attributeName)
{
var activity = ActivitySource.CreateActivity(OnEventName, ActivityKind.Internal, parentId: null, null, null);
if (activity is not null)
{
if (activity.IsAllDataRequested)
{
if (_circuitId != null)
{
activity.SetTag("aspnetcore.components.circuit.id", _circuitId);
}
if (componentType != null)
{
activity.SetTag("aspnetcore.components.type", componentType);
}
if (methodName != null)
{
activity.SetTag("aspnetcore.components.method", methodName);
}
if (attributeName != null)
{
activity.SetTag("aspnetcore.components.attribute.name", attributeName);
}
if (_httpContext != default)
{
activity.AddLink(new ActivityLink(_httpContext));
}
if (_circuitContext != default)
{
activity.AddLink(new ActivityLink(_circuitContext));
}
if (_routeContext != default)
{
activity.AddLink(new ActivityLink(_routeContext));
}
}

activity.DisplayName = $"Event {attributeName ?? "[unknown attribute]"} -> {componentType ?? "[unknown component]"}.{methodName ?? "[unknown method]"}";
activity.Start();
}
return activity;
}

public static void FailEventActivity(Activity? activity, Exception ex)
{
if (activity != null && !activity.IsStopped)
{
activity.SetTag("error.type", ex.GetType().FullName);
activity.SetStatus(ActivityStatusCode.Error);
activity.Stop();
}
}

public static async Task CaptureEventStopAsync(Task task, Activity? activity)
{
try
{
await task;
activity?.Stop();
}
catch (Exception ex)
{
FailEventActivity(activity, ex);
}
}
}
Comment on lines +112 to +177
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably needs to go into a different class ComponentEventActivitySource (or any other name, RendererEventMetrics or something like that)

191 changes: 191 additions & 0 deletions src/Components/Components/src/ComponentsMetrics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Diagnostics.Metrics;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Components;

internal sealed class ComponentsMetrics : IDisposable
{
public const string MeterName = "Microsoft.AspNetCore.Components";
public const string LifecycleMeterName = "Microsoft.AspNetCore.Components.Lifecycle";
private readonly Meter _meter;
private readonly Meter _lifeCycleMeter;

private readonly Counter<long> _navigationCount;

private readonly Histogram<double> _eventDuration;
private readonly Histogram<double> _parametersDuration;
private readonly Histogram<double> _batchDuration;

public bool IsNavigationEnabled => _navigationCount.Enabled;

public bool IsEventEnabled => _eventDuration.Enabled;

public bool IsParametersEnabled => _parametersDuration.Enabled;

public bool IsBatchEnabled => _batchDuration.Enabled;

public ComponentsMetrics(IMeterFactory meterFactory)
{
Debug.Assert(meterFactory != null);

_meter = meterFactory.Create(MeterName);
_lifeCycleMeter = meterFactory.Create(LifecycleMeterName);

_navigationCount = _meter.CreateCounter<long>(
"aspnetcore.components.navigation",
unit: "{route}",
description: "Total number of route changes.");

_eventDuration = _meter.CreateHistogram(
"aspnetcore.components.event_handler",
unit: "s",
description: "Duration of processing browser event. It includes business logic of the component but not affected child components.",
advice: new InstrumentAdvice<double> { HistogramBucketBoundaries = MetricsConstants.ShortSecondsBucketBoundaries });

_parametersDuration = _lifeCycleMeter.CreateHistogram(
"aspnetcore.components.update_parameters",
unit: "s",
description: "Duration of processing component parameters. It includes business logic of the component.",
advice: new InstrumentAdvice<double> { HistogramBucketBoundaries = MetricsConstants.BlazorRenderingSecondsBucketBoundaries });

_batchDuration = _lifeCycleMeter.CreateHistogram(
"aspnetcore.components.render_diff",
unit: "s",
description: "Duration of rendering component tree and producing HTML diff. It includes business logic of the changed components.",
advice: new InstrumentAdvice<double> { HistogramBucketBoundaries = MetricsConstants.BlazorRenderingSecondsBucketBoundaries });
}

public void Navigation(string componentType, string route)
{
var tags = new TagList
{
{ "aspnetcore.components.type", componentType ?? "unknown" },
{ "aspnetcore.components.route", route ?? "unknown" },
};

_navigationCount.Add(1, tags);
}

public async Task CaptureEventDuration(Task task, long startTimestamp, string? componentType, string? methodName, string? attributeName)
{
var tags = new TagList
{
{ "aspnetcore.components.type", componentType ?? "unknown" },
{ "aspnetcore.components.method", methodName ?? "unknown" },
{ "aspnetcore.components.attribute.name", attributeName ?? "unknown" }
};

try
{
await task;
}
catch (Exception ex)
{
tags.Add("error.type", ex.GetType().FullName ?? "unknown");
}
var duration = Stopwatch.GetElapsedTime(startTimestamp);
_eventDuration.Record(duration.TotalSeconds, tags);
}

public void FailEventSync(Exception ex, long startTimestamp, string? componentType, string? methodName, string? attributeName)
{
var tags = new TagList
{
{ "aspnetcore.components.type", componentType ?? "unknown" },
{ "aspnetcore.components.method", methodName ?? "unknown" },
{ "aspnetcore.components.attribute.name", attributeName ?? "unknown" },
{ "error.type", ex.GetType().FullName ?? "unknown" }
};
var duration = Stopwatch.GetElapsedTime(startTimestamp);
_eventDuration.Record(duration.TotalSeconds, tags);
}

public async Task CaptureParametersDuration(Task task, long startTimestamp, string? componentType)
{
var tags = new TagList
{
{ "aspnetcore.components.type", componentType ?? "unknown" },
};

try
{
await task;
}
catch(Exception ex)
{
tags.Add("error.type", ex.GetType().FullName ?? "unknown");
}
var duration = Stopwatch.GetElapsedTime(startTimestamp);
_parametersDuration.Record(duration.TotalSeconds, tags);
}

public void FailParametersSync(Exception ex, long startTimestamp, string? componentType)
{
var duration = Stopwatch.GetElapsedTime(startTimestamp);
var tags = new TagList
{
{ "aspnetcore.components.type", componentType ?? "unknown" },
{ "error.type", ex.GetType().FullName ?? "unknown" }
};
_parametersDuration.Record(duration.TotalSeconds, tags);
}

public async Task CaptureBatchDuration(Task task, long startTimestamp, int diffLength)
{
var tags = new TagList
{
{ "aspnetcore.components.diff.length", BucketDiffLength(diffLength) }
};

try
{
await task;
}
catch (Exception ex)
{
tags.Add("error.type", ex.GetType().FullName ?? "unknown");
}
var duration = Stopwatch.GetElapsedTime(startTimestamp);
_batchDuration.Record(duration.TotalSeconds, tags);
}

public void FailBatchSync(Exception ex, long startTimestamp)
{
var duration = Stopwatch.GetElapsedTime(startTimestamp);
var tags = new TagList
{
{ "aspnetcore.components.diff.length", 0 },
{ "error.type", ex.GetType().FullName ?? "unknown" }
};
_batchDuration.Record(duration.TotalSeconds, tags);
}

private static int BucketDiffLength(int diffLength)
{
return diffLength switch
{
<= 1 => 1,
<= 2 => 2,
<= 5 => 5,
<= 10 => 10,
<= 20 => 20,
<= 50 => 50,
<= 100 => 100,
<= 500 => 500,
<= 1000 => 1000,
<= 10000 => 10000,
_ => 10001,
};
}

public void Dispose()
{
_meter.Dispose();
_lifeCycleMeter.Dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.Web" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.Server" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Blazor.Build.Tests" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.Authorization.Tests" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.Forms.Tests" />
Expand Down
4 changes: 3 additions & 1 deletion src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#nullable enable

Microsoft.AspNetCore.Components.Routing.Router.NotFoundPage.get -> System.Type!
Microsoft.AspNetCore.Components.Routing.Router.NotFoundPage.set -> void
Microsoft.AspNetCore.Components.Infrastructure.ComponentsMetricsServiceCollectionExtensions
Microsoft.AspNetCore.Components.NavigationManager.OnNotFound -> System.EventHandler<Microsoft.AspNetCore.Components.Routing.NotFoundEventArgs!>!
Microsoft.AspNetCore.Components.NavigationManager.NotFound() -> void
Microsoft.AspNetCore.Components.Routing.IHostEnvironmentNavigationManager.Initialize(string! baseUri, string! uri, System.Func<string!, System.Threading.Tasks.Task!>! onNavigateTo) -> void
Expand All @@ -14,5 +14,7 @@ Microsoft.AspNetCore.Components.SupplyParameterFromPersistentComponentStateAttri
Microsoft.AspNetCore.Components.SupplyParameterFromPersistentComponentStateAttribute.SupplyParameterFromPersistentComponentStateAttribute() -> void
Microsoft.Extensions.DependencyInjection.SupplyParameterFromPersistentComponentStateProviderServiceCollectionExtensions
static Microsoft.AspNetCore.Components.Infrastructure.RegisterPersistentComponentStateServiceCollectionExtensions.AddPersistentServiceRegistration<TService>(Microsoft.Extensions.DependencyInjection.IServiceCollection! services, Microsoft.AspNetCore.Components.IComponentRenderMode! componentRenderMode) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.AspNetCore.Components.Infrastructure.ComponentsMetricsServiceCollectionExtensions.AddComponentsMetrics(Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.AspNetCore.Components.Infrastructure.ComponentsMetricsServiceCollectionExtensions.AddComponentsTracing(Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.SupplyParameterFromPersistentComponentStateProviderServiceCollectionExtensions.AddSupplyValueFromPersistentComponentStateProvider(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.SignalRendererToFinishRendering() -> void
Loading
Loading