Unverified Commit d7b331f3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[otel] fix missing http.route attribute (#90832)

parent 296e1800
...@@ -549,6 +549,7 @@ export async function handler( ...@@ -549,6 +549,7 @@ export async function handler(
interceptionRoutePatterns interceptionRoutePatterns
) )
res.setHeader('Vary', varyHeader) res.setHeader('Vary', varyHeader)
let parentSpan: Span | undefined
const invokeRouteModule = async ( const invokeRouteModule = async (
span: Span | undefined, span: Span | undefined,
context: AppPageRouteHandlerContext context: AppPageRouteHandlerContext
...@@ -592,6 +593,12 @@ export async function handler( ...@@ -592,6 +593,12 @@ export async function handler(
'next.span_name': name, 'next.span_name': name,
}) })
span.updateName(name) span.updateName(name)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else { } else {
span.updateName(`${method} ${srcPage}`) span.updateName(`${method} ${srcPage}`)
} }
...@@ -1597,6 +1604,7 @@ export async function handler( ...@@ -1597,6 +1604,7 @@ export async function handler(
if (isWrappedByNextServer && activeSpan) { if (isWrappedByNextServer && activeSpan) {
await handleResponse(activeSpan) await handleResponse(activeSpan)
} else { } else {
parentSpan = tracer.getActiveScopeSpan()
return await tracer.withPropagatedContext( return await tracer.withPropagatedContext(
req.headers, req.headers,
() => () =>
......
...@@ -263,6 +263,7 @@ export async function handler( ...@@ -263,6 +263,7 @@ export async function handler(
) )
try { try {
let parentSpan: Span | undefined
const invokeRouteModule = async (span?: Span) => { const invokeRouteModule = async (span?: Span) => {
return routeModule.handle(nextReq, context).finally(() => { return routeModule.handle(nextReq, context).finally(() => {
if (!span) return if (!span) return
...@@ -300,6 +301,12 @@ export async function handler( ...@@ -300,6 +301,12 @@ export async function handler(
'next.span_name': name, 'next.span_name': name,
}) })
span.updateName(name) span.updateName(name)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else { } else {
span.updateName(`${method} ${srcPage}`) span.updateName(`${method} ${srcPage}`)
} }
...@@ -497,6 +504,7 @@ export async function handler( ...@@ -497,6 +504,7 @@ export async function handler(
if (isWrappedByNextServer && activeSpan) { if (isWrappedByNextServer && activeSpan) {
await handleResponse(activeSpan) await handleResponse(activeSpan)
} else { } else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext( await tracer.withPropagatedContext(
req.headers, req.headers,
() => () =>
......
...@@ -86,6 +86,7 @@ export async function handler( ...@@ -86,6 +86,7 @@ export async function handler(
const onRequestError = const onRequestError =
routeModule.instrumentationOnRequestError.bind(routeModule) routeModule.instrumentationOnRequestError.bind(routeModule)
let parentSpan: Span | undefined
const invokeRouteModule = async (span?: Span) => const invokeRouteModule = async (span?: Span) =>
routeModule routeModule
.render(req, res, { .render(req, res, {
...@@ -147,6 +148,12 @@ export async function handler( ...@@ -147,6 +148,12 @@ export async function handler(
'next.span_name': name, 'next.span_name': name,
}) })
span.updateName(name) span.updateName(name)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else { } else {
span.updateName(`${method} ${srcPage}`) span.updateName(`${method} ${srcPage}`)
} }
...@@ -157,6 +164,7 @@ export async function handler( ...@@ -157,6 +164,7 @@ export async function handler(
if (isWrappedByNextServer && activeSpan) { if (isWrappedByNextServer && activeSpan) {
await invokeRouteModule(activeSpan) await invokeRouteModule(activeSpan)
} else { } else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext( await tracer.withPropagatedContext(
req.headers, req.headers,
() => () =>
......
...@@ -876,6 +876,13 @@ export default abstract class Server< ...@@ -876,6 +876,13 @@ export default abstract class Server<
const tracer = getTracer() const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () => { return tracer.withPropagatedContext(req.headers, () => {
// Capture the parent span before creating the handleRequest span.
// When deployed with an adapter, the platform's runtime may create its
// own OTEL HTTP server span before Next.js runs. We propagate http.route
// to this parent span so APM tools (e.g. Datadog) can derive the
// resource name correctly.
const parentSpan = tracer.getActiveScopeSpan()
return tracer.trace( return tracer.trace(
BaseServerSpan.handleRequest, BaseServerSpan.handleRequest,
{ {
...@@ -934,6 +941,14 @@ export default abstract class Server< ...@@ -934,6 +941,14 @@ export default abstract class Server<
'next.span_name': name, 'next.span_name': name,
}) })
span.updateName(name) span.updateName(name)
// Propagate http.route to the parent span if one exists and
// is different from the handleRequest span. This ensures APM
// tools that read attributes from the outermost span (e.g.
// a platform-created HTTP span) can derive the resource name.
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else { } else {
span.updateName(isRSCRequest ? `RSC ${method}` : `${method}`) span.updateName(isRSCRequest ? `RSC ${method}` : `${method}`)
} }
......
...@@ -236,6 +236,7 @@ export const getHandler = ({ ...@@ -236,6 +236,7 @@ export const getHandler = ({
query: hasStaticProps ? {} : originalQuery, query: hasStaticProps ? {} : originalQuery,
}) })
let parentSpan: Span | undefined
const handleResponse = async (span?: Span) => { const handleResponse = async (span?: Span) => {
const responseGenerator: ResponseGenerator = async ({ const responseGenerator: ResponseGenerator = async ({
previousCacheEntry, previousCacheEntry,
...@@ -422,6 +423,13 @@ export const getHandler = ({ ...@@ -422,6 +423,13 @@ export const getHandler = ({
'next.span_name': name, 'next.span_name': name,
}) })
span.updateName(name) span.updateName(name)
// Propagate http.route to the parent span if one exists
// (e.g. a platform-created HTTP span in adapter
// deployments).
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else { } else {
span.updateName(`${method} ${srcPage}`) span.updateName(`${method} ${srcPage}`)
} }
...@@ -755,6 +763,7 @@ export const getHandler = ({ ...@@ -755,6 +763,7 @@ export const getHandler = ({
if (activeSpan) { if (activeSpan) {
await handleResponse() await handleResponse()
} else { } else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext(req.headers, () => await tracer.withPropagatedContext(req.headers, () =>
tracer.trace( tracer.trace(
BaseServerSpan.handleRequest, BaseServerSpan.handleRequest,
......
import { Suspense } from 'react'
import { connection } from 'next/server'
async function SlugContent({ params }: { params: Promise<{ slug: string }> }) {
await connection()
const { slug } = await params
return <p>slug: {slug}</p>
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<Suspense fallback={<p>loading...</p>}>
<SlugContent params={params} />
</Suspense>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { Server as HttpServer } from 'node:http'
import { SavedSpan } from './constants'
export interface Collector {
getSpans: () => SavedSpan[]
shutdown: () => Promise<void>
}
export async function connectCollector({
port,
}: {
port: number
}): Promise<Collector> {
const spans: SavedSpan[] = []
const server = new HttpServer(async (req, res) => {
if (req.method !== 'POST') {
res.writeHead(405)
res.end()
return
}
const body = await new Promise<Buffer>((resolve, reject) => {
const acc: Buffer[] = []
req.on('data', (chunk: Buffer) => {
acc.push(chunk)
})
req.on('end', () => {
resolve(Buffer.concat(acc))
})
req.on('error', reject)
})
const newSpans = JSON.parse(body.toString('utf-8')) as SavedSpan[]
spans.push(...newSpans)
res.statusCode = 202
res.end()
})
await new Promise<void>((resolve, reject) => {
server.listen(port, (err?: Error) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
return {
getSpans() {
return spans
},
shutdown() {
return new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
).catch((err) => {
console.warn('WARN: collector server disconnect failure:', err)
})
},
}
}
import { SpanKind } from '@opentelemetry/api'
export type SavedSpan = {
runtime?: string
traceId?: string
parentId?: string
name?: string
id?: string
kind?: SpanKind
timestamp?: number
duration?: number
attributes?: Record<string, any>
status?: any
}
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import {
SimpleSpanProcessor,
SpanExporter,
ReadableSpan,
BasicTracerProvider,
} from '@opentelemetry/sdk-trace-base'
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'
import {
ExportResult,
ExportResultCode,
hrTimeToMicroseconds,
} from '@opentelemetry/core'
import { SavedSpan } from './constants'
const serializeSpan = (span: ReadableSpan): SavedSpan => ({
runtime: process.env.NEXT_RUNTIME,
traceId: span.spanContext().traceId,
parentId: span.parentSpanId,
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: hrTimeToMicroseconds(span.startTime),
duration: hrTimeToMicroseconds(span.duration),
attributes: span.attributes,
status: span.status,
})
class TestExporter implements SpanExporter {
constructor(private port: number) {}
async export(
spans: ReadableSpan[],
resultCallback: (result: ExportResult) => void
) {
try {
const response = await fetch(`http://localhost:${this.port}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(spans.map(serializeSpan)),
})
try {
await response.arrayBuffer()
} catch (e) {
// ignore.
}
if (response.status >= 400) {
resultCallback({
code: ExportResultCode.FAILED,
error: new Error(`http status ${response.status}`),
})
return
}
resultCallback({ code: ExportResultCode.SUCCESS })
} catch (e) {
resultCallback({ code: ExportResultCode.FAILED, error: e })
}
}
shutdown(): Promise<void> {
return Promise.resolve()
}
}
export async function register() {
if (!process.env.TEST_OTEL_COLLECTOR_PORT) {
throw new Error('TEST_OTEL_COLLECTOR_PORT is not set')
}
const port = parseInt(process.env.TEST_OTEL_COLLECTOR_PORT)
const contextManager = new AsyncLocalStorageContextManager()
contextManager.enable()
const provider = new BasicTracerProvider({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'test-next-app',
}),
})
provider.addSpanProcessor(new SimpleSpanProcessor(new TestExporter(port)))
provider.register({
contextManager,
})
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { type Collector, connectCollector } from './collector'
const COLLECTOR_PORT = 9876
describe('otel-parent-span-propagation', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: require('./package.json').dependencies,
env: {
TEST_OTEL_COLLECTOR_PORT: String(COLLECTOR_PORT),
NEXT_TELEMETRY_DISABLED: '1',
},
})
if (skipped) {
return
}
let collector: Collector
beforeEach(async () => {
collector = await connectCollector({ port: COLLECTOR_PORT })
})
afterEach(async () => {
await collector.shutdown()
})
// Verifies that http.route is set on the handleRequest span.
// In production, when external OTEL instrumentation (e.g. Datadog,
// @opentelemetry/instrumentation-http) creates a parent HTTP server span,
// our fix also propagates http.route to that parent span so APM tools
// derive the resource name correctly (e.g. "GET /[slug]" instead of "GET").
// Parent span propagation is verified manually in production environments.
it('should set http.route on handleRequest span for dynamic routes', async () => {
await next.fetch('/test-slug')
await retry(async () => {
const spans = collector.getSpans()
const handleRequestSpan = spans.find(
(s) =>
s.attributes?.['next.span_type'] === 'BaseServer.handleRequest' &&
s.attributes?.['http.target'] === '/test-slug'
)
expect(handleRequestSpan).toBeDefined()
expect(handleRequestSpan!.attributes?.['http.route']).toBe('/[slug]')
expect(handleRequestSpan!.attributes?.['next.route']).toBe('/[slug]')
expect(handleRequestSpan!.name).toBe('GET /[slug]')
})
})
it('should set http.route on handleRequest span for static routes', async () => {
await next.fetch('/')
await retry(async () => {
const spans = collector.getSpans()
const handleRequestSpan = spans.find(
(s) =>
s.attributes?.['next.span_type'] === 'BaseServer.handleRequest' &&
s.attributes?.['http.target'] === '/'
)
expect(handleRequestSpan).toBeDefined()
expect(handleRequestSpan!.attributes?.['http.route']).toBe('/')
expect(handleRequestSpan!.attributes?.['next.route']).toBe('/')
expect(handleRequestSpan!.name).toBe('GET /')
})
})
})
{
"dependencies": {
"@opentelemetry/api": "^1.7.0",
"@opentelemetry/context-async-hooks": "^1.21.0",
"@opentelemetry/core": "^1.21.0",
"@opentelemetry/resources": "^1.21.0",
"@opentelemetry/sdk-trace-base": "^1.21.0",
"@opentelemetry/semantic-conventions": "^1.21.0"
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment