Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6ebfa78
[SignalR] Reduce hub invocation activity overhead
martincostello Sep 27, 2026
c06ddd7
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Sep 29, 2026
17c9c12
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 6, 2026
4ff0f82
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 7, 2026
61a7e69
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 15, 2026
8de8061
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 15, 2026
e9be2b4
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 23, 2026
1be63ce
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 23, 2026
6cc6fde
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 27, 2026
34aaca5
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 27, 2026
58e2533
Address feedback
martincostello Oct 30, 2026
7ab162b
Merge remote-tracking branch 'origin/main' into signalr-reducea-activ…
martincostello Oct 30, 2026
27749c8
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Oct 30, 2026
54d866c
Address feedback
martincostello Oct 31, 2026
59bc2ee
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Nov 2, 2026
b167468
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Nov 2, 2026
60820f1
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Nov 2, 2026
1c3813a
Merge branch 'main' into signalr-reducea-activity-overhead
martincostello Nov 2, 2026
5c3e549
Make HubMethodDescriptor.Name required
martincostello Nov 2, 2026
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
40 changes: 22 additions & 18 deletions src/Shared/ConnectionEndpointTags.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ internal static class ConnectionEndpointTags
private static object? s_boxedPort;

/// <summary>
/// Adds connection endpoint tags to a TagList using <see cref="IConnectionEndPointFeature"/>.
/// Adds connection endpoint tags to a collection of tags, such as a <see cref="TagList"/>, using <see cref="IConnectionEndPointFeature"/>.
/// </summary>
/// <param name="tags">The <see cref="TagList"/> to add tags to.</param>
/// <param name="tags">The tags to add to.</param>
/// <param name="features">The feature collection to get endpoint information from.</param>
public static void AddConnectionEndpointTags(ref TagList tags, IFeatureCollection features)
public static void AddConnectionEndpointTags<TTags>(ref TTags tags, IFeatureCollection features)
where TTags : ICollection<KeyValuePair<string, object?>>
Comment thread
martincostello marked this conversation as resolved.
Resolved
{
var endpointFeature = features.Get<IConnectionEndPointFeature>();
if (endpointFeature is null)
Expand All @@ -39,12 +40,13 @@ public static void AddConnectionEndpointTags(ref TagList tags, IFeatureCollectio
}

/// <summary>
/// Adds connection endpoint tags to a TagList using <see cref="IConnectionEndPointFeature"/>,
/// Adds connection endpoint tags to a collection of tags, such as a <see cref="TagList"/>, using <see cref="IConnectionEndPointFeature"/>,
/// with a fallback to the <see cref="BaseConnectionContext"/> endpoint properties.
/// </summary>
/// <param name="tags">The <see cref="TagList"/> to add tags to.</param>
/// <param name="tags">The tags to add to.</param>
/// <param name="connectionContext">The connection context to get endpoint information from.</param>
public static void AddConnectionEndpointTags(ref TagList tags, BaseConnectionContext connectionContext)
public static void AddConnectionEndpointTags<TTags>(ref TTags tags, BaseConnectionContext connectionContext)
where TTags : ICollection<KeyValuePair<string, object?>>
{
// Try to get the local endpoint from the feature first, then fall back to the direct property.
var localEndpoint = connectionContext.Features.Get<IConnectionEndPointFeature>()?.LocalEndPoint
Expand All @@ -57,39 +59,41 @@ public static void AddConnectionEndpointTags(ref TagList tags, BaseConnectionCon
AddEndpointTags(ref tags, localEndpoint, networkTransport);
}

private static void AddEndpointTags(ref TagList tags, EndPoint? localEndpoint, string networkTransport)
// Generic so value types like TagList are updated in place without boxing.
private static void AddEndpointTags<TTags>(ref TTags tags, EndPoint? localEndpoint, string networkTransport)
where TTags : ICollection<KeyValuePair<string, object?>>
{
if (localEndpoint is IPEndPoint localIPEndPoint)
{
tags.Add("server.address", localIPEndPoint.Address.ToString());
tags.Add("server.port", GetBoxedPort(localIPEndPoint.Port));
tags.Add(new("server.address", localIPEndPoint.Address.ToString()));
tags.Add(new("server.port", GetBoxedPort(localIPEndPoint.Port)));

switch (localIPEndPoint.Address.AddressFamily)
{
case AddressFamily.InterNetwork:
tags.Add("network.type", "ipv4");
tags.Add(new("network.type", "ipv4"));
break;
case AddressFamily.InterNetworkV6:
tags.Add("network.type", "ipv6");
tags.Add(new("network.type", "ipv6"));
break;
}

tags.Add("network.transport", networkTransport);
tags.Add(new("network.transport", networkTransport));
}
else if (localEndpoint is UnixDomainSocketEndPoint udsEndPoint)
{
tags.Add("server.address", udsEndPoint.ToString());
tags.Add("network.transport", "unix");
tags.Add(new("server.address", udsEndPoint.ToString()));
tags.Add(new("network.transport", "unix"));
}
else if (localEndpoint is NamedPipeEndPoint namedPipeEndPoint)
{
tags.Add("server.address", namedPipeEndPoint.ToString());
tags.Add("network.transport", "pipe");
tags.Add(new("server.address", namedPipeEndPoint.ToString()));
tags.Add(new("network.transport", "pipe"));
}
else if (localEndpoint != null)
{
tags.Add("server.address", localEndpoint.ToString());
tags.Add("network.transport", localEndpoint.AddressFamily.ToString());
tags.Add(new("server.address", localEndpoint.ToString()));
tags.Add(new("network.transport", localEndpoint.AddressFamily.ToString()));
}
}

Expand Down
17 changes: 16 additions & 1 deletion src/SignalR/server/Core/src/HubConnectionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,22 @@ public partial class HubConnectionContext
// Tracks groups that the connection has been added to
internal HashSet<string> GroupNames { get; } = new HashSet<string>();

internal Activity? OriginalActivity { get; set; }
private ActivityLink[]? _originalActivityLinks;

internal Activity? OriginalActivity
{
get;
set
{
field = value;
_originalActivityLinks = null;
}
}

// Links to OriginalActivity for hub invocation activities. The links are copied when an
// activity is created, so the same array can be used by every invocation on the connection.
internal ActivityLink[]? OriginalActivityLinks =>
OriginalActivity is { } originalActivity ? _originalActivityLinks ??= [new ActivityLink(originalActivity.Context)] : null;

/// <summary>
/// Initializes a new instance of the <see cref="HubConnectionContext"/> class.
Expand Down
105 changes: 62 additions & 43 deletions src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ internal sealed partial class DefaultHubDispatcher<[DynamicallyAccessedMembers(H
{
private static readonly string _fullHubName = typeof(THub).FullName ?? typeof(THub).Name;

// The most tags added to an activity: 3 hub tags (rpc.method, rpc.system, rpc.service) and
// 4 connection endpoint tags (server.address, server.port, network.type, network.transport).
private const int MaxActivityTags = 7;
Comment thread
BrennanConroy marked this conversation as resolved.
Resolved

[ThreadStatic]
private static List<KeyValuePair<string, object?>>? t_activityTags;

private readonly Dictionary<string, HubMethodDescriptor> _methods = new(StringComparer.OrdinalIgnoreCase);
private readonly Utf8HashLookup _cachedMethodNames = new();
private readonly IServiceScopeFactory _serviceScopeFactory;
Expand Down Expand Up @@ -93,7 +100,7 @@ public override async Task OnConnectedAsync(HubConnectionContext connection)
// OnConnectedAsync won't work with client results (ISingleClientProxy.InvokeAsync)
InitializeHub(hub, connection, hubCallerContext, invokeAllowed: false);

activity = StartActivity(SignalRServerActivitySource.OnConnected, ActivityKind.Internal, linkedActivity: null, scope.ServiceProvider, nameof(hub.OnConnectedAsync), headers: null, _logger, connection);
activity = StartActivity(SignalRServerActivitySource.OnConnected, ActivityKind.Internal, links: null, scope.ServiceProvider, nameof(hub.OnConnectedAsync), headers: null, _logger, connection);

if (_onConnectedMiddleware != null)
{
Expand Down Expand Up @@ -129,7 +136,7 @@ public override async Task OnDisconnectedAsync(HubConnectionContext connection,
var hubCallerContext = connection.HubCallerContext;
InitializeHub(hub, connection, hubCallerContext);

activity = StartActivity(SignalRServerActivitySource.OnDisconnected, ActivityKind.Internal, linkedActivity: null, scope.ServiceProvider, nameof(hub.OnDisconnectedAsync), headers: null, _logger, connection);
activity = StartActivity(SignalRServerActivitySource.OnDisconnected, ActivityKind.Internal, links: null, scope.ServiceProvider, nameof(hub.OnDisconnectedAsync), headers: null, _logger, connection);

if (_onDisconnectedMiddleware != null)
{
Expand Down Expand Up @@ -176,7 +183,7 @@ private async Task<bool> InvokeOnAuthenticationRefreshedAsync(HubConnectionConte
var hubCallerContext = connection.HubCallerContext;
InitializeHub(hub, connection, hubCallerContext, invokeAllowed: false);

activity = StartActivity(SignalRServerActivitySource.OnAuthenticationRefreshed, ActivityKind.Internal, linkedActivity: null, scope.ServiceProvider, nameof(hub.OnAuthenticationRefreshedAsync), headers: null, _logger, connection);
activity = StartActivity(SignalRServerActivitySource.OnAuthenticationRefreshed, ActivityKind.Internal, links: null, scope.ServiceProvider, nameof(hub.OnAuthenticationRefreshedAsync), headers: null, _logger, connection);

await hub.OnAuthenticationRefreshedAsync();
}
Expand Down Expand Up @@ -432,6 +439,7 @@ await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
// Invoke or Send
static async Task ExecuteInvocation(DefaultHubDispatcher<THub> dispatcher,
ObjectMethodExecutor methodExecutor,
HubMethodDescriptor descriptor,
THub hub,
object?[] arguments,
AsyncServiceScope scope,
Expand All @@ -455,7 +463,7 @@ static async Task ExecuteInvocation(DefaultHubDispatcher<THub> dispatcher,

// Use hubMethodInvocationMessage.Target instead of methodExecutor.MethodInfo.Name
// We want to take HubMethodNameAttribute into account which will be the same as what the invocation target is
var activity = StartActivity(SignalRServerActivitySource.InvocationIn, ActivityKind.Server, connection.OriginalActivity, scope.ServiceProvider, hubMethodInvocationMessage.Target, hubMethodInvocationMessage.Headers, logger, connection);
var activity = StartActivity(SignalRServerActivitySource.InvocationIn, ActivityKind.Server, connection.OriginalActivityLinks, scope.ServiceProvider, hubMethodInvocationMessage.Target, hubMethodInvocationMessage.Headers, logger, connection, descriptor);

// Register the CancellationTokenSource if present so CancelInvocationMessage can cancel it
var ctsRegistered = false;
Expand Down Expand Up @@ -523,7 +531,7 @@ await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
}
}

invocation = ExecuteInvocation(this, methodExecutor, hub, arguments, scope, hubActivator, connection, hubCallerContext, hubMethodInvocationMessage, isStreamCall, cts, streamOwner);
invocation = ExecuteInvocation(this, methodExecutor, descriptor, hub, arguments, scope, hubActivator, connection, hubCallerContext, hubMethodInvocationMessage, isStreamCall, cts, streamOwner);
}

if (isStreamCall || isStreamResponse)
Expand Down Expand Up @@ -600,7 +608,7 @@ private async Task StreamAsync(string invocationId, HubConnectionContext connect
Activity.Current = null;
}

var activity = StartActivity(SignalRServerActivitySource.InvocationIn, ActivityKind.Server, connection.OriginalActivity, scope.ServiceProvider, hubMethodInvocationMessage.Target, hubMethodInvocationMessage.Headers, _logger, connection);
var activity = StartActivity(SignalRServerActivitySource.InvocationIn, ActivityKind.Server, connection.OriginalActivityLinks, scope.ServiceProvider, hubMethodInvocationMessage.Target, hubMethodInvocationMessage.Headers, _logger, connection, descriptor);

var ctsRegistered = false;
try
Expand Down Expand Up @@ -930,7 +938,7 @@ private void DiscoverHubMethods(bool disableImplicitFromServiceParameters)

var authorizationMetadata = methodInfo.GetCustomAttributes(inherit: true);
EnsureNoAuthenticationSchemeSpecified(authorizationMetadata);
_methods[methodName] = new HubMethodDescriptor(executor, serviceProviderIsService, authorizationMetadata);
_methods[methodName] = new HubMethodDescriptor(executor, serviceProviderIsService, authorizationMetadata) { Name = methodName };
_cachedMethodNames.Add(methodName);

Log.HubMethodBound(_logger, hubName, methodName);
Expand Down Expand Up @@ -963,7 +971,7 @@ public override IReadOnlyList<Type> GetParameterTypes(string methodName)

// Starts an Activity for a Hub method invocation and sets up all the tags and other state.
// Make sure to call Activity.Stop() once the Hub method completes, and consider calling SetActivityError on exception.
private static Activity? StartActivity(string operationName, ActivityKind kind, Activity? linkedActivity, IServiceProvider serviceProvider, string methodName, IDictionary<string, string>? headers, ILogger logger, HubConnectionContext? connection = null)
private static Activity? StartActivity(string operationName, ActivityKind kind, IEnumerable<ActivityLink>? links, IServiceProvider serviceProvider, string methodName, IDictionary<string, string>? headers, ILogger logger, HubConnectionContext? connection = null, HubMethodDescriptor? descriptor = null)
{
var activitySource = serviceProvider.GetService<SignalRServerActivitySource>()?.ActivitySource;
if (activitySource is null)
Expand All @@ -977,51 +985,62 @@ public override IReadOnlyList<Type> GetParameterTypes(string methodName)
return null;
}

var tagList = new TagList
{
{ "rpc.method", methodName },
{ "rpc.system", "signalr" },
{ "rpc.service", _fullHubName }
};

// Add connection endpoint tags if connection is available
if (connection is not null)
{
ConnectionEndpointTags.AddConnectionEndpointTags(ref tagList, connection.Features);
}

IEnumerable<KeyValuePair<string, object?>> tags = tagList;
IEnumerable<ActivityLink>? links = (linkedActivity is not null) ? [new ActivityLink(linkedActivity.Context)] : null;
// Use a reusable list for the tags rather than a TagList, which would be boxed, along with its enumerator,
// for every invocation. This is safe because the tags are copied into the activity when it's created. The
// list is taken from the thread-static field while it's in use so a reentrant call can't modify it.
// Don't build a TagList and copy it into the list either. There's a JIT performance issue that can cause
// the copy operation to be up to 10x slower with AVX, see https://github.com/dotnet/runtime/issues/133784.
var tags = t_activityTags ?? new List<KeyValuePair<string, object?>>(MaxActivityTags);
t_activityTags = null;

Activity? activity;
if (headers != null)
try
{
var propagator = serviceProvider.GetService<DistributedContextPropagator>() ?? DistributedContextPropagator.Current;
// Update MaxActivityTags when adding tags here or in ConnectionEndpointTags.
tags.Add(new("rpc.method", methodName));
tags.Add(new("rpc.system", "signalr"));
tags.Add(new("rpc.service", _fullHubName));

activity = ActivityCreator.CreateFromRemote(
activitySource,
propagator,
headers,
static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>
{
fieldValues = default;
var headers = (IDictionary<string, string>)carrier!;
headers.TryGetValue(fieldName, out fieldValue);
},
operationName,
kind,
tags,
links,
loggingEnabled);
// Add connection endpoint tags if connection is available
if (connection is not null)
{
ConnectionEndpointTags.AddConnectionEndpointTags(ref tags, connection.Features);
}

if (headers != null)
{
var propagator = serviceProvider.GetService<DistributedContextPropagator>() ?? DistributedContextPropagator.Current;

activity = ActivityCreator.CreateFromRemote(
activitySource,
propagator,
headers,
static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>
{
fieldValues = default;
var headers = (IDictionary<string, string>)carrier!;
headers.TryGetValue(fieldName, out fieldValue);
},
operationName,
kind,
tags,
links,
loggingEnabled);
}
else
{
activity = activitySource.CreateActivity(operationName, kind, parentId: null, tags: tags, links: links);
}
}
else
finally
{
activity = activitySource.CreateActivity(operationName, kind, parentId: null, tags: tags, links: links);
tags.Clear();
t_activityTags = tags;
}

if (activity is not null)
{
activity.DisplayName = $"{_fullHubName}/{methodName}";
activity.DisplayName = descriptor?.GetActivityDisplayName(_fullHubName) ?? $"{_fullHubName}/{methodName}";
activity.Start();
}

Expand Down
10 changes: 10 additions & 0 deletions src/SignalR/server/Core/src/Internal/HubMethodDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ internal sealed class HubMethodDescriptor
private ConditionalWeakTable<IAuthorizationPolicyProvider, AuthorizationPolicy>? _authorizationPolicies;
// bitset to store which parameters come from DI up to 64 arguments
private ulong _isServiceArgument;
private string? _activityDisplayName;

public HubMethodDescriptor(ObjectMethodExecutor methodExecutor, IServiceProviderIsService? serviceProviderIsService, IEnumerable<object> authorizationMetadata)
{
Expand Down Expand Up @@ -161,6 +162,8 @@ private bool MarkServiceParameter(int index)

public List<(int, object?)>? KeyedServiceKeys { get; private set; }

public required string Name { get; init; }

public ObjectMethodExecutor MethodExecutor { get; }

public IReadOnlyList<Type> ParameterTypes { get; }
Expand Down Expand Up @@ -244,6 +247,13 @@ public object GetService(IServiceProvider serviceProvider, int index, Type param
return _makeCancelableEnumerator.Invoke(stream, cancellationToken);
}

public string GetActivityDisplayName(string hubName)
{
// The hub name and the name this method is registered with never change, so the display
// name is only built once. A race on the first use only results in an extra allocation.
return _activityDisplayName ??= $"{hubName}/{Name}";
}

[UnconditionalSuppressMessage("Trimming", "IL2060:MakeGenericMethod",
Justification = "The adapter methods passed into here (MakeAsyncEnumerator and MakeAsyncEnumeratorFromChannel) don't have trimming annotations.")]
[RequiresDynamicCode("Calls MakeGenericMethod with types that may be ValueTypes")]
Expand Down
Loading
Loading