Unverified Commit 46201e16 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Improve OTEL spans naming (#47209)

Adds bunch of default attributes and span names as discussed in https://github.com/vercel/next.js/pull/47066

Also discovered a few issues with our test setup.
It's actually quite handy to use jest snapshots for this, thanks for the tip @feedthejim 

Currently we have following spans:
- root span with name `GET /app/rsc-fetch` (both API calls and page requests)
  - `SERVER` span	
  - attributes:
    -  `"http.method": "GET"`
    -  `"http.status_code": 200`
    -  `"http.target": "/app/rsc-fetch"`
    -  `"next.span_name": "GET /app/rsc-fetch"`
    -  `"next.span_type": "BaseServer.handleRequest"`
- fetch span `fetch GET https://vercel.com/`
  - `CLIENT` span	
  - attributes:
    -  `"http.method": "GET"`
    -  `"http.url": "https://vercel.com/"`
    -  `"net.peer.name": "vercel.com"`
    -  `"next.span_name": "fetch GET https://vercel.com/"`
    -  `"next.span_type": "AppRender.fetch"`

- rendering of page `rendering /app/rsc-fetch`
  - attributes:
    -  `"next.pathname": "/app/rsc-fetch"`
    -  `"next.span_name": "rendering /app/rsc-fetch"`
    -  `"next.span_type": "BaseServer.renderToResponse"`
    
- finding the right page component `resolving route /app/rsc-fetch/page`
  - attributes
    -  `"next.route": "/app/rsc-fetch/page"`
    -  `"next.span_name": "resolving route /app/rsc-fetch/page"`
    -  `"next.span_type": "NextNodeServer.findPageComponents"`
    
- getServerSideProps `getServerSideProps /pages/getServerSideProps`
  - attributes
    -  `"next.span_name": "getServerSideProps /pages/getServerSideProps"`
    -  `"next.span_type": "Render.getServerSideProps"`
    

fix NEXT-829 ([link](https://linear.app/vercel/issue/NEXT-829))
parent 40cb797a
...@@ -90,7 +90,7 @@ import { AppRouteRouteMatcherProvider } from './future/route-matcher-providers/a ...@@ -90,7 +90,7 @@ import { AppRouteRouteMatcherProvider } from './future/route-matcher-providers/a
import { PagesAPIRouteMatcherProvider } from './future/route-matcher-providers/pages-api-route-matcher-provider' import { PagesAPIRouteMatcherProvider } from './future/route-matcher-providers/pages-api-route-matcher-provider'
import { PagesRouteMatcherProvider } from './future/route-matcher-providers/pages-route-matcher-provider' import { PagesRouteMatcherProvider } from './future/route-matcher-providers/pages-route-matcher-provider'
import { ServerManifestLoader } from './future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader' import { ServerManifestLoader } from './future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'
import { getTracer } from './lib/trace/tracer' import { getTracer, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants' import { BaseServerSpan } from './lib/trace/constants'
import { sendResponse } from './future/route-handlers/app-route-route-handler' import { sendResponse } from './future/route-handlers/app-route-route-handler'
import { I18NProvider } from './future/helpers/i18n-provider' import { I18NProvider } from './future/helpers/i18n-provider'
...@@ -520,7 +520,20 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -520,7 +520,20 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<void> { ): Promise<void> {
return getTracer().trace( return getTracer().trace(
BaseServerSpan.handleRequest, BaseServerSpan.handleRequest,
async () => await this.handleRequestImpl(req, res, parsedUrl) {
spanName: [req.method, req.url].join(' '),
kind: SpanKind.SERVER,
attributes: {
'http.method': req.method,
'http.target': req.url,
},
},
async (span) =>
await this.handleRequestImpl(req, res, parsedUrl).finally(() =>
span?.setAttributes({
'http.status_code': res.statusCode,
})
)
) )
} }
...@@ -1907,9 +1920,18 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1907,9 +1920,18 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private async renderToResponse( private async renderToResponse(
ctx: RequestContext ctx: RequestContext
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
return getTracer().trace(BaseServerSpan.renderToResponse, async () => { return getTracer().trace(
return this.renderToResponseImpl(ctx) BaseServerSpan.renderToResponse,
}) {
spanName: `rendering page`,
attributes: {
'next.pathname': ctx.pathname,
},
},
async () => {
return this.renderToResponseImpl(ctx)
}
)
} }
private async renderToResponseImpl( private async renderToResponseImpl(
......
This diff is collapsed.
...@@ -88,7 +88,7 @@ enum RouterSpan { ...@@ -88,7 +88,7 @@ enum RouterSpan {
executeRoute = 'Router.executeRoute', executeRoute = 'Router.executeRoute',
} }
type SpanNames = type SpanTypes =
| `${BaseServerSpan}` | `${BaseServerSpan}`
| `${LoadComponentsSpan}` | `${LoadComponentsSpan}`
| `${NextServerSpan}` | `${NextServerSpan}`
...@@ -100,7 +100,7 @@ type SpanNames = ...@@ -100,7 +100,7 @@ type SpanNames =
// This list is used to filter out spans that are not relevant to the user // This list is used to filter out spans that are not relevant to the user
export const NextVanillaSpanAllowlist = [ export const NextVanillaSpanAllowlist = [
NextServerSpan.getRequestHandler, BaseServerSpan.handleRequest,
NextNodeServerSpan.findPageComponents, NextNodeServerSpan.findPageComponents,
BaseServerSpan.renderToResponse, BaseServerSpan.renderToResponse,
RenderSpan.getServerSideProps, RenderSpan.getServerSideProps,
...@@ -113,7 +113,7 @@ export { ...@@ -113,7 +113,7 @@ export {
NextServerSpan, NextServerSpan,
NextNodeServerSpan, NextNodeServerSpan,
StartServerSpan, StartServerSpan,
SpanNames, SpanTypes,
RenderSpan, RenderSpan,
RouterSpan, RouterSpan,
AppRenderSpan, AppRenderSpan,
......
import { NextVanillaSpanAllowlist, SpanNames } from './constants' import { NextVanillaSpanAllowlist, SpanTypes } from './constants'
import type { ContextAPI, Span, SpanOptions, Tracer } from '@opentelemetry/api' import type { ContextAPI, Span, SpanOptions, Tracer } from '@opentelemetry/api'
...@@ -24,13 +24,16 @@ const isPromise = <T>(p: any): p is Promise<T> => { ...@@ -24,13 +24,16 @@ const isPromise = <T>(p: any): p is Promise<T> => {
} }
const closeSpanWithError = (span: Span, error?: Error) => { const closeSpanWithError = (span: Span, error?: Error) => {
if (error) {
span.recordException(error)
}
span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message }) span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message })
span.end() span.end()
} }
type TracerSpanOptions = SpanOptions & { type TracerSpanOptions = SpanOptions & {
parentSpan?: Span parentSpan?: Span
tracerName?: string spanName?: string
} }
interface NextTracer { interface NextTracer {
...@@ -52,22 +55,22 @@ interface NextTracer { ...@@ -52,22 +55,22 @@ interface NextTracer {
* *
*/ */
trace<T>( trace<T>(
name: SpanNames, type: SpanTypes,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T> fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T> ): Promise<T>
trace<T>( trace<T>(
name: SpanNames, type: SpanTypes,
fn: (span: Span, done?: (error?: Error) => any) => T fn: (span?: Span, done?: (error?: Error) => any) => T
): T ): T
trace<T>( trace<T>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T> fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T> ): Promise<T>
trace<T>( trace<T>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => T fn: (span?: Span, done?: (error?: Error) => any) => T
): T ): T
/** /**
...@@ -84,14 +87,14 @@ interface NextTracer { ...@@ -84,14 +87,14 @@ interface NextTracer {
* * The function doesn't accept a callback and doesn't return a promise, in * * The function doesn't accept a callback and doesn't return a promise, in
* which case the span will finish at the end of the function execution. * which case the span will finish at the end of the function execution.
*/ */
wrap<T = (...args: Array<any>) => any>(name: SpanNames, fn: T): T wrap<T = (...args: Array<any>) => any>(type: SpanTypes, fn: T): T
wrap<T = (...args: Array<any>) => any>( wrap<T = (...args: Array<any>) => any>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: T fn: T
): T ): T
wrap<T = (...args: Array<any>) => any>( wrap<T = (...args: Array<any>) => any>(
name: SpanNames, type: SpanTypes,
options: (...args: any[]) => TracerSpanOptions, options: (...args: any[]) => TracerSpanOptions,
fn: T fn: T
): T ): T
...@@ -104,8 +107,8 @@ interface NextTracer { ...@@ -104,8 +107,8 @@ interface NextTracer {
* context via `tracer.getContext().with`. `trace`, or `wrap` is generally recommended as it gracefully * context via `tracer.getContext().with`. `trace`, or `wrap` is generally recommended as it gracefully
* handles context activation. (ref: https://github.com/open-telemetry/opentelemetry-js/issues/1923) * handles context activation. (ref: https://github.com/open-telemetry/opentelemetry-js/issues/1923)
*/ */
startSpan(name: SpanNames): Span startSpan(type: SpanTypes): Span
startSpan(name: SpanNames, options: TracerSpanOptions): Span startSpan(type: SpanTypes, options: TracerSpanOptions): Span
/** /**
* Returns currently activated span if current context is in the scope of the span. * Returns currently activated span if current context is in the scope of the span.
...@@ -135,25 +138,25 @@ class NextTracerImpl implements NextTracer { ...@@ -135,25 +138,25 @@ class NextTracerImpl implements NextTracer {
// 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>(
name: SpanNames, type: SpanTypes,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T> fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T> ): Promise<T>
public trace<T>( public trace<T>(
name: SpanNames, type: SpanTypes,
fn: (span: Span, done?: (error?: Error) => any) => T fn: (span?: Span, done?: (error?: Error) => any) => T
): T ): T
public trace<T>( public trace<T>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T> fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T> ): Promise<T>
public trace<T>( public trace<T>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => T fn: (span?: Span, done?: (error?: Error) => any) => T
): T ): T
public trace<T>(...args: Array<any>) { public trace<T>(...args: Array<any>) {
const [name, fnOrOptions, fnOrEmpty] = args const [type, fnOrOptions, fnOrEmpty] = args
// coerce options form overload // coerce options form overload
const { const {
...@@ -170,30 +173,38 @@ class NextTracerImpl implements NextTracer { ...@@ -170,30 +173,38 @@ class NextTracerImpl implements NextTracer {
} }
: { : {
fn: fnOrEmpty, fn: fnOrEmpty,
options: fnOrOptions, options: { ...fnOrOptions },
} }
if ( if (
!NextVanillaSpanAllowlist.includes(name) && !NextVanillaSpanAllowlist.includes(type) &&
process.env.NEXT_OTEL_VERBOSE !== '1' process.env.NEXT_OTEL_VERBOSE !== '1'
) { ) {
return fn() return fn()
} }
const spanName = options.spanName ?? type
// Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it. // Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it.
const spanContext = this.getSpanContext( const spanContext = this.getSpanContext(
options?.parentSpan ?? this.getActiveScopeSpan() options?.parentSpan ?? this.getActiveScopeSpan()
) )
options.attributes = {
'next.span_name': spanName,
'next.span_type': type,
...options.attributes,
}
const runWithContext = (actualFn: (span: Span) => T | Promise<T>) => const runWithContext = (actualFn: (span: Span) => T | Promise<T>) =>
spanContext spanContext
? this.getTracerInstance().startActiveSpan( ? this.getTracerInstance().startActiveSpan(
name, spanName,
options, options,
spanContext, spanContext,
actualFn actualFn
) )
: this.getTracerInstance().startActiveSpan(name, options, actualFn) : this.getTracerInstance().startActiveSpan(spanName, options, actualFn)
return runWithContext((span: Span) => { return runWithContext((span: Span) => {
try { try {
...@@ -220,14 +231,14 @@ class NextTracerImpl implements NextTracer { ...@@ -220,14 +231,14 @@ class NextTracerImpl implements NextTracer {
}) })
} }
public wrap<T = (...args: Array<any>) => any>(name: SpanNames, fn: T): T public wrap<T = (...args: Array<any>) => any>(type: SpanTypes, fn: T): T
public wrap<T = (...args: Array<any>) => any>( public wrap<T = (...args: Array<any>) => any>(
name: SpanNames, type: SpanTypes,
options: TracerSpanOptions, options: TracerSpanOptions,
fn: T fn: T
): T ): T
public wrap<T = (...args: Array<any>) => any>( public wrap<T = (...args: Array<any>) => any>(
name: SpanNames, type: SpanTypes,
options: (...args: any[]) => TracerSpanOptions, options: (...args: any[]) => TracerSpanOptions,
fn: T fn: T
): T ): T
...@@ -268,15 +279,15 @@ class NextTracerImpl implements NextTracer { ...@@ -268,15 +279,15 @@ class NextTracerImpl implements NextTracer {
} }
} }
public startSpan(name: SpanNames): Span public startSpan(type: SpanTypes): Span
public startSpan(name: SpanNames, options: TracerSpanOptions): Span public startSpan(type: SpanTypes, options: TracerSpanOptions): Span
public startSpan(...args: Array<any>): Span { public startSpan(...args: Array<any>): Span {
const [name, options]: [string, TracerSpanOptions | undefined] = args as any const [type, options]: [string, TracerSpanOptions | undefined] = args as any
const spanContext = this.getSpanContext( const spanContext = this.getSpanContext(
options?.parentSpan ?? this.getActiveScopeSpan() options?.parentSpan ?? this.getActiveScopeSpan()
) )
return this.getTracerInstance().startSpan(name, options, spanContext) return this.getTracerInstance().startSpan(type, options, spanContext)
} }
private getSpanContext(parentSpan?: Span) { private getSpanContext(parentSpan?: Span) {
......
...@@ -958,8 +958,15 @@ export default class NextNodeServer extends BaseServer { ...@@ -958,8 +958,15 @@ export default class NextNodeServer extends BaseServer {
params: Params | null params: Params | null
isAppPath: boolean isAppPath: boolean
}): Promise<FindComponentsResult | null> { }): Promise<FindComponentsResult | null> {
return getTracer().trace(NextNodeServerSpan.findPageComponents, () => return getTracer().trace(
this.findPageComponentsImpl({ pathname, query, params, isAppPath }) NextNodeServerSpan.findPageComponents,
{
spanName: `resolving page into components`,
attributes: {
'next.route': pathname,
},
},
() => this.findPageComponentsImpl({ pathname, query, params, isAppPath })
) )
} }
......
...@@ -962,22 +962,29 @@ export async function renderToHTML( ...@@ -962,22 +962,29 @@ export async function renderToHTML(
} }
try { try {
data = await getTracer().trace(RenderSpan.getServerSideProps, async () => data = await getTracer().trace(
getServerSideProps({ RenderSpan.getServerSideProps,
req: req as IncomingMessage & { {
cookies: NextApiRequestCookies spanName: `getServerSideProps ${pathname}`,
}, },
res: resOrProxy, async () =>
query, getServerSideProps({
resolvedUrl: renderOpts.resolvedUrl as string, req: req as IncomingMessage & {
...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined), cookies: NextApiRequestCookies
...(previewData !== false },
? { preview: true, previewData: previewData } res: resOrProxy,
: undefined), query,
locales: renderOpts.locales, resolvedUrl: renderOpts.resolvedUrl as string,
locale: renderOpts.locale, ...(pageIsDynamic
defaultLocale: renderOpts.defaultLocale, ? { params: params as ParsedUrlQuery }
}) : undefined),
...(previewData !== false
? { preview: true, previewData: previewData }
: undefined),
locales: renderOpts.locales,
locale: renderOpts.locale,
defaultLocale: renderOpts.defaultLocale,
})
) )
canAccessRes = false canAccessRes = false
} catch (serverSidePropsError: any) { } catch (serverSidePropsError: any) {
......
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export default async function Page() { export default async function Page() {
const data = await fetch('https://user:pass@vercel.com') const data = await fetch('https://vercel.com')
return <pre>{await data.text()}</pre> return <pre>{await data.text()}</pre>
} }
...@@ -3,16 +3,16 @@ import { SpanKind } from '@opentelemetry/api' ...@@ -3,16 +3,16 @@ import { SpanKind } from '@opentelemetry/api'
export const traceFile = 'otel-trace.txt' export const traceFile = 'otel-trace.txt'
export type SavedSpan = { export type SavedSpan = {
traceId: string traceId?: string
parentId?: string parentId?: string
traceState: any traceState?: any
name: string name?: string
id: string id?: string
kind: SpanKind kind?: SpanKind
timestamp: number timestamp?: number
duration: number duration?: number
attributes: Record<string, any> attributes?: Record<string, any>
status: any status?: any
events: any[] events?: any[]
links: any[] links?: any[]
} }
export default async function Page() { export default function Page() {
return <div>Page</div> return <div>Page</div>
} }
......
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