Skip to content
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

[Instrumentation.AspNetCore] Listen to SignalR server activities #2429

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions build/Common.props
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
Refer to https://docs.microsoft.com/en-us/nuget/concepts/package-versioning for semver syntax.
-->
<MinVerPkgVer>[6.0.0,7.0)</MinVerPkgVer>
<MicrosoftAspNetCoreSignalRClientPkgVer>[9.0.0,)</MicrosoftAspNetCoreSignalRClientPkgVer>
<MicrosoftExtensionsHostingAbstractionsPkgVer>[2.1.0,5.0)</MicrosoftExtensionsHostingAbstractionsPkgVer>
<MicrosoftExtensionsConfigurationPkgVer>[9.0.0,)</MicrosoftExtensionsConfigurationPkgVer>
<MicrosoftExtensionsOptionsPkgVer>[9.0.0,)</MicrosoftExtensionsOptionsPkgVer>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreTraceInstrumentationOptions.DisableAspNetCoreSignalRSupport.get -> bool
OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreTraceInstrumentationOptions.DisableAspNetCoreSignalRSupport.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static TracerProviderBuilder AddAspNetCoreInstrumentation(
{
deferredTracerProviderBuilder.Configure((sp, builder) =>
{
AddAspNetCoreInstrumentationSources(builder, sp);
AddAspNetCoreInstrumentationSources(builder, name, sp);
});
}

Expand All @@ -84,9 +84,12 @@ public static TracerProviderBuilder AddAspNetCoreInstrumentation(
// Note: This is used by unit tests.
internal static TracerProviderBuilder AddAspNetCoreInstrumentation(
this TracerProviderBuilder builder,
HttpInListener listener)
HttpInListener listener,
string? optionsName = null)
{
builder.AddAspNetCoreInstrumentationSources();
optionsName ??= Options.DefaultName;

builder.AddAspNetCoreInstrumentationSources(optionsName);

#pragma warning disable CA2000
return builder.AddInstrumentation(
Expand All @@ -96,6 +99,7 @@ internal static TracerProviderBuilder AddAspNetCoreInstrumentation(

private static void AddAspNetCoreInstrumentationSources(
this TracerProviderBuilder builder,
string optionsName,
IServiceProvider? serviceProvider = null)
{
// For .NET7.0 onwards activity will be created using activitySource.
Expand All @@ -121,5 +125,16 @@ private static void AddAspNetCoreInstrumentationSources(
builder.AddSource(HttpInListener.ActivitySourceName);
builder.AddLegacySource(HttpInListener.ActivityOperationName); // for the activities created by AspNetCore
}

// SignalR activities first added in .NET 9.0
if (Environment.Version.Major >= 9)
{
var options = serviceProvider?.GetRequiredService<IOptionsMonitor<AspNetCoreTraceInstrumentationOptions>>().Get(optionsName);
if (options is null || !options.DisableAspNetCoreSignalRSupport)
{
// https://github.com/dotnet/aspnetcore/blob/6ae3ea387b20f6497b82897d613e9b8a6e31d69c/src/SignalR/server/Core/src/Internal/SignalRServerActivitySource.cs#L13C35-L13C70
builder.AddSource("Microsoft.AspNetCore.SignalR.Server");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ internal AspNetCoreTraceInstrumentationOptions(IConfiguration configuration)
/// </remarks>
public bool RecordException { get; set; }

/// <summary>
/// Gets or sets a value indicating whether SignalR activities are recorded.
/// </summary>
public bool DisableAspNetCoreSignalRSupport { get; set; }
Copy link
Contributor

@noahfalk noahfalk Jan 15, 2025

Choose a reason for hiding this comment

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

Naming suggestion:

Suggested change
public bool DisableAspNetCoreSignalRSupport { get; set; }
public bool EnableAspNetCoreSignalRSupport { get; set; }

A couple thoughts in there:

  1. Naming the property Enable rather than Disable avoids reasoning with double-negatives when the value is false.
  2. It matches the pattern for EnableGrpcAspNetCoreSupport below.

Together with the name change you'd presumably also swap the default value so the behavior remains the same.


/// <summary>
/// Gets or sets a value indicating whether RPC attributes are added to an Activity when using Grpc.AspNetCore.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -1114,6 +1115,104 @@ public async Task ValidateUrlQueryRedaction(string urlQuery, string expectedUrlQ
Assert.Equal(expectedUrlQuery, activity.GetTagValue(SemanticConventions.AttributeUrlQuery));
}

#if NET9_0_OR_GREATER
[Fact]
public async Task SignalRActivitesAreListenedTo()
{
var exportedItems = new List<Activity>();
void ConfigureTestServices(IServiceCollection services)
{
this.tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAspNetCoreInstrumentation()
.AddInMemoryExporter(exportedItems)
.Build();
}

// Arrange
using (var server = this.factory
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(ConfigureTestServices);
builder.ConfigureLogging(loggingBuilder => loggingBuilder.ClearProviders());
}))
{
await using var client = new HubConnectionBuilder()
.WithUrl(server.Server.BaseAddress + "testHub", o =>
{
o.HttpMessageHandlerFactory = _ => server.Server.CreateHandler();
o.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.LongPolling;
}).Build();
await client.StartAsync();

await client.SendAsync("Send", "text");

await client.StopAsync();
}

WaitForActivityExport(exportedItems, 11);

var hubActivity = exportedItems
.Where(a => a.DisplayName.StartsWith("TestApp.AspNetCore.TestHub", StringComparison.InvariantCulture));

Assert.Equal(3, hubActivity.Count());
Assert.Collection(
hubActivity,
one =>
{
Assert.Equal("TestApp.AspNetCore.TestHub/OnConnectedAsync", one.DisplayName);
},
two =>
{
Assert.Equal("TestApp.AspNetCore.TestHub/Send", two.DisplayName);
},
three =>
{
Assert.Equal("TestApp.AspNetCore.TestHub/OnDisconnectedAsync", three.DisplayName);
});
}

[Fact]
public async Task SignalRActivitesCanBeDisabled()
{
var exportedItems = new List<Activity>();
void ConfigureTestServices(IServiceCollection services)
{
this.tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAspNetCoreInstrumentation(o => o.DisableAspNetCoreSignalRSupport = true)
.AddInMemoryExporter(exportedItems)
.Build();
}

// Arrange
using (var server = this.factory
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(ConfigureTestServices);
builder.ConfigureLogging(loggingBuilder => loggingBuilder.ClearProviders());
}))
{
await using var client = new HubConnectionBuilder()
.WithUrl(server.Server.BaseAddress + "testHub", o =>
{
o.HttpMessageHandlerFactory = _ => server.Server.CreateHandler();
o.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.LongPolling;
}).Build();
await client.StartAsync();

await client.SendAsync("Send", "text");

await client.StopAsync();
}

WaitForActivityExport(exportedItems, 8);

var hubActivity = exportedItems
.Where(a => a.DisplayName.StartsWith("TestApp.AspNetCore.TestHub", StringComparison.InvariantCulture));

Assert.Empty(hubActivity);
}
#endif

public void Dispose()
{
this.tracerProvider?.Dispose();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ItemGroup>
<PackageReference Include="OpenTelemetry.Exporter.InMemory" Version="$(OpenTelemetryCoreLatestVersion)" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="$(OpenTelemetryCoreLatestVersion)" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="$(MicrosoftAspNetCoreSignalRClientPkgVer)" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 4 additions & 0 deletions test/TestApp.AspNetCore/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public static void Main(string[] args)

builder.Services.AddMvc();

builder.Services.AddSignalR();

builder.Services.AddSingleton<HttpClient>();

builder.Services.AddSingleton(
Expand All @@ -43,6 +45,8 @@ public static void Main(string[] args)

app.MapControllers();

app.MapHub<TestHub>("/testHub");

app.UseMiddleware<CallbackMiddleware>();

app.UseMiddleware<ActivityMiddleware>();
Expand Down
15 changes: 15 additions & 0 deletions test/TestApp.AspNetCore/TestHub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

using Microsoft.AspNetCore.SignalR;

namespace TestApp.AspNetCore;

public class TestHub : Hub
{
public override Task OnConnectedAsync() => base.OnConnectedAsync();

public void Send(string message)
{
}
}