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
import { PagesAPIRouteMatcherProvider } from './future/route-matcher-providers/pages-api-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 { getTracer } from './lib/trace/tracer'
import { getTracer, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants'
import { sendResponse } from './future/route-handlers/app-route-route-handler'
import { I18NProvider } from './future/helpers/i18n-provider'
......@@ -520,7 +520,20 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<void> {
return getTracer().trace(
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> {
private async renderToResponse(
ctx: RequestContext
): Promise<ResponsePayload | null> {
return getTracer().trace(BaseServerSpan.renderToResponse, async () => {
return this.renderToResponseImpl(ctx)
})
return getTracer().trace(
BaseServerSpan.renderToResponse,
{
spanName: `rendering page`,
attributes: {
'next.pathname': ctx.pathname,
},
},
async () => {
return this.renderToResponseImpl(ctx)
}
)
}
private async renderToResponseImpl(
......
This diff is collapsed.
......@@ -88,7 +88,7 @@ enum RouterSpan {
executeRoute = 'Router.executeRoute',
}
type SpanNames =
type SpanTypes =
| `${BaseServerSpan}`
| `${LoadComponentsSpan}`
| `${NextServerSpan}`
......@@ -100,7 +100,7 @@ type SpanNames =
// This list is used to filter out spans that are not relevant to the user
export const NextVanillaSpanAllowlist = [
NextServerSpan.getRequestHandler,
BaseServerSpan.handleRequest,
NextNodeServerSpan.findPageComponents,
BaseServerSpan.renderToResponse,
RenderSpan.getServerSideProps,
......@@ -113,7 +113,7 @@ export {
NextServerSpan,
NextNodeServerSpan,
StartServerSpan,
SpanNames,
SpanTypes,
RenderSpan,
RouterSpan,
AppRenderSpan,
......
import { NextVanillaSpanAllowlist, SpanNames } from './constants'
import { NextVanillaSpanAllowlist, SpanTypes } from './constants'
import type { ContextAPI, Span, SpanOptions, Tracer } from '@opentelemetry/api'
......@@ -24,13 +24,16 @@ const isPromise = <T>(p: any): p is Promise<T> => {
}
const closeSpanWithError = (span: Span, error?: Error) => {
if (error) {
span.recordException(error)
}
span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message })
span.end()
}
type TracerSpanOptions = SpanOptions & {
parentSpan?: Span
tracerName?: string
spanName?: string
}
interface NextTracer {
......@@ -52,22 +55,22 @@ interface NextTracer {
*
*/
trace<T>(
name: SpanNames,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T>
type: SpanTypes,
fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T>
trace<T>(
name: SpanNames,
fn: (span: Span, done?: (error?: Error) => any) => T
type: SpanTypes,
fn: (span?: Span, done?: (error?: Error) => any) => T
): T
trace<T>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T>
fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T>
trace<T>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => T
fn: (span?: Span, done?: (error?: Error) => any) => T
): T
/**
......@@ -84,14 +87,14 @@ interface NextTracer {
* * 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.
*/
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>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: T
): T
wrap<T = (...args: Array<any>) => any>(
name: SpanNames,
type: SpanTypes,
options: (...args: any[]) => TracerSpanOptions,
fn: T
): T
......@@ -104,8 +107,8 @@ interface NextTracer {
* 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)
*/
startSpan(name: SpanNames): Span
startSpan(name: SpanNames, options: TracerSpanOptions): Span
startSpan(type: SpanTypes): Span
startSpan(type: SpanTypes, options: TracerSpanOptions): Span
/**
* Returns currently activated span if current context is in the scope of the span.
......@@ -135,25 +138,25 @@ class NextTracerImpl implements NextTracer {
// Trace, wrap implementation is inspired by datadog trace implementation
// (https://datadoghq.dev/dd-trace-js/interfaces/tracer.html#trace).
public trace<T>(
name: SpanNames,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T>
type: SpanTypes,
fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T>
public trace<T>(
name: SpanNames,
fn: (span: Span, done?: (error?: Error) => any) => T
type: SpanTypes,
fn: (span?: Span, done?: (error?: Error) => any) => T
): T
public trace<T>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => Promise<T>
fn: (span?: Span, done?: (error?: Error) => any) => Promise<T>
): Promise<T>
public trace<T>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: (span: Span, done?: (error?: Error) => any) => T
fn: (span?: Span, done?: (error?: Error) => any) => T
): T
public trace<T>(...args: Array<any>) {
const [name, fnOrOptions, fnOrEmpty] = args
const [type, fnOrOptions, fnOrEmpty] = args
// coerce options form overload
const {
......@@ -170,30 +173,38 @@ class NextTracerImpl implements NextTracer {
}
: {
fn: fnOrEmpty,
options: fnOrOptions,
options: { ...fnOrOptions },
}
if (
!NextVanillaSpanAllowlist.includes(name) &&
!NextVanillaSpanAllowlist.includes(type) &&
process.env.NEXT_OTEL_VERBOSE !== '1'
) {
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.
const spanContext = this.getSpanContext(
options?.parentSpan ?? this.getActiveScopeSpan()
)
options.attributes = {
'next.span_name': spanName,
'next.span_type': type,
...options.attributes,
}
const runWithContext = (actualFn: (span: Span) => T | Promise<T>) =>
spanContext
? this.getTracerInstance().startActiveSpan(
name,
spanName,
options,
spanContext,
actualFn
)
: this.getTracerInstance().startActiveSpan(name, options, actualFn)
: this.getTracerInstance().startActiveSpan(spanName, options, actualFn)
return runWithContext((span: Span) => {
try {
......@@ -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>(
name: SpanNames,
type: SpanTypes,
options: TracerSpanOptions,
fn: T
): T
public wrap<T = (...args: Array<any>) => any>(
name: SpanNames,
type: SpanTypes,
options: (...args: any[]) => TracerSpanOptions,
fn: T
): T
......@@ -268,15 +279,15 @@ class NextTracerImpl implements NextTracer {
}
}
public startSpan(name: SpanNames): Span
public startSpan(name: SpanNames, options: TracerSpanOptions): Span
public startSpan(type: SpanTypes): Span
public startSpan(type: SpanTypes, options: TracerSpanOptions): 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(
options?.parentSpan ?? this.getActiveScopeSpan()
)
return this.getTracerInstance().startSpan(name, options, spanContext)
return this.getTracerInstance().startSpan(type, options, spanContext)
}
private getSpanContext(parentSpan?: Span) {
......
......@@ -958,8 +958,15 @@ export default class NextNodeServer extends BaseServer {
params: Params | null
isAppPath: boolean
}): Promise<FindComponentsResult | null> {
return getTracer().trace(NextNodeServerSpan.findPageComponents, () =>
this.findPageComponentsImpl({ pathname, query, params, isAppPath })
return getTracer().trace(
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(
}
try {
data = await getTracer().trace(RenderSpan.getServerSideProps, async () =>
getServerSideProps({
req: req as IncomingMessage & {
cookies: NextApiRequestCookies
},
res: resOrProxy,
query,
resolvedUrl: renderOpts.resolvedUrl as string,
...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined),
...(previewData !== false
? { preview: true, previewData: previewData }
: undefined),
locales: renderOpts.locales,
locale: renderOpts.locale,
defaultLocale: renderOpts.defaultLocale,
})
data = await getTracer().trace(
RenderSpan.getServerSideProps,
{
spanName: `getServerSideProps ${pathname}`,
},
async () =>
getServerSideProps({
req: req as IncomingMessage & {
cookies: NextApiRequestCookies
},
res: resOrProxy,
query,
resolvedUrl: renderOpts.resolvedUrl as string,
...(pageIsDynamic
? { params: params as ParsedUrlQuery }
: undefined),
...(previewData !== false
? { preview: true, previewData: previewData }
: undefined),
locales: renderOpts.locales,
locale: renderOpts.locale,
defaultLocale: renderOpts.defaultLocale,
})
)
canAccessRes = false
} catch (serverSidePropsError: any) {
......
......@@ -2,6 +2,6 @@
export const dynamic = 'force-dynamic'
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>
}
......@@ -3,16 +3,16 @@ import { SpanKind } from '@opentelemetry/api'
export const traceFile = 'otel-trace.txt'
export type SavedSpan = {
traceId: string
traceId?: string
parentId?: string
traceState: any
name: string
id: string
kind: SpanKind
timestamp: number
duration: number
attributes: Record<string, any>
status: any
events: any[]
links: any[]
traceState?: any
name?: string
id?: string
kind?: SpanKind
timestamp?: number
duration?: number
attributes?: Record<string, any>
status?: any
events?: any[]
links?: any[]
}
export default async function Page() {
export default function Page() {
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