Skip to content

[Blazor] Remove InternalsVisibleTo from Components to Components.Server #62085

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
87 changes: 19 additions & 68 deletions src/Components/Components/src/ComponentsActivitySource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,79 +11,36 @@ namespace Microsoft.AspNetCore.Components;
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 Activity? _capturedActivity;

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

public static ActivityContext CaptureHttpContext()
/// <summary>
/// Initializes the ComponentsActivitySource with a captured activity for linking.
/// </summary>
/// <param name="capturedActivity">Activity to link with component activities.</param>
public void Initialize(Activity? capturedActivity)
{
var parentActivity = Activity.Current;
if (parentActivity is not null && parentActivity.OperationName == "Microsoft.AspNetCore.Hosting.HttpRequestIn" && parentActivity.Recorded)
{
return parentActivity.Context;
}
return default;
}

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();
}
_capturedActivity = capturedActivity;
}

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)
// Copy any circuit ID from captured activity if present
if (_capturedActivity != null && _capturedActivity.GetTagItem("aspnetcore.components.circuit.id") is string circuitId)
{
activity.SetTag("aspnetcore.components.circuit.id", _circuitId);
activity.SetTag("aspnetcore.components.circuit.id", circuitId);
}

Comment on lines +38 to +43
Copy link
Member

Choose a reason for hiding this comment

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

Copy all the tags or don't copy any. but don't look for the specific circuit id tag here

if (componentType != null)
{
activity.SetTag("aspnetcore.components.type", componentType);
Expand All @@ -92,13 +49,9 @@ public void FailCircuitActivity(Activity? activity, Exception ex)
{
activity.SetTag("aspnetcore.components.route", route);
}
if (_httpContext != default)
if (_capturedActivity != null)
{
activity.AddLink(new ActivityLink(_httpContext));
}
if (_circuitContext != default)
{
activity.AddLink(new ActivityLink(_circuitContext));
activity.AddLink(new ActivityLink(_capturedActivity.Context));
}
}

Expand All @@ -116,10 +69,12 @@ public void FailCircuitActivity(Activity? activity, Exception ex)
{
if (activity.IsAllDataRequested)
{
if (_circuitId != null)
// Copy any circuit ID from captured activity if present
if (_capturedActivity != null && _capturedActivity.GetTagItem("aspnetcore.components.circuit.id") is string circuitId)
{
activity.SetTag("aspnetcore.components.circuit.id", _circuitId);
activity.SetTag("aspnetcore.components.circuit.id", circuitId);
}

Comment on lines +72 to +77
Copy link
Member

Choose a reason for hiding this comment

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

FailCircuitActivity should receive the CircuitId as a parameter, not search for it inside the captured tag

if (componentType != null)
{
activity.SetTag("aspnetcore.components.type", componentType);
Expand All @@ -132,13 +87,9 @@ public void FailCircuitActivity(Activity? activity, Exception ex)
{
activity.SetTag("aspnetcore.components.attribute.name", attributeName);
}
if (_httpContext != default)
{
activity.AddLink(new ActivityLink(_httpContext));
}
if (_circuitContext != default)
if (_capturedActivity != null)
{
activity.AddLink(new ActivityLink(_circuitContext));
activity.AddLink(new ActivityLink(_capturedActivity.Context));
}
if (_routeContext != default)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@

<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
86 changes: 86 additions & 0 deletions src/Components/Server/src/Circuits/CircuitActivitySource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// 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.Server.Circuits;

/// <summary>
/// Activity source for circuit-related activities.
/// </summary>
public class CircuitActivitySource
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 be internal

{
internal const string Name = "Microsoft.AspNetCore.Components.Server";
internal const string OnCircuitName = $"{Name}.CircuitStart";

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

/// <summary>
/// Creates and starts a new activity for circuit initialization.
/// </summary>
/// <param name="circuitId">The ID of the circuit being initialized.</param>
/// <param name="httpContext">The HTTP context associated with the request that created the circuit.</param>
/// <returns>The created activity.</returns>
public Activity? StartCircuitActivity(string circuitId, ActivityContext httpContext)
{
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);
}
Comment on lines +31 to +34
Copy link
Member

Choose a reason for hiding this comment

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

circuitId is never null

if (httpContext != default)
{
activity.AddLink(new ActivityLink(httpContext));
}
}
activity.DisplayName = $"Circuit {circuitId ?? ""}";
activity.Start();
}
return activity;
}

/// <summary>
/// Stops a circuit activity that was previously started.
/// </summary>
/// <param name="activity">The activity to stop.</param>
public void StopCircuitActivity(Activity? activity)
{
if (activity != null && !activity.IsStopped)
{
activity.Stop();
}
}

/// <summary>
/// Marks a circuit activity as failed and stops it.
/// </summary>
/// <param name="activity">The activity to mark as failed.</param>
/// <param name="ex">The exception that caused the failure.</param>
public void FailCircuitActivity(Activity? activity, Exception ex)
{
if (activity != null && !activity.IsStopped)
{
activity.SetTag("error.type", ex.GetType().FullName);
activity.SetStatus(ActivityStatusCode.Error);
activity.Stop();
}
}
Comment on lines +63 to +71
Copy link
Member

Choose a reason for hiding this comment

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

Should receive the circuitId and add it as a tag


/// <summary>
/// Captures the current HTTP context activity.
/// </summary>
/// <returns>The captured HTTP context activity.</returns>
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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extension methods for adding <see cref="CircuitActivitySource"/> to the service collection.
/// </summary>
internal static class CircuitActivitySourceServiceCollectionExtensions
{
/// <summary>
/// Adds <see cref="CircuitActivitySource"/> to the service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCircuitActivitySource(this IServiceCollection services)
{
services.TryAddSingleton<CircuitActivitySource>();
return services;
}
}
16 changes: 13 additions & 3 deletions src/Components/Server/src/Circuits/CircuitFactory.cs
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.Diagnostics;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Infrastructure;
Expand Down Expand Up @@ -45,7 +46,8 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
string uri,
ClaimsPrincipal user,
IPersistentComponentStateStore store,
ResourceAssetCollection resourceCollection)
ResourceAssetCollection resourceCollection,
Activity? circuitActivity = null)
{
var scope = _scopeFactory.CreateAsyncScope();
var jsRuntime = (RemoteJSRuntime)scope.ServiceProvider.GetRequiredService<IJSRuntime>();
Expand All @@ -67,6 +69,11 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
navigationManager.Initialize(baseUri, uri);
}
var componentsActivitySource = scope.ServiceProvider.GetService<ComponentsActivitySource>();

// We don't need to explicitly initialize the ComponentsActivitySource here anymore
// since the RemoteRenderer will capture Activity.Current and initialize it

var circuitActivitySource = scope.ServiceProvider.GetService<CircuitActivitySource>();

if (components.Count > 0)
{
Expand Down Expand Up @@ -99,8 +106,10 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
.OrderBy(h => h.Order)
.ToArray();

var circuitId = _circuitIdFactory.CreateCircuitId();

var circuitHost = new CircuitHost(
_circuitIdFactory.CreateCircuitId(),
circuitId,
scope,
_options,
client,
Expand All @@ -110,7 +119,8 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
navigationManager,
circuitHandlers,
_circuitMetrics,
componentsActivitySource,
circuitActivitySource,
circuitActivity,
_loggerFactory.CreateLogger<CircuitHost>());
Log.CreatedCircuit(_logger, circuitHost);

Expand Down
17 changes: 10 additions & 7 deletions src/Components/Server/src/Circuits/CircuitHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ internal partial class CircuitHost : IAsyncDisposable
private readonly RemoteNavigationManager _navigationManager;
private readonly ILogger _logger;
private readonly CircuitMetrics? _circuitMetrics;
private readonly ComponentsActivitySource? _componentsActivitySource;
private readonly CircuitActivitySource? _circuitActivitySource;
private readonly Activity? _circuitActivity;
private Func<Func<Task>, Task> _dispatchInboundActivity;
private CircuitHandler[] _circuitHandlers;
private bool _initialized;
Expand All @@ -52,7 +53,8 @@ public CircuitHost(
RemoteNavigationManager navigationManager,
CircuitHandler[] circuitHandlers,
CircuitMetrics? circuitMetrics,
ComponentsActivitySource? componentsActivitySource,
CircuitActivitySource? circuitActivitySource,
Activity? circuitActivity,
ILogger logger)
{
CircuitId = circuitId;
Expand All @@ -71,7 +73,8 @@ public CircuitHost(
_navigationManager = navigationManager ?? throw new ArgumentNullException(nameof(navigationManager));
_circuitHandlers = circuitHandlers ?? throw new ArgumentNullException(nameof(circuitHandlers));
_circuitMetrics = circuitMetrics;
_componentsActivitySource = componentsActivitySource;
_circuitActivitySource = circuitActivitySource;
_circuitActivity = circuitActivity;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));

Services = scope.ServiceProvider;
Expand Down Expand Up @@ -124,7 +127,6 @@ public Task InitializeAsync(ProtectedPrerenderComponentApplicationStore store, A
{
_initialized = true; // We're ready to accept incoming JSInterop calls from here on

activity = _componentsActivitySource?.StartCircuitActivity(CircuitId.Id, httpContext);
_startTime = (_circuitMetrics != null && _circuitMetrics.IsDurationEnabled()) ? Stopwatch.GetTimestamp() : 0;

// We only run the handlers in case we are in a Blazor Server scenario, which renders
Expand Down Expand Up @@ -169,12 +171,10 @@ public Task InitializeAsync(ProtectedPrerenderComponentApplicationStore store, A
_isFirstUpdate = Descriptors.Count == 0;

Log.InitializationSucceeded(_logger);

activity?.Stop();
}
catch (Exception ex)
{
_componentsActivitySource?.FailCircuitActivity(activity, ex);
_circuitActivitySource?.FailCircuitActivity(_circuitActivity, ex);

// Report errors asynchronously. InitializeAsync is designed not to throw.
Log.InitializationFailed(_logger, ex);
Expand Down Expand Up @@ -337,6 +337,9 @@ private async Task OnCircuitDownAsync(CancellationToken cancellationToken)
{
Log.CircuitClosed(_logger, CircuitId);
_circuitMetrics?.OnCircuitDown(_startTime, Stopwatch.GetTimestamp());

// Stop the circuit activity when the circuit is closed
_circuitActivitySource?.StopCircuitActivity(_circuitActivity);

List<Exception> exceptions = null;

Expand Down
4 changes: 3 additions & 1 deletion src/Components/Server/src/Circuits/ICircuitFactory.cs
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.Diagnostics;
using System.Security.Claims;

namespace Microsoft.AspNetCore.Components.Server.Circuits;
Expand All @@ -14,5 +15,6 @@ ValueTask<CircuitHost> CreateCircuitHostAsync(
string uri,
ClaimsPrincipal user,
IPersistentComponentStateStore store,
ResourceAssetCollection resourceCollection);
ResourceAssetCollection resourceCollection,
Activity? circuitActivity = null);
}
Loading
Loading