Skip to content

Commit 040233c

Browse files
authored
Add ASP.NET Core instrumentation to OpenTelemetry tracing (#3823)
## Why make this change? - Closes #3559 - When OpenTelemetry is enabled, DAB exports no span for inbound REST, GraphQL or MCP requests. The `TracerProvider` only registers `HttpClientInstrumentation`, so the only exported spans are outbound calls DAB makes itself (schema download, health self-checks). An incoming `traceparent` is also not continued, which breaks distributed traces going through DAB. ## What is this change? - Registers `.AddAspNetCoreInstrumentation()` in the `WithTracing` block of `Startup.cs`. - The `OpenTelemetry.Instrumentation.AspNetCore` package (1.12.0) is already referenced by `Azure.DataApiBuilder.Service.csproj` and `Directory.Packages.props`, but it was never used. **No new dependency and no version change.** - ASP.NET Core already creates an activity for every request on the `Microsoft.AspNetCore` activity source; without this call the OpenTelemetry SDK does not subscribe to it, so those activities are never sampled or exported. - Existing DAB spans (`DABActivitySource`, e.g. `GET {entity}` / `QUERY {entity}` in `RestController`) and HotChocolate spans now become children of the server span, and the incoming W3C `traceparent` is honored. - SQL client spans (also mentioned in the issue) are intentionally left out of this PR: `OpenTelemetry.Instrumentation.SqlClient` is not available on the `data_api_builder_build_packages` feed, so adding it would fail restore (`NU1301`) until a maintainer adds it to the feed. Version `1.15.2` would be the compatible one (depends on `OpenTelemetry.Api.ProviderBuilderExtensions >= 1.15.3`, matching the current `OpenTelemetry.Exporter.OpenTelemetryProtocol` 1.15.3). Happy to follow up in a separate PR. ## How was this tested? - [x] Integration Tests - Added `OpenTelemetryTests.TestOpenTelemetryRecordsInboundHttpRequestSpan`. It registers an `ActivityListener` on the `Microsoft.AspNetCore` source that never samples by itself, sends a request to the `TestServer`, and asserts that the server activity for that request path is `Recorded`. The activity can only be recorded if the OpenTelemetry `TracerProvider` subscribes to ASP.NET Core, so the test fails without the fix. - [ ] Unit Tests - Manual: the same one-line change applied on top of `v2.0.12`, running against SQL Server with OTLP gRPC export to Grafana Alloy → Tempo. Before: the OTEL SDK self-diagnostics log shows `Instrumentations added = "HttpClientInstrumentation"` and no request spans. After: one `Server` span per REST request is visible in Tempo. ## Sample Request(s) With `runtime.telemetry.open-telemetry.enabled: true`: ``` GET http://localhost:5000/api/Book ``` now exports a `Server` span (`http.request.method=GET`, `url.path=/api/Book`, `http.response.status_code=200`), with the existing DAB spans for the request (`GET Book`, `QUERY Book`) nested under it. --------- Co-authored-by: clempiq <104780066+clementpiquin@users.noreply.github.com>
1 parent 594e942 commit 040233c

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

‎src/Service.Tests/Configuration/Telemetry/OpenTelemetryTests.cs‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
// Licensed under the MIT License.
33

44
using System;
5+
using System.Diagnostics;
56
using System.IO;
7+
using System.Net.Http;
8+
using System.Threading.Tasks;
69
using Azure.DataApiBuilder.Config.ObjectModel;
710
using Microsoft.AspNetCore.TestHost;
811
using Microsoft.Extensions.DependencyInjection;
@@ -24,6 +27,7 @@ public class OpenTelemetryTests
2427

2528
private const string CONFIG_WITH_TELEMETRY = "dab-open-telemetry-test-config.json";
2629
private const string CONFIG_WITHOUT_TELEMETRY = "dab-no-open-telemetry-test-config.json";
30+
private const string ASPNETCORE_ACTIVITY_SOURCE_NAME = "Microsoft.AspNetCore";
2731
private static RuntimeConfig _configuration;
2832

2933
/// <summary>
@@ -88,6 +92,61 @@ public void TestOpenTelemetryServicesEnabled()
8892
Assert.IsNotNull(meterProvider, "MeterProvider should be registered.");
8993
}
9094

95+
/// <summary>
96+
/// Tests that an inbound HTTP request produces a recorded server span when Open Telemetry is enabled,
97+
/// and that this span continues the trace context received in the W3C traceparent header.
98+
/// The listener below never samples by itself, so the span can only be recorded because
99+
/// the OpenTelemetry TracerProvider subscribes to the ASP.NET Core activity source.
100+
/// </summary>
101+
[TestMethod]
102+
public async Task TestOpenTelemetryRecordsInboundHttpRequestSpan()
103+
{
104+
// Arrange
105+
SetUpTelemetryInConfig(CONFIG_WITH_TELEMETRY, true, "http://localhost:4317", "key=key", OtlpExportProtocol.Grpc);
106+
107+
ActivityTraceId incomingTraceId = ActivityTraceId.CreateRandom();
108+
ActivitySpanId incomingParentSpanId = ActivitySpanId.CreateRandom();
109+
TaskCompletionSource<Activity> recordedServerActivity = new(TaskCreationOptions.RunContinuationsAsynchronously);
110+
using ActivityListener listener = new()
111+
{
112+
ShouldListenTo = source => source.Name == ASPNETCORE_ACTIVITY_SOURCE_NAME,
113+
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.None,
114+
ActivityStopped = activity =>
115+
{
116+
if (activity.TraceId == incomingTraceId)
117+
{
118+
recordedServerActivity.TrySetResult(activity);
119+
}
120+
}
121+
};
122+
ActivitySource.AddActivityListener(listener);
123+
124+
string[] args = new[]
125+
{
126+
$"--ConfigFileName={CONFIG_WITH_TELEMETRY}"
127+
};
128+
using TestServer server = new(Program.CreateWebHostBuilder(args));
129+
Assert.IsNotNull(server.Services.GetService<TracerProvider>(), "TracerProvider should be registered.");
130+
using HttpClient client = server.CreateClient();
131+
132+
using HttpRequestMessage request = new(HttpMethod.Get, "/");
133+
request.Headers.Add("traceparent", $"00-{incomingTraceId.ToHexString()}-{incomingParentSpanId.ToHexString()}-01");
134+
135+
// Act
136+
using HttpResponseMessage response = await client.SendAsync(request);
137+
138+
// Assert
139+
// The server activity is stopped once the request pipeline completes, which can happen after the response is returned.
140+
Task completedTask = await Task.WhenAny(recordedServerActivity.Task, Task.Delay(TimeSpan.FromSeconds(10)));
141+
Assert.AreSame(recordedServerActivity.Task, completedTask, "An inbound HTTP request should produce a server span.");
142+
143+
Activity serverActivity = await recordedServerActivity.Task;
144+
Assert.IsTrue(serverActivity.Recorded, "The server span should be recorded.");
145+
Assert.AreEqual(ActivityKind.Server, serverActivity.Kind, "The span should be a server span.");
146+
Assert.AreEqual(incomingTraceId, serverActivity.TraceId, "The server span should continue the incoming trace.");
147+
Assert.AreEqual(incomingParentSpanId, serverActivity.ParentSpanId, "The server span should be parented to the incoming span.");
148+
}
149+
91150
/// <summary>
92151
/// Tests if the services are correctly disabled for Open Telemetry.
93152
/// </summary>

‎src/Service/Startup.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,9 @@ public void ConfigureServices(IServiceCollection services)
213213
.WithTracing(tracing =>
214214
{
215215
tracing.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(runtimeConfig.Runtime.Telemetry.OpenTelemetry.ServiceName!))
216+
// Creates a server span for every inbound HTTP request (REST, GraphQL, MCP, health)
217+
// and continues the incoming W3C traceparent, so DAB spans are parented correctly.
218+
.AddAspNetCoreInstrumentation()
216219
.AddHttpClientInstrumentation()
217220
// TODO: should we also add FusionCache traces?
218221
// To do so we just need to add the package ZiggyCreatures.FusionCache.OpenTelemetry and call

0 commit comments

Comments
 (0)