Unverified Commit 08fdc1eb authored by Dima Voytenko's avatar Dima Voytenko Committed by GitHub

OpenTelemetry: propagate a configured context(s) to root requests (#57084)

Implement OTEL propagation according to the OpenTelemetry API per
https://opentelemetry.io/docs/specs/otel/context/api-propagators/. Any
configured propagator should work with this API, including
`W3CTraceContextPropagator` (https://www.w3.org/TR/trace-context/).

Alternative to the https://github.com/vercel/next.js/pull/56891.

/cc @sfirrin
parent ec8ee596
...@@ -755,50 +755,54 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -755,50 +755,54 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<void> { ): Promise<void> {
await this.prepare() await this.prepare()
const method = req.method.toUpperCase() const method = req.method.toUpperCase()
return getTracer().trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
if (!span) return
span.setAttributes({
'http.status_code': res.statusCode,
})
const rootSpanAttributes = getTracer().getRootSpanAttributes()
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) return
if (
rootSpanAttributes.get('next.span_type') !==
BaseServerSpan.handleRequest
) {
console.warn(
`Unexpected root span type '${rootSpanAttributes.get(
'next.span_type'
)}'. Please report this Next.js issue https://github.com/vercel/next.js`
)
return
}
const route = rootSpanAttributes.get('next.route') const tracer = getTracer()
if (route) { return tracer.withPropagatedContext(req, () => {
const newName = `${method} ${route}` return tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
if (!span) return
span.setAttributes({ span.setAttributes({
'next.route': route, 'http.status_code': res.statusCode,
'http.route': route,
'next.span_name': newName,
}) })
span.updateName(newName) const rootSpanAttributes = tracer.getRootSpanAttributes()
} // We were unable to get attributes, probably OTEL is not enabled
}) if (!rootSpanAttributes) return
)
if (
rootSpanAttributes.get('next.span_type') !==
BaseServerSpan.handleRequest
) {
console.warn(
`Unexpected root span type '${rootSpanAttributes.get(
'next.span_type'
)}'. Please report this Next.js issue https://github.com/vercel/next.js`
)
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const newName = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': newName,
})
span.updateName(newName)
}
})
)
})
} }
private async handleRequestImpl( private async handleRequestImpl(
......
import type { BaseNextRequest } from '../../base-http'
import type { SpanTypes } from './constants' import type { SpanTypes } from './constants'
import { NextVanillaSpanAllowlist } from './constants' import { NextVanillaSpanAllowlist } from './constants'
...@@ -28,7 +29,8 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -28,7 +29,8 @@ if (process.env.NEXT_RUNTIME === 'edge') {
} }
} }
const { context, trace, SpanStatusCode, SpanKind } = api const { context, propagation, trace, SpanStatusCode, SpanKind, ROOT_CONTEXT } =
api
const isPromise = <T>(p: any): p is Promise<T> => { const isPromise = <T>(p: any): p is Promise<T> => {
return p !== null && typeof p === 'object' && typeof p.then === 'function' return p !== null && typeof p === 'object' && typeof p.then === 'function'
...@@ -171,6 +173,14 @@ class NextTracerImpl implements NextTracer { ...@@ -171,6 +173,14 @@ class NextTracerImpl implements NextTracer {
return trace.getSpan(context?.active()) return trace.getSpan(context?.active())
} }
public withPropagatedContext<T>(req: BaseNextRequest, fn: () => T): T {
if (context.active() !== ROOT_CONTEXT) {
return fn()
}
const remoteContext = propagation.extract(ROOT_CONTEXT, req.headers)
return context.with(remoteContext, fn)
}
// Trace, wrap implementation is inspired by datadog trace implementation // Trace, wrap implementation is inspired by datadog trace implementation
// (https://datadoghq.dev/dd-trace-js/interfaces/tracer.html#trace). // (https://datadoghq.dev/dd-trace-js/interfaces/tracer.html#trace).
public trace<T>( public trace<T>(
...@@ -229,7 +239,9 @@ class NextTracerImpl implements NextTracer { ...@@ -229,7 +239,9 @@ class NextTracerImpl implements NextTracer {
let isRootSpan = false let isRootSpan = false
if (!spanContext) { if (!spanContext) {
spanContext = api.ROOT_CONTEXT spanContext = ROOT_CONTEXT
isRootSpan = true
} else if (trace.getSpanContext(spanContext)?.isRemote) {
isRootSpan = true isRootSpan = true
} }
...@@ -241,7 +253,7 @@ class NextTracerImpl implements NextTracer { ...@@ -241,7 +253,7 @@ class NextTracerImpl implements NextTracer {
...options.attributes, ...options.attributes,
} }
return api.context.with(spanContext.setValue(rootSpanIdKey, spanId), () => return context.with(spanContext.setValue(rootSpanIdKey, spanId), () =>
this.getTracerInstance().startActiveSpan( this.getTracerInstance().startActiveSpan(
spanName, spanName,
options, options,
......
export default function Page() {
return <div>Page</div>
}
export function getStaticProps() {
return {
props: {},
}
}
// We don't want to render in build time
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
}
}
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