Unverified Commit c894f5df authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix missing route in otel spans without base-server (#91665)

When invoking `handler` exports directly without `base-server` we need
to ensure span names are still updated with the route correctly so not
just method name is in span name.
parent 3003e17b
......@@ -713,25 +713,21 @@ export async function handler(
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name,
})
span.updateName(name)
const route = rootSpanAttributes.get('next.route') || normalizedSrcPage
const name = `${method} ${route}`
// 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)
parentSpan.updateName(name)
}
} else {
span.updateName(`${method} ${srcPage}`)
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
})
}
......
......@@ -301,25 +301,21 @@ export async function handler(
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
} else {
span.updateName(`${method} ${srcPage}`)
const route = rootSpanAttributes.get('next.route') || normalizedSrcPage
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
})
}
......
......@@ -138,25 +138,21 @@ export async function handler(
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
} else {
span.updateName(`${method} ${srcPage}`)
const route = rootSpanAttributes.get('next.route') || srcPage
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
})
......
......@@ -224,6 +224,9 @@ export const getHandler = ({
const tracer = getTracer()
const activeSpan = tracer.getActiveScopeSpan()
const isWrappedByNextServer = Boolean(
routerServerContext?.isWrappedByNextServer
)
try {
const method = req.method || 'GET'
......@@ -413,26 +416,22 @@ export const getHandler = ({
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
} else {
span.updateName(`${method} ${srcPage}`)
const route = rootSpanAttributes.get('next.route') || srcPage
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': 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)
parentSpan.updateName(name)
}
})
} catch (err: unknown) {
......@@ -750,23 +749,27 @@ export const getHandler = ({
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
if (activeSpan) {
await handleResponse()
if (isWrappedByNextServer && activeSpan) {
await handleResponse(activeSpan)
} else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext(req.headers, () =>
tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${srcPage}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
await tracer.withPropagatedContext(
req.headers,
() =>
tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${srcPage}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
},
handleResponse
)
handleResponse
),
undefined,
!isWrappedByNextServer
)
}
} catch (err) {
......
import { createServer, type IncomingMessage, type ServerResponse } from 'http'
import path from 'path'
import { parse } from 'url'
import getPort from 'get-port'
import { trace } from '@opentelemetry/api'
......@@ -15,29 +16,73 @@ type EntrypointHandler = (
}
) => Promise<unknown>
function loadEntrypointHandler(pathParts: string[]): EntrypointHandler {
const entrypointPath = path.join(__dirname, '.next', 'server', ...pathParts)
const mod = require(entrypointPath) as { handler?: EntrypointHandler }
if (typeof mod.handler !== 'function') {
throw new Error(`Entrypoint handler missing at ${entrypointPath}`)
}
return mod.handler
}
async function main() {
const port = await getPort()
const hostname = 'localhost'
require('next/dist/server/node-environment')
const entrypointPath = path.join(
__dirname,
'.next',
'server',
const appPageHandler = loadEntrypointHandler([
'app',
'app',
'[param]',
'rsc-fetch',
'page.js'
)
const { handler } = require(entrypointPath) as { handler: EntrypointHandler }
'page.js',
])
const appRouteHandler = loadEntrypointHandler([
'app',
'api',
'app',
'[param]',
'data',
'route.js',
])
const pagesRouteHandler = loadEntrypointHandler([
'pages',
'pages',
'[param]',
'getServerSideProps.js',
])
const pagesApiRouteHandler = loadEntrypointHandler([
'pages',
'api',
'pages',
'[param]',
'basic.js',
])
const tracer = trace.getTracer('custom-entrypoint-server', '1.0.0')
const resolveHandler = (pathname: string): EntrypointHandler | undefined => {
if (pathname.startsWith('/app/')) return appPageHandler
if (pathname.startsWith('/api/app/')) return appRouteHandler
if (pathname.startsWith('/pages/')) return pagesRouteHandler
if (pathname.startsWith('/api/pages/')) return pagesApiRouteHandler
return undefined
}
createServer((req, res) => {
const method = req.method || 'GET'
const pathname = parse(req.url || '/', false).pathname || '/'
const handler = resolveHandler(pathname)
if (!handler) {
res.statusCode = 404
res.end('Not Found')
return
}
// Simulate a custom parent span around direct entrypoint invocation.
tracer.startActiveSpan('custom-entrypoint-request', async (span) => {
tracer.startActiveSpan(method, async (span) => {
try {
await handler(req, res, {
waitUntil: () => {},
......
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { check, retry } from 'next-test-utils'
import { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers'
import { SavedSpan } from './constants'
......@@ -11,6 +11,7 @@ const EXTERNAL = {
} as const
const COLLECTOR_PORT = 9001
const isStartMode = process.env.NEXT_TEST_MODE === 'start'
describe('opentelemetry', () => {
const { next, skipped, isNextDev } = nextTestSetup({
......@@ -1418,7 +1419,7 @@ describe('opentelemetry with custom server', () => {
})
})
if (!isNextDev) {
if (isStartMode) {
describe('opentelemetry with direct entrypoint handler', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
......@@ -1456,25 +1457,93 @@ if (!isNextDev) {
await collector.shutdown()
})
it('should propagate incoming context without next-server wrapper', async () => {
await next.fetch('/app/param/rsc-fetch', {
headers: {
traceparent: `00-${EXTERNAL.traceId}-${EXTERNAL.spanId}-01`,
},
})
const directEntrypointCases = [
{ pathname: '/app/param/rsc-fetch', route: '/app/[param]/rsc-fetch' },
{ pathname: '/api/app/param/data', route: '/api/app/[param]/data' },
{
pathname: '/pages/param/getServerSideProps',
route: '/pages/[param]/getServerSideProps',
},
{
pathname: '/api/pages/param/basic',
route: '/api/pages/[param]/basic',
},
] as const
describe.each(directEntrypointCases)(
'direct entrypoint $pathname',
({ pathname, route }) => {
it(`should add route names to handleRequest and parent spans for direct entrypoint ${pathname}`, async () => {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
await retry(
async () => {
const spans = collector.getSpans()
const handleRequestSpan = spans.find((span) => {
if (
span.attributes?.['next.span_type'] !==
'BaseServer.handleRequest'
) {
return false
}
const target = span.attributes?.['http.target'] as
| string
| undefined
return Boolean(target && target.includes(pathname))
})
expect(handleRequestSpan).toBeDefined()
expect(handleRequestSpan!.name).toBe(`GET ${route}`)
expect(handleRequestSpan!.attributes?.['http.target']).toContain(
pathname
)
expect(handleRequestSpan!.attributes?.['next.route']).toBe(route)
expect(handleRequestSpan!.attributes?.['http.route']).toBe(route)
expect(handleRequestSpan!.attributes?.['next.span_name']).toBe(
`GET ${route}`
)
const parentSpan = spans.find(
(span) =>
span.traceId === handleRequestSpan!.traceId &&
!span.parentId &&
!span.attributes?.['next.span_type'] &&
span.name === handleRequestSpan!.name
)
expect(parentSpan).toBeDefined()
expect(parentSpan!.name).toBe(`GET ${route}`)
},
30_000,
1_000,
`direct entrypoint span route naming ${pathname}`
)
})
await expectTrace(getCollector(), [
{
name: 'GET /app/[param]/rsc-fetch/page',
traceId: EXTERNAL.traceId,
parentId: EXTERNAL.spanId,
attributes: {
'http.target': '/app/param/rsc-fetch',
'next.span_type': 'BaseServer.handleRequest',
},
},
])
})
it(`should propagate incoming context without next-server wrapper for direct entrypoint ${pathname}`, async () => {
const response = await next.fetch(pathname, {
headers: {
traceparent: `00-${EXTERNAL.traceId}-${EXTERNAL.spanId}-01`,
},
})
expect(response.status).toBe(200)
await expectTrace(getCollector(), [
{
name: `GET ${route}`,
traceId: EXTERNAL.traceId,
parentId: EXTERNAL.spanId,
attributes: {
'http.target': pathname,
'next.span_type': 'BaseServer.handleRequest',
'http.route': route,
'next.route': route,
},
},
])
})
}
)
})
}
......
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