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

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

Merged
merged 3 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
86 changes: 45 additions & 41 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -757,50 +757,54 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<void> {
await this.prepare()
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')
if (route) {
const newName = `${method} ${route}`
const tracer = getTracer()
return tracer.withPropagatedContext(req, () => {
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({
'next.route': route,
'http.route': route,
'next.span_name': newName,
'http.status_code': res.statusCode,
})
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(
Expand Down
18 changes: 15 additions & 3 deletions packages/next/src/server/lib/trace/tracer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BaseNextRequest } from '../../base-http'
import type { SpanTypes } from './constants'
import { NextVanillaSpanAllowlist } from './constants'

Expand Down Expand Up @@ -28,7 +29,8 @@ if (process.env.NEXT_RUNTIME === 'edge') {
}
}

const { context, trace, SpanStatusCode, SpanKind } = api
const { context, propagation, trace, SpanStatusCode, SpanKind, ROOT_CONTEXT } =
dvoytenko marked this conversation as resolved.
Show resolved Hide resolved
api

const isPromise = <T>(p: any): p is Promise<T> => {
return p !== null && typeof p === 'object' && typeof p.then === 'function'
Expand Down Expand Up @@ -171,6 +173,14 @@ class NextTracerImpl implements NextTracer {
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
// (https://datadoghq.dev/dd-trace-js/interfaces/tracer.html#trace).
public trace<T>(
Expand Down Expand Up @@ -229,7 +239,9 @@ class NextTracerImpl implements NextTracer {
let isRootSpan = false

if (!spanContext) {
spanContext = api.ROOT_CONTEXT
spanContext = ROOT_CONTEXT
isRootSpan = true
} else if (trace.getSpanContext(spanContext)?.isRemote) {
isRootSpan = true
}

Expand All @@ -241,7 +253,7 @@ class NextTracerImpl implements NextTracer {
...options.attributes,
}

return api.context.with(spanContext.setValue(rootSpanIdKey, spanId), () =>
return context.with(spanContext.setValue(rootSpanIdKey, spanId), () =>
this.getTracerInstance().startActiveSpan(
spanName,
options,
Expand Down
Loading
Loading