Unverified Commit 491f7809 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix Request Insights span collection (#95818)

## Summary

Fix Request Insights collection so the dev server records all non-hidden
Next.js spans locally, including non-vanilla trace and wrapped spans,
while preserving the existing OpenTelemetry export allowlist unless
verbose tracing is enabled.

Keep reporting timelines correct by propagating request identity before
work async storage exists, honoring explicit span timestamps, and
anchoring request duration to the BaseServer request span. Standardize
span categories on `next.span_category`, retain presentation-only UI
filtering, and filter internal request identity headers at ingress.

## Verification

- `pnpm test-dev-turbo
test/development/app-dir/request-insights/request-insights.test.ts`

<!-- NEXT_JS_LLM -->
parent 3baea357
...@@ -98,7 +98,7 @@ describe('request insights trace viewer', () => { ...@@ -98,7 +98,7 @@ describe('request insights trace viewer', () => {
]) ])
}) })
it('shows high-level spans by default and reveals hidden spans in verbose mode', () => { it('filters collected spans for presentation without changing collection', () => {
const request = createRequest({ const request = createRequest({
spans: [ spans: [
{ {
...@@ -335,7 +335,7 @@ describe('request insights trace viewer', () => { ...@@ -335,7 +335,7 @@ describe('request insights trace viewer', () => {
startTime: 100, startTime: 100,
durationMs: 10, durationMs: 10,
attributes: { attributes: {
'next.span.category': 'nextjs', 'next.span_category': 'nextjs',
'next.span_type': 'BaseServer.render', 'next.span_type': 'BaseServer.render',
}, },
}, },
...@@ -344,7 +344,7 @@ describe('request insights trace viewer', () => { ...@@ -344,7 +344,7 @@ describe('request insights trace viewer', () => {
startTime: 110, startTime: 110,
durationMs: 10, durationMs: 10,
attributes: { attributes: {
'next.span.category': 'application', 'next.span_category': 'application',
'next.span_type': 'ResolveMetadata.generateMetadata', 'next.span_type': 'ResolveMetadata.generateMetadata',
}, },
}, },
...@@ -384,7 +384,7 @@ describe('request insights trace viewer', () => { ...@@ -384,7 +384,7 @@ describe('request insights trace viewer', () => {
startTime: 120, startTime: 120,
durationMs: 30, durationMs: 30,
attributes: { attributes: {
'next.span.category': 'application', 'next.span_category': 'application',
'next.span_type': 'AppRender.fetch', 'next.span_type': 'AppRender.fetch',
'next.fetch.idx': 1, 'next.fetch.idx': 1,
}, },
...@@ -396,7 +396,7 @@ describe('request insights trace viewer', () => { ...@@ -396,7 +396,7 @@ describe('request insights trace viewer', () => {
startTime: 155, startTime: 155,
durationMs: 10, durationMs: 10,
attributes: { attributes: {
'next.span.category': 'nextjs', 'next.span_category': 'nextjs',
'next.span_type': 'AppRender.fetch', 'next.span_type': 'AppRender.fetch',
'next.fetch.idx': 2, 'next.fetch.idx': 2,
}, },
......
...@@ -323,7 +323,7 @@ function getFetchIndex(span: RequestInsightSpan): number | undefined { ...@@ -323,7 +323,7 @@ function getFetchIndex(span: RequestInsightSpan): number | undefined {
} }
function getSpanCategory(span: RequestInsightSpan): 'nextjs' | 'application' { function getSpanCategory(span: RequestInsightSpan): 'nextjs' | 'application' {
const category = span.attributes?.['next.span.category'] const category = span.attributes?.['next.span_category']
if (category === 'nextjs' || category === 'application') { if (category === 'nextjs' || category === 'application') {
return category return category
} }
......
...@@ -96,6 +96,7 @@ import { ...@@ -96,6 +96,7 @@ import {
import { isRedirectError } from '../../client/components/redirect-error' import { isRedirectError } from '../../client/components/redirect-error'
import { getImplicitTags, type ImplicitTags } from '../lib/implicit-tags' import { getImplicitTags, type ImplicitTags } from '../lib/implicit-tags'
import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants' import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants'
import { getRequestInsightsIdentity } from '../lib/trace/request-insights-identity'
import { getTracer, SpanStatusCode } from '../lib/trace/tracer' import { getTracer, SpanStatusCode } from '../lib/trace/tracer'
import { FlightRenderResult } from './flight-render-result' import { FlightRenderResult } from './flight-render-result'
import { import {
...@@ -2674,6 +2675,9 @@ async function renderToHTMLOrFlightImpl( ...@@ -2674,6 +2675,9 @@ async function renderToHTMLOrFlightImpl(
let requestId: string let requestId: string
let htmlRequestId: string let htmlRequestId: string
const requestInsightsIdentity = process.env.__NEXT_REQUEST_INSIGHTS
? getRequestInsightsIdentity()
: undefined
const { const {
flightRouterState, flightRouterState,
...@@ -2688,6 +2692,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -2688,6 +2692,10 @@ async function renderToHTMLOrFlightImpl(
if (parsedRequestHeaders.requestId) { if (parsedRequestHeaders.requestId) {
// If the client has provided a request ID (in development mode), we use it. // If the client has provided a request ID (in development mode), we use it.
requestId = parsedRequestHeaders.requestId requestId = parsedRequestHeaders.requestId
} else if (requestInsightsIdentity) {
// Request Insights starts recording before the work store exists. Reuse
// the identity from that outer request scope so all spans stay together.
requestId = requestInsightsIdentity.requestId
} else { } else {
// Otherwise we generate a new request ID. // Otherwise we generate a new request ID.
if (isStaticGeneration) { if (isStaticGeneration) {
...@@ -2708,7 +2716,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -2708,7 +2716,10 @@ async function renderToHTMLOrFlightImpl(
// send debug information to the associated WebSocket client. Otherwise, this // send debug information to the associated WebSocket client. Otherwise, this
// is the request for the HTML document, so we use the request ID also as the // is the request for the HTML document, so we use the request ID also as the
// HTML request ID. // HTML request ID.
htmlRequestId = parsedRequestHeaders.htmlRequestId || requestId htmlRequestId =
parsedRequestHeaders.htmlRequestId ||
requestInsightsIdentity?.htmlRequestId ||
requestId
workStore.requestId = requestId workStore.requestId = requestId
workStore.htmlRequestId = htmlRequestId workStore.htmlRequestId = htmlRequestId
......
...@@ -84,6 +84,8 @@ import { ...@@ -84,6 +84,8 @@ import {
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { import {
RSC_HEADER, RSC_HEADER,
NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER,
NEXT_RSC_UNION_QUERY, NEXT_RSC_UNION_QUERY,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
...@@ -92,6 +94,7 @@ import { ...@@ -92,6 +94,7 @@ import {
NEXT_INSTANT_TEST_COOKIE, NEXT_INSTANT_TEST_COOKIE,
NEXT_HMR_REFRESH_HEADER, NEXT_HMR_REFRESH_HEADER,
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import { nanoid } from 'next/dist/compiled/nanoid'
import type { import type {
MatchOptions, MatchOptions,
RouteMatcherManager, RouteMatcherManager,
...@@ -110,6 +113,8 @@ import { ...@@ -110,6 +113,8 @@ import {
SpanStatusCode, SpanStatusCode,
} from './lib/trace/tracer' } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants' import { BaseServerSpan } from './lib/trace/constants'
import { runWithRequestInsightsIdentity } from './lib/trace/request-insights-identity'
import { isRequestInsightsEnabled } from './lib/trace/span-store'
import { I18NProvider } from './lib/i18n-provider' import { I18NProvider } from './lib/i18n-provider'
import { sendResponse } from './send-response' import { sendResponse } from './send-response'
import { normalizeNextQueryParam } from './web/utils' import { normalizeNextQueryParam } from './web/utils'
...@@ -902,86 +907,111 @@ export default abstract class Server< ...@@ -902,86 +907,111 @@ export default abstract class Server<
const method = req.method.toUpperCase() const method = req.method.toUpperCase()
const tracer = getTracer() const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () => { const handleRequest = () =>
// Capture the parent span before creating the handleRequest span. tracer.withPropagatedContext(req.headers, () => {
// When deployed with an adapter, the platform's runtime may create its // Capture the parent span before creating the handleRequest span.
// own OTEL HTTP server span before Next.js runs. We propagate http.route // When deployed with an adapter, the platform's runtime may create its
// to this parent span so APM tools (e.g. Datadog) can derive the // own OTEL HTTP server span before Next.js runs. We propagate http.route
// resource name correctly. // to this parent span so APM tools (e.g. Datadog) can derive the
const parentSpan = tracer.getActiveScopeSpan() // resource name correctly.
const parentSpan = tracer.getActiveScopeSpan()
return tracer.trace(
BaseServerSpan.handleRequest, return tracer.trace(
{ BaseServerSpan.handleRequest,
spanName: `${method}`, {
kind: SpanKind.SERVER, spanName: `${method}`,
attributes: { kind: SpanKind.SERVER,
'http.method': method, attributes: {
'http.target': req.url, 'http.method': method,
'http.target': req.url,
},
}, },
}, async (span) =>
async (span) => this.handleRequestImpl(req, res, parsedUrl).finally(() => {
this.handleRequestImpl(req, res, parsedUrl).finally(() => { if (!span) return
if (!span) return
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': isRSCRequest,
})
if (res.statusCode && res.statusCode >= 500) { const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
// For 5xx status codes: SHOULD be set to 'Error' span status. span.setAttributes({
// x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status 'http.status_code': res.statusCode,
span.setStatus({ 'next.rsc': isRSCRequest,
code: SpanStatusCode.ERROR,
}) })
// For span status 'Error', SHOULD set 'error.type' attribute.
span.setAttribute('error.type', res.statusCode.toString())
}
const rootSpanAttributes = tracer.getRootSpanAttributes() if (res.statusCode && res.statusCode >= 500) {
// We were unable to get attributes, probably OTEL is not enabled // For 5xx status codes: SHOULD be set to 'Error' span status.
if (!rootSpanAttributes) return // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
span.setStatus({
code: SpanStatusCode.ERROR,
})
// For span status 'Error', SHOULD set 'error.type' attribute.
span.setAttribute('error.type', res.statusCode.toString())
}
if ( const rootSpanAttributes = tracer.getRootSpanAttributes()
rootSpanAttributes.get('next.span_type') !== // We were unable to get attributes, probably OTEL is not enabled
BaseServerSpan.handleRequest if (!rootSpanAttributes) return
) {
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 (
if (route) { rootSpanAttributes.get('next.span_type') !==
const name = isRSCRequest BaseServerSpan.handleRequest
? `RSC ${method} ${route}` ) {
: `${method} ${route}` console.warn(
`Unexpected root span type '${rootSpanAttributes.get(
'next.span_type'
)}'. Please report this Next.js issue https://github.com/vercel/next.js`
)
return
}
span.setAttributes({ const route = rootSpanAttributes.get('next.route')
'next.route': route, if (route) {
'http.route': route, const name = isRSCRequest
'next.span_name': name, ? `RSC ${method} ${route}`
}) : `${method} ${route}`
span.updateName(name)
span.setAttributes({
// Propagate http.route to the parent span if one exists and 'next.route': route,
// is different from the handleRequest span. This ensures APM 'http.route': route,
// tools that read attributes from the outermost span (e.g. 'next.span_name': name,
// a platform-created HTTP span) can derive the resource name. })
if (parentSpan && parentSpan !== span) { span.updateName(name)
parentSpan.setAttribute('http.route', route)
// Propagate http.route to the parent span if one exists and
// is different from the handleRequest span. This ensures APM
// tools that read attributes from the outermost span (e.g.
// a platform-created HTTP span) can derive the resource name.
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else {
span.updateName(isRSCRequest ? `RSC ${method}` : `${method}`)
} }
} else { })
span.updateName(isRSCRequest ? `RSC ${method}` : `${method}`) )
} })
})
) if (!isRequestInsightsEnabled()) {
}) return handleRequest()
}
const requestIdHeader = req.headers[NEXT_REQUEST_ID_HEADER]
const requestId =
typeof requestIdHeader === 'string' ? requestIdHeader : nanoid()
const htmlRequestIdHeader = req.headers[NEXT_HTML_REQUEST_ID_HEADER]
// The request root and route-matching spans start before App Render creates
// its workStore. Carry their identity in this outer scope; App Render copies
// it into the workStore so the complete timeline uses one request ID.
return runWithRequestInsightsIdentity(
{
requestId,
htmlRequestId:
typeof htmlRequestIdHeader === 'string'
? htmlRequestIdHeader
: requestId,
url: req.url,
},
handleRequest
)
} }
private async handleRequestImpl( private async handleRequestImpl(
......
...@@ -6,6 +6,7 @@ import { runInNewContext } from 'node:vm' ...@@ -6,6 +6,7 @@ import { runInNewContext } from 'node:vm'
import { setFlagsFromString } from 'node:v8' import { setFlagsFromString } from 'node:v8'
import { SpanStatusCode, trace } from 'next/dist/compiled/@opentelemetry/api' import { SpanStatusCode, trace } from 'next/dist/compiled/@opentelemetry/api'
import { createLocalSpan } from './local-span-recorder' import { createLocalSpan } from './local-span-recorder'
import { runWithRequestInsightsIdentity } from './request-insights-identity'
import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store' import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store'
const originalDevServer = process.env.__NEXT_DEV_SERVER const originalDevServer = process.env.__NEXT_DEV_SERVER
...@@ -119,6 +120,47 @@ describe('local recording span', () => { ...@@ -119,6 +120,47 @@ describe('local recording span', () => {
]) ])
}) })
it('uses the request insights identity before the work store exists', () => {
runWithRequestInsightsIdentity(
{
requestId: 'request-1',
htmlRequestId: 'html-1',
url: '/dashboard?tab=overview',
},
() => {
const span = createLocalSpan({ name: 'test.request-root' })
span.end()
}
)
expect(spanRecords).toEqual([
expect.objectContaining({
name: 'test.request-root',
requestId: 'request-1',
htmlRequestId: 'html-1',
url: '/dashboard?tab=overview',
}),
])
})
it('records explicit performance timestamps', () => {
const startTime = performance.now() - 10
const span = createLocalSpan({
name: 'test.local-span.explicit-time',
startTime,
})
span.end(startTime + 0.2)
expect(spanRecords).toEqual([
expect.objectContaining({
name: 'test.local-span.explicit-time',
startTime: performance.timeOrigin + startTime,
durationMs: expect.closeTo(0.2, 3),
}),
])
})
it('releases heavy references after ending while the span remains reachable', async () => { it('releases heavy references after ending while the span remains reachable', async () => {
const { span, delegateRef, attributeRef } = createEndedSpanWithReferences() const { span, delegateRef, attributeRef } = createEndedSpanWithReferences()
......
...@@ -7,6 +7,7 @@ import type { AsyncLocalStorage } from 'async_hooks' ...@@ -7,6 +7,7 @@ import type { AsyncLocalStorage } from 'async_hooks'
import { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api' import { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'
import { import {
isLocalSpanRecordingEnabled, isLocalSpanRecordingEnabled,
isRequestInsightsEnabled,
recordSpan, recordSpan,
type SpanStoreAttributes, type SpanStoreAttributes,
type SpanStoreEvent, type SpanStoreEvent,
...@@ -34,6 +35,7 @@ export function createLocalSpan({ ...@@ -34,6 +35,7 @@ export function createLocalSpan({
name, name,
attributes, attributes,
links, links,
startTime,
traceId, traceId,
spanId, spanId,
parentSpanId, parentSpanId,
...@@ -42,6 +44,7 @@ export function createLocalSpan({ ...@@ -42,6 +44,7 @@ export function createLocalSpan({
name: string name: string
attributes?: LocalSpanAttributes attributes?: LocalSpanAttributes
links?: SpanOptions['links'] links?: SpanOptions['links']
startTime?: SpanOptions['startTime']
traceId?: string traceId?: string
spanId?: string spanId?: string
parentSpanId?: string parentSpanId?: string
...@@ -51,6 +54,7 @@ export function createLocalSpan({ ...@@ -51,6 +54,7 @@ export function createLocalSpan({
name, name,
attributes, attributes,
links, links,
startTime,
delegateSpan, delegateSpan,
traceId: traceId ?? getLocalTraceId(), traceId: traceId ?? getLocalTraceId(),
spanId: spanId ?? getLocalSpanId(), spanId: spanId ?? getLocalSpanId(),
...@@ -76,6 +80,7 @@ export type LocalSpanRecorder = { ...@@ -76,6 +80,7 @@ export type LocalSpanRecorder = {
getActiveLocalSpan: typeof getActiveLocalSpan getActiveLocalSpan: typeof getActiveLocalSpan
isLocalRecordingSpan: typeof isLocalRecordingSpan isLocalRecordingSpan: typeof isLocalRecordingSpan
isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled
isRequestInsightsEnabled: typeof isRequestInsightsEnabled
withLocalSpan: typeof withLocalSpan withLocalSpan: typeof withLocalSpan
} }
...@@ -90,6 +95,7 @@ export function registerLocalSpanRecorder(): void { ...@@ -90,6 +95,7 @@ export function registerLocalSpanRecorder(): void {
getActiveLocalSpan, getActiveLocalSpan,
isLocalRecordingSpan, isLocalRecordingSpan,
isLocalSpanRecordingEnabled, isLocalSpanRecordingEnabled,
isRequestInsightsEnabled,
withLocalSpan, withLocalSpan,
} }
} }
...@@ -122,7 +128,6 @@ class LocalRecordingSpan implements Span { ...@@ -122,7 +128,6 @@ class LocalRecordingSpan implements Span {
private readonly parentSpanId?: string private readonly parentSpanId?: string
private requestIdentity: RequestIdentity private requestIdentity: RequestIdentity
private readonly startTime: number private readonly startTime: number
private readonly startTimeMs: number
private statusCode: number | undefined private statusCode: number | undefined
private statusMessage: string | undefined private statusMessage: string | undefined
private exception: private exception:
...@@ -137,6 +142,7 @@ class LocalRecordingSpan implements Span { ...@@ -137,6 +142,7 @@ class LocalRecordingSpan implements Span {
name, name,
attributes, attributes,
links, links,
startTime,
delegateSpan, delegateSpan,
traceId, traceId,
spanId, spanId,
...@@ -146,6 +152,7 @@ class LocalRecordingSpan implements Span { ...@@ -146,6 +152,7 @@ class LocalRecordingSpan implements Span {
name: string name: string
attributes?: LocalSpanAttributes attributes?: LocalSpanAttributes
links?: SpanOptions['links'] links?: SpanOptions['links']
startTime?: SpanOptions['startTime']
delegateSpan?: Span delegateSpan?: Span
traceId: string traceId: string
spanId: string spanId: string
...@@ -164,8 +171,7 @@ class LocalRecordingSpan implements Span { ...@@ -164,8 +171,7 @@ class LocalRecordingSpan implements Span {
this.links = getSpanStoreLinks(links) this.links = getSpanStoreLinks(links)
this.parentSpanId = parentSpanId this.parentSpanId = parentSpanId
this.requestIdentity = requestIdentity this.requestIdentity = requestIdentity
this.startTime = Date.now() this.startTime = getTimestamp(startTime)
this.startTimeMs = getCurrentTimeMs()
this.statusCode = undefined this.statusCode = undefined
this.statusMessage = undefined this.statusMessage = undefined
this.exception = undefined this.exception = undefined
...@@ -254,7 +260,7 @@ class LocalRecordingSpan implements Span { ...@@ -254,7 +260,7 @@ class LocalRecordingSpan implements Span {
this.delegateSpan?.end(endTime) this.delegateSpan?.end(endTime)
} finally { } finally {
try { try {
this.record() this.record(endTime)
} finally { } finally {
this.releaseReferences() this.releaseReferences()
} }
...@@ -282,14 +288,14 @@ class LocalRecordingSpan implements Span { ...@@ -282,14 +288,14 @@ class LocalRecordingSpan implements Span {
this.delegateSpan?.recordException(exception, time) this.delegateSpan?.recordException(exception, time)
} }
private record(): void { private record(endTime: Parameters<Span['end']>[0]): void {
const recordAttributes = const recordAttributes =
Object.keys(this.attributes).length > 0 ? this.attributes : undefined Object.keys(this.attributes).length > 0 ? this.attributes : undefined
recordSpan({ recordSpan({
name: this.name, name: this.name,
startTime: this.startTime, startTime: this.startTime,
durationMs: getCurrentTimeMs() - this.startTimeMs, durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),
status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok', status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',
traceId: this.spanContextValue.traceId, traceId: this.spanContextValue.traceId,
spanId: this.spanContextValue.spanId, spanId: this.spanContextValue.spanId,
...@@ -374,8 +380,31 @@ function cleanSpanStoreAttributes( ...@@ -374,8 +380,31 @@ function cleanSpanStoreAttributes(
return cleanedAttributes return cleanedAttributes
} }
function getCurrentTimeMs(): number { function getTimestamp(time?: SpanOptions['startTime']): number {
return typeof performance !== 'undefined' ? performance.now() : Date.now() if (time instanceof Date) {
return time.getTime()
}
if (Array.isArray(time)) {
return time[0] * 1000 + time[1] / 1_000_000
}
if (typeof time === 'number') {
const timeOrigin = getPerformanceTimeOrigin()
return timeOrigin !== undefined && time < timeOrigin
? timeOrigin + time
: time
}
const timeOrigin = getPerformanceTimeOrigin()
return timeOrigin === undefined ? Date.now() : timeOrigin + performance.now()
}
function getPerformanceTimeOrigin(): number | undefined {
return typeof performance !== 'undefined' &&
typeof performance.timeOrigin === 'number'
? performance.timeOrigin
: undefined
} }
function getStringAttribute( function getStringAttribute(
...@@ -452,20 +481,24 @@ function getSpanStoreExceptionAttributes( ...@@ -452,20 +481,24 @@ function getSpanStoreExceptionAttributes(
function getCurrentRequestIdentity(): RequestIdentity { function getCurrentRequestIdentity(): RequestIdentity {
try { try {
const { getRequestInsightsIdentity } =
require('./request-insights-identity') as typeof import('./request-insights-identity')
const { workAsyncStorage } = const { workAsyncStorage } =
require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external') require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')
const { workUnitAsyncStorage } = const { workUnitAsyncStorage } =
require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external') require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const requestInsightsIdentity = getRequestInsightsIdentity()
const url = const url =
workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined
return { return {
requestId: workStore?.requestId, requestId: workStore?.requestId ?? requestInsightsIdentity?.requestId,
htmlRequestId: workStore?.htmlRequestId, htmlRequestId:
workStore?.htmlRequestId ?? requestInsightsIdentity?.htmlRequestId,
route: workStore?.route, route: workStore?.route,
url: url ? `${url.pathname}${url.search}` : undefined, url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,
} }
} catch { } catch {
return {} return {}
......
import type { AsyncLocalStorage } from 'async_hooks'
import { createAsyncLocalStorage } from '../../app-render/async-local-storage'
export type RequestInsightsIdentity = {
requestId: string
htmlRequestId: string
url: string | undefined
}
// This storage covers the part of BaseServer request handling that runs before
// App Render creates workAsyncStorage. Once available, workStore remains the
// primary identity source for locally recorded spans.
const REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(
'@next/request-insights-identity-storage'
)
function getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {
const globalStore = globalThis as typeof globalThis & {
[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>
}
return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=
createAsyncLocalStorage())
}
export function runWithRequestInsightsIdentity<T>(
identity: RequestInsightsIdentity,
fn: () => T
): T {
return getRequestInsightsIdentityStorage().run(identity, fn)
}
export function getRequestInsightsIdentity():
| RequestInsightsIdentity
| undefined {
return getRequestInsightsIdentityStorage().getStore()
}
...@@ -42,6 +42,7 @@ describe('request insights', () => { ...@@ -42,6 +42,7 @@ describe('request insights', () => {
htmlRequestId: 'html_1', htmlRequestId: 'html_1',
route: '/products/[id]', route: '/products/[id]',
attributes: { attributes: {
'next.span_category': 'nextjs',
'next.span_type': 'AppRender.getBodyResult', 'next.span_type': 'AppRender.getBodyResult',
}, },
events: [ events: [
...@@ -67,6 +68,7 @@ describe('request insights', () => { ...@@ -67,6 +68,7 @@ describe('request insights', () => {
htmlRequestId: 'html_1', htmlRequestId: 'html_1',
route: '/products/[id]', route: '/products/[id]',
attributes: { attributes: {
'next.span_category': 'application',
'next.span_type': 'AppRender.fetch', 'next.span_type': 'AppRender.fetch',
'http.url': 'https://example.vercel.sh/', 'http.url': 'https://example.vercel.sh/',
'http.method': 'GET', 'http.method': 'GET',
...@@ -88,10 +90,16 @@ describe('request insights', () => { ...@@ -88,10 +90,16 @@ describe('request insights', () => {
spans: expect.arrayContaining([ spans: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
name: 'fetch GET https://example.vercel.sh/', name: 'fetch GET https://example.vercel.sh/',
attributes: expect.objectContaining({
'next.span_category': 'application',
}),
}), }),
expect.objectContaining({ expect.objectContaining({
traceId: 'trace_1', traceId: 'trace_1',
spanId: 'span_1', spanId: 'span_1',
attributes: expect.objectContaining({
'next.span_category': 'nextjs',
}),
events: [ events: [
{ {
name: 'metadata ready', name: 'metadata ready',
...@@ -146,6 +154,53 @@ describe('request insights', () => { ...@@ -146,6 +154,53 @@ describe('request insights', () => {
unsubscribe() unsubscribe()
}) })
it('uses the HTTP request span as the end-to-end request timing', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
recordSpan({
name: 'render route (app) /dashboard',
requestId: 'req_timing',
startTime: 100,
durationMs: 60,
})
recordSpan({
name: 'GET /dashboard',
requestId: 'req_timing',
startTime: 100,
durationMs: 50,
attributes: {
'next.span_type': 'BaseServer.handleRequest',
},
})
recordRequestInsightFetch(
{ requestId: 'req_timing' },
{ url: 'https://example.com/late', startTime: 145, durationMs: 20 }
)
expect(getRequestInsightsSnapshot().requests[0]).toEqual(
expect.objectContaining({
startTime: 100,
durationMs: 50,
})
)
})
it('does not treat aggregate client component loading as a trace span', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
recordSpan({
name: 'NextNodeServer.clientComponentLoading',
requestId: 'req_client_loading',
startTime: 100,
durationMs: 50,
attributes: {
'next.span_type': 'NextNodeServer.clientComponentLoading',
},
})
expect(getRequestInsightsSnapshot().requests).toEqual([])
})
it('records request fetch metrics when the OTel fetch span does not complete locally', () => { it('records request fetch metrics when the OTel fetch span does not complete locally', () => {
recordRequestInsightFetch( recordRequestInsightFetch(
{ {
......
...@@ -9,6 +9,8 @@ export { isRequestInsightsEnabled } from './span-store' ...@@ -9,6 +9,8 @@ export { isRequestInsightsEnabled } from './span-store'
const MAX_REQUEST_INSIGHTS = 100 const MAX_REQUEST_INSIGHTS = 100
const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store') const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')
const CLIENT_COMPONENT_LOADING_SPAN_TYPE =
'NextNodeServer.clientComponentLoading'
type RequestInsightsListener = (insight: RequestInsight) => void type RequestInsightsListener = (insight: RequestInsight) => void
type RequestInsightIdentity = { type RequestInsightIdentity = {
...@@ -32,6 +34,7 @@ const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([ ...@@ -32,6 +34,7 @@ const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([
'next.route', 'next.route',
'next.rsc', 'next.rsc',
'next.segment', 'next.segment',
'next.span_category',
'next.span_name', 'next.span_name',
'next.span_type', 'next.span_type',
]) ])
...@@ -40,6 +43,10 @@ const SENSITIVE_PARAM_NAME_RE = ...@@ -40,6 +43,10 @@ const SENSITIVE_PARAM_NAME_RE =
class InMemoryRequestInsightsStore { class InMemoryRequestInsightsStore {
private readonly requests = new Map<string, RequestInsight>() private readonly requests = new Map<string, RequestInsight>()
private readonly requestTimings = new Map<
string,
{ startTime: number; durationMs: number }
>()
private readonly requestOrder: string[] = [] private readonly requestOrder: string[] = []
private readonly listeners = new Set<RequestInsightsListener>() private readonly listeners = new Set<RequestInsightsListener>()
...@@ -54,19 +61,15 @@ class InMemoryRequestInsightsStore { ...@@ -54,19 +61,15 @@ class InMemoryRequestInsightsStore {
) )
const spanStartTime = span.startTime ?? span.timestamp const spanStartTime = span.startTime ?? span.timestamp
const spanEndTime = span.durationMs
? spanStartTime + span.durationMs
: spanStartTime
const requestEndTime = insight.durationMs
? insight.startTime + insight.durationMs
: insight.startTime
insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId
insight.route = insight.route ?? span.route insight.route = insight.route ?? span.route
insight.url = insight.url ?? sanitizeUrl(span.url) insight.url = insight.url ?? sanitizeUrl(span.url)
insight.startTime = Math.min(insight.startTime, spanStartTime) this.updateTiming(
insight.durationMs = insight,
Math.max(requestEndTime, spanEndTime) - insight.startTime spanStartTime,
span.durationMs,
span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'
)
insight.status = insight.status =
insight.status === 'error' || span.status === 'error' insight.status === 'error' || span.status === 'error'
? 'error' ? 'error'
...@@ -103,15 +106,7 @@ class InMemoryRequestInsightsStore { ...@@ -103,15 +106,7 @@ class InMemoryRequestInsightsStore {
const fetchStartTime = fetch.startTime ?? Date.now() const fetchStartTime = fetch.startTime ?? Date.now()
const insight = this.getOrCreateRequest(identity, fetchStartTime) const insight = this.getOrCreateRequest(identity, fetchStartTime)
const fetchEndTime = fetch.durationMs this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)
? fetchStartTime + fetch.durationMs
: fetchStartTime
const requestEndTime = insight.durationMs
? insight.startTime + insight.durationMs
: insight.startTime
insight.durationMs =
Math.max(requestEndTime, fetchEndTime) - insight.startTime
this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch)) this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))
this.notify(insight) this.notify(insight)
} }
...@@ -133,9 +128,37 @@ class InMemoryRequestInsightsStore { ...@@ -133,9 +128,37 @@ class InMemoryRequestInsightsStore {
clear(): void { clear(): void {
this.requests.clear() this.requests.clear()
this.requestTimings.clear()
this.requestOrder.length = 0 this.requestOrder.length = 0
} }
private updateTiming(
insight: RequestInsight,
startTime: number,
durationMs: number | undefined,
isRequestSpan: boolean
): void {
if (isRequestSpan && durationMs !== undefined) {
const requestTiming = { startTime, durationMs }
this.requestTimings.set(insight.requestId, requestTiming)
insight.startTime = requestTiming.startTime
insight.durationMs = requestTiming.durationMs
return
}
const requestTiming = this.requestTimings.get(insight.requestId)
if (requestTiming) {
insight.startTime = requestTiming.startTime
insight.durationMs = requestTiming.durationMs
return
}
const endTime = startTime + (durationMs ?? 0)
const requestEndTime = insight.startTime + (insight.durationMs ?? 0)
insight.startTime = Math.min(insight.startTime, startTime)
insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime
}
private notify(insight: RequestInsight): void { private notify(insight: RequestInsight): void {
for (const listener of this.listeners) { for (const listener of this.listeners) {
listener(insight) listener(insight)
...@@ -197,12 +220,19 @@ class InMemoryRequestInsightsStore { ...@@ -197,12 +220,19 @@ class InMemoryRequestInsightsStore {
const requestId = this.requestOrder.shift() const requestId = this.requestOrder.shift()
if (requestId) { if (requestId) {
this.requests.delete(requestId) this.requests.delete(requestId)
this.requestTimings.delete(requestId)
} }
} }
} }
} }
export function recordRequestInsightSpan(span: SpanStoreRecord): void { export function recordRequestInsightSpan(span: SpanStoreRecord): void {
if (
span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE
) {
return
}
getRequestInsightsStore().recordSpan(span) getRequestInsightsStore().recordSpan(span)
} }
......
...@@ -96,6 +96,7 @@ describe('span recording', () => { ...@@ -96,6 +96,7 @@ describe('span recording', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true' process.env.__NEXT_REQUEST_INSIGHTS = 'true'
setSpanRecorderForTest(recorder) setSpanRecorderForTest(recorder)
expect(isRequestInsightsEnabled()).toBe(false)
expect(isLocalSpanRecordingEnabled()).toBe(false) expect(isLocalSpanRecordingEnabled()).toBe(false)
recordSpan({ name: 'test.production', requestId: 'req_2' }) recordSpan({ name: 'test.production', requestId: 'req_2' })
......
...@@ -74,6 +74,10 @@ export function isLocalSpanRecordingEnabled(): boolean { ...@@ -74,6 +74,10 @@ export function isLocalSpanRecordingEnabled(): boolean {
} }
export function isRequestInsightsEnabled(): boolean { export function isRequestInsightsEnabled(): boolean {
if (!process.env.__NEXT_DEV_SERVER) {
return false
}
const value = process.env.__NEXT_REQUEST_INSIGHTS const value = process.env.__NEXT_REQUEST_INSIGHTS
return isEnabledEnvValue(value) return isEnabledEnvValue(value)
} }
......
...@@ -20,12 +20,18 @@ import { ...@@ -20,12 +20,18 @@ import {
import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store' import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store'
import { registerLocalSpanRecorder } from './local-span-recorder' import { registerLocalSpanRecorder } from './local-span-recorder'
import { AppRenderSpan, NodeSpan } from './constants' import {
AppRenderSpan,
BaseServerSpan,
LoadComponentsSpan,
NodeSpan,
} from './constants'
import { SpanKind, SpanStatusCode, getTracer } from './tracer' import { SpanKind, SpanStatusCode, getTracer } from './tracer'
const customContextKey = createContextKey('next.tracer.test.custom-context') const customContextKey = createContextKey('next.tracer.test.custom-context')
const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS
const originalDevServer = process.env.__NEXT_DEV_SERVER const originalDevServer = process.env.__NEXT_DEV_SERVER
const originalOtelVerbose = process.env.NEXT_OTEL_VERBOSE
const spanRecords: SpanStoreRecord[] = [] const spanRecords: SpanStoreRecord[] = []
function getSpanRecords(filter: { name?: string } = {}): SpanStoreRecord[] { function getSpanRecords(filter: { name?: string } = {}): SpanStoreRecord[] {
...@@ -155,6 +161,7 @@ describe('local span recording', () => { ...@@ -155,6 +161,7 @@ describe('local span recording', () => {
beforeEach(() => { beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1' process.env.__NEXT_DEV_SERVER = '1'
delete process.env.__NEXT_REQUEST_INSIGHTS delete process.env.__NEXT_REQUEST_INSIGHTS
delete process.env.NEXT_OTEL_VERBOSE
setSpanRecorderForTest((span) => spanRecords.push(span)) setSpanRecorderForTest((span) => spanRecords.push(span))
registerLocalSpanRecorder() registerLocalSpanRecorder()
}) })
...@@ -170,6 +177,11 @@ describe('local span recording', () => { ...@@ -170,6 +177,11 @@ describe('local span recording', () => {
} else { } else {
process.env.__NEXT_DEV_SERVER = originalDevServer process.env.__NEXT_DEV_SERVER = originalDevServer
} }
if (originalOtelVerbose === undefined) {
delete process.env.NEXT_OTEL_VERBOSE
} else {
process.env.NEXT_OTEL_VERBOSE = originalOtelVerbose
}
trace.disable() trace.disable()
setSpanRecorderForTest(undefined) setSpanRecorderForTest(undefined)
spanRecords.length = 0 spanRecords.length = 0
...@@ -184,6 +196,90 @@ describe('local span recording', () => { ...@@ -184,6 +196,90 @@ describe('local span recording', () => {
expect(getSpanRecords()).toEqual([]) expect(getSpanRecords()).toEqual([])
}) })
it('records non-vanilla trace and wrapped spans for request insights', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
getTracer().trace(BaseServerSpan.render, () => undefined)
const wrappedLoadComponents = getTracer().wrap(
LoadComponentsSpan.loadComponents,
() => undefined
)
wrappedLoadComponents()
expect(getSpanRecords()).toEqual([
expect.objectContaining({
name: BaseServerSpan.render,
attributes: expect.objectContaining({
'next.span_category': 'nextjs',
}),
}),
expect.objectContaining({
name: LoadComponentsSpan.loadComponents,
attributes: expect.objectContaining({
'next.span_category': 'nextjs',
}),
}),
])
})
it('only exports non-vanilla spans when verbose tracing is enabled', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const exportedSpans: string[] = []
const delegateSpan = trace.wrapSpanContext({
traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef',
traceFlags: 1,
})
trace.setGlobalTracerProvider({
getTracer() {
return {
startSpan(name: string) {
exportedSpans.push(name)
return delegateSpan
},
startActiveSpan(...args: unknown[]) {
exportedSpans.push(args[0] as string)
const callback = args.at(-1) as (
span: typeof delegateSpan
) => unknown
return callback(delegateSpan)
},
}
},
})
getTracer().trace(BaseServerSpan.render, () => undefined)
expect(exportedSpans).toEqual([])
getTracer().trace(NodeSpan.runHandler, () => undefined)
expect(exportedSpans).toEqual([NodeSpan.runHandler])
process.env.NEXT_OTEL_VERBOSE = '1'
getTracer().trace(BaseServerSpan.render, () => undefined)
expect(exportedSpans).toEqual([NodeSpan.runHandler, BaseServerSpan.render])
})
it('does not record or export hidden spans', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
let receivedSpan: unknown = 'not-called'
const startSpan = jest.fn()
const startActiveSpan = jest.fn()
trace.setGlobalTracerProvider({
getTracer() {
return { startSpan, startActiveSpan }
},
})
getTracer().trace(BaseServerSpan.render, { hideSpan: true }, (span) => {
receivedSpan = span
})
expect(receivedSpan).toBeUndefined()
expect(getSpanRecords()).toEqual([])
expect(startSpan).not.toHaveBeenCalled()
expect(startActiveSpan).not.toHaveBeenCalled()
})
it('bypasses local span handling outside the dev server', () => { it('bypasses local span handling outside the dev server', () => {
delete process.env.__NEXT_DEV_SERVER delete process.env.__NEXT_DEV_SERVER
let receivedSpan: unknown = 'not-called' let receivedSpan: unknown = 'not-called'
...@@ -221,6 +317,7 @@ describe('local span recording', () => { ...@@ -221,6 +317,7 @@ describe('local span recording', () => {
durationMs: expect.any(Number), durationMs: expect.any(Number),
attributes: expect.objectContaining({ attributes: expect.objectContaining({
'next.route': '/products/[id]', 'next.route': '/products/[id]',
'next.span_category': 'nextjs',
'next.span_name': 'test.sync', 'next.span_name': 'test.sync',
'next.span_type': NodeSpan.runHandler, 'next.span_type': NodeSpan.runHandler,
}), }),
...@@ -235,6 +332,7 @@ describe('local span recording', () => { ...@@ -235,6 +332,7 @@ describe('local span recording', () => {
kind: SpanKind.CLIENT, kind: SpanKind.CLIENT,
spanName: 'fetch GET https://example.vercel.sh/', spanName: 'fetch GET https://example.vercel.sh/',
attributes: { attributes: {
'next.span_category': 'application',
'http.url': 'https://example.vercel.sh/', 'http.url': 'https://example.vercel.sh/',
'http.method': 'GET', 'http.method': 'GET',
'net.peer.name': 'example.vercel.sh', 'net.peer.name': 'example.vercel.sh',
...@@ -253,6 +351,7 @@ describe('local span recording', () => { ...@@ -253,6 +351,7 @@ describe('local span recording', () => {
attributes: expect.objectContaining({ attributes: expect.objectContaining({
'next.span_name': 'fetch GET https://example.vercel.sh/', 'next.span_name': 'fetch GET https://example.vercel.sh/',
'next.span_type': AppRenderSpan.fetch, 'next.span_type': AppRenderSpan.fetch,
'next.span_category': 'application',
'http.url': 'https://example.vercel.sh/', 'http.url': 'https://example.vercel.sh/',
'http.method': 'GET', 'http.method': 'GET',
'net.peer.name': 'example.vercel.sh', 'net.peer.name': 'example.vercel.sh',
...@@ -415,7 +514,10 @@ describe('local span recording', () => { ...@@ -415,7 +514,10 @@ describe('local span recording', () => {
expect(getTracer().getActiveScopeSpan()).toBe(parentSpan) expect(getTracer().getActiveScopeSpan()).toBe(parentSpan)
const childSpan = getTracer().startSpan(AppRenderSpan.fetch, { const childSpan = getTracer().startSpan(AppRenderSpan.fetch, {
attributes: { 'next.page': 'child' }, attributes: {
'next.page': 'child',
'next.span_category': 'application',
},
}) })
childSpanId = childSpan.spanContext().spanId childSpanId = childSpan.spanContext().spanId
childSpan.end() childSpan.end()
...@@ -434,6 +536,9 @@ describe('local span recording', () => { ...@@ -434,6 +536,9 @@ describe('local span recording', () => {
expect.objectContaining({ expect.objectContaining({
name: NodeSpan.runHandler, name: NodeSpan.runHandler,
parentSpanId: undefined, parentSpanId: undefined,
attributes: expect.objectContaining({
'next.span_category': 'nextjs',
}),
}) })
) )
expect(childRecord).toEqual( expect(childRecord).toEqual(
...@@ -442,6 +547,9 @@ describe('local span recording', () => { ...@@ -442,6 +547,9 @@ describe('local span recording', () => {
spanId: childSpanId, spanId: childSpanId,
traceId: parentRecord?.traceId, traceId: parentRecord?.traceId,
parentSpanId: parentRecord?.spanId, parentSpanId: parentRecord?.spanId,
attributes: expect.objectContaining({
'next.span_category': 'application',
}),
}) })
) )
}) })
......
...@@ -185,6 +185,7 @@ type NextAttributeNames = ...@@ -185,6 +185,7 @@ type NextAttributeNames =
| 'next.page' | 'next.page'
| 'next.rsc' | 'next.rsc'
| 'next.segment' | 'next.segment'
| 'next.span_category'
| 'next.span_name' | 'next.span_name'
| 'next.span_type' | 'next.span_type'
| 'next.clientComponentLoadCount' | 'next.clientComponentLoadCount'
...@@ -337,8 +338,9 @@ class NextTracerImpl implements NextTracer { ...@@ -337,8 +338,9 @@ class NextTracerImpl implements NextTracer {
const [type, fnOrOptions, fnOrEmpty] = args const [type, fnOrOptions, fnOrEmpty] = args
const tracingEnabled = const tracingEnabled =
Boolean(NEXT_OTEL_PERFORMANCE_PREFIX) || this.isOpenTelemetryEnabled() Boolean(NEXT_OTEL_PERFORMANCE_PREFIX) || this.isOpenTelemetryEnabled()
const localSpanRecorder = getLocalSpanRecorder()
const localSpanRecordingEnabled = const localSpanRecordingEnabled =
getLocalSpanRecorder()?.isLocalSpanRecordingEnabled() ?? false localSpanRecorder?.isLocalSpanRecordingEnabled() ?? false
if (!tracingEnabled && !localSpanRecordingEnabled) { if (!tracingEnabled && !localSpanRecordingEnabled) {
return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty() return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty()
...@@ -364,11 +366,14 @@ class NextTracerImpl implements NextTracer { ...@@ -364,11 +366,14 @@ class NextTracerImpl implements NextTracer {
const spanName = options.spanName ?? type const spanName = options.spanName ?? type
if ( const shouldDelegateSpan =
(!NextVanillaSpanAllowlist.has(type) && NextVanillaSpanAllowlist.has(type) ||
process.env.NEXT_OTEL_VERBOSE !== '1') || process.env.NEXT_OTEL_VERBOSE === '1'
options.hideSpan const shouldTraceSpan =
) { shouldDelegateSpan ||
(localSpanRecorder?.isRequestInsightsEnabled() ?? false)
if (!shouldTraceSpan || options.hideSpan) {
return fn() return fn()
} }
...@@ -392,6 +397,7 @@ class NextTracerImpl implements NextTracer { ...@@ -392,6 +397,7 @@ class NextTracerImpl implements NextTracer {
const spanId = getSpanId() const spanId = getSpanId()
options.attributes = { options.attributes = {
'next.span_category': 'nextjs',
'next.span_name': spanName, 'next.span_name': spanName,
'next.span_type': type, 'next.span_type': type,
...options.attributes, ...options.attributes,
...@@ -402,7 +408,7 @@ class NextTracerImpl implements NextTracer { ...@@ -402,7 +408,7 @@ class NextTracerImpl implements NextTracer {
spanName, spanName,
options, options,
spanContext, spanContext,
tracingEnabled, tracingEnabled && shouldDelegateSpan,
localSpanRecordingEnabled, localSpanRecordingEnabled,
(span: Span) => { (span: Span) => {
let startTime: number | undefined let startTime: number | undefined
...@@ -545,6 +551,7 @@ class NextTracerImpl implements NextTracer { ...@@ -545,6 +551,7 @@ class NextTracerImpl implements NextTracer {
name, name,
attributes: options.attributes, attributes: options.attributes,
links: options.links, links: options.links,
startTime: options.startTime,
delegateSpan, delegateSpan,
traceId: delegateSpanContext?.traceId ?? parentSpanContext?.traceId, traceId: delegateSpanContext?.traceId ?? parentSpanContext?.traceId,
spanId: delegateSpanContext?.spanId, spanId: delegateSpanContext?.spanId,
...@@ -570,7 +577,8 @@ class NextTracerImpl implements NextTracer { ...@@ -570,7 +577,8 @@ class NextTracerImpl implements NextTracer {
if ( if (
!NextVanillaSpanAllowlist.has(name) && !NextVanillaSpanAllowlist.has(name) &&
process.env.NEXT_OTEL_VERBOSE !== '1' process.env.NEXT_OTEL_VERBOSE !== '1' &&
!process.env.__NEXT_DEV_SERVER
) { ) {
return fn return fn
} }
...@@ -603,10 +611,20 @@ class NextTracerImpl implements NextTracer { ...@@ -603,10 +611,20 @@ class NextTracerImpl implements NextTracer {
public startSpan(type: SpanTypes): Span public startSpan(type: SpanTypes): Span
public startSpan(type: SpanTypes, options: TracerSpanOptions): Span public startSpan(type: SpanTypes, options: TracerSpanOptions): Span
public startSpan(...args: Array<any>): Span { public startSpan(...args: Array<any>): Span {
const [type, options]: [string, TracerSpanOptions | undefined] = args as any const [type, passedOptions]: [string, TracerSpanOptions | undefined] =
args as any
const options: TracerSpanOptions = passedOptions
? {
...passedOptions,
attributes: {
'next.span_category': 'nextjs',
...passedOptions.attributes,
},
}
: { attributes: { 'next.span_category': 'nextjs' } }
const parentContext = const parentContext =
this.getSpanContext(options?.parentSpan ?? this.getActiveScopeSpan()) ?? this.getSpanContext(options.parentSpan ?? this.getActiveScopeSpan()) ??
context.active() context.active()
const localSpanRecordingEnabled = const localSpanRecordingEnabled =
getLocalSpanRecorder()?.isLocalSpanRecordingEnabled() ?? false getLocalSpanRecorder()?.isLocalSpanRecordingEnabled() ?? false
...@@ -621,7 +639,7 @@ class NextTracerImpl implements NextTracer { ...@@ -621,7 +639,7 @@ class NextTracerImpl implements NextTracer {
return this.createLocalRecordingSpan( return this.createLocalRecordingSpan(
type, type,
options ?? {}, options,
parentContext, parentContext,
delegateSpan delegateSpan
) )
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createServer } from 'http' import { createServer } from 'http'
import type { AddressInfo } from 'net' import type { AddressInfo } from 'net'
import { retry } from 'next-test-utils'
type RequestInsight = { type RequestInsight = {
requestId: string requestId: string
...@@ -8,7 +9,9 @@ type RequestInsight = { ...@@ -8,7 +9,9 @@ type RequestInsight = {
route: string route: string
startTime: number startTime: number
status: 'ok' status: 'ok'
spans: [] spans: Array<{
attributes?: Record<string, string | number | boolean>
}>
fetches: Array<{ fetches: Array<{
durationMs: number durationMs: number
statusCode: number statusCode: number
...@@ -80,6 +83,42 @@ describe('request insights', () => { ...@@ -80,6 +83,42 @@ describe('request insights', () => {
) )
}) })
it('keeps outer server and app render spans on the same request', async () => {
await next.render('/')
await retry(async () => {
const snapshot = (await next
.fetch('/_next/development/request-insights')
.then((response) => response.json())) as {
requests: RequestInsight[]
}
const pageRequests = snapshot.requests.filter(
(request) => request.route === '/'
)
const requestsWithRelevantSpans = pageRequests.filter((request) =>
request.spans.some((span) => {
const spanType = span.attributes?.['next.span_type']
return (
spanType === 'BaseServer.handleRequest' ||
spanType === 'AppRender.getBodyResult'
)
})
)
expect(requestsWithRelevantSpans).toHaveLength(1)
expect(
requestsWithRelevantSpans[0].spans.map(
(span) => span.attributes?.['next.span_type']
)
).toEqual(
expect.arrayContaining([
'BaseServer.handleRequest',
'AppRender.getBodyResult',
])
)
})
})
it('uses the development endpoint and reports truncated output', async () => { it('uses the development endpoint and reports truncated output', async () => {
const { result, requestedPaths } = await runWithResponse( const { result, requestedPaths } = await runWithResponse(
{ {
......
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