Unverified Commit fab0afcb authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

request insights: record local framework spans (1/5) (#93974)

## What

Adds a dev-only local recorder for framework OTEL spans. This lets Next
mirror span data into an in-memory store when local span capture is
enabled, without requiring a user to run an OTEL provider.

Stack:

1. request insights: record local framework spans (1/5) ← current
2. request insights: derive request history and fetch data (2/5)
3. request insights: expose dev snapshots to tools and HMR (3/5)
4. request insights: add agent diagnosis access (4/5)
5. request insights: add DevTools request panel (5/5)

## Review Focus

- Local recorder behavior when no OTEL provider is installed.
- Preserving existing OTEL span API behavior when a provider is
installed.
- Request identity propagation through existing app render async
storage.

## Proof In This PR

- `pnpm jest packages/next/src/server/lib/trace/tracer.test.ts
packages/next/src/server/lib/trace/span-store.test.ts --runInBand`
- `pnpm --filter=next types`

## Deferred Coverage

- Request-level aggregation, fetch enrichment, dev transport, CLI/MCP
access, and the DevTools panel are later PRs in this stack.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 1bd2fd58
...@@ -2707,6 +2707,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -2707,6 +2707,8 @@ async function renderToHTMLOrFlightImpl(
// 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 || requestId
workStore.requestId = requestId
workStore.htmlRequestId = htmlRequestId
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment( const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
interpolatedParams, interpolatedParams,
...@@ -7376,6 +7378,8 @@ async function validateInstantConfigInBuildWithSample( ...@@ -7376,6 +7378,8 @@ async function validateInstantConfigInBuildWithSample(
isBuildTimePrerendering: false, isBuildTimePrerendering: false,
fetchCache: outerWorkStore.fetchCache, fetchCache: outerWorkStore.fetchCache,
isOnDemandRevalidate: false, isOnDemandRevalidate: false,
requestId: outerWorkStore.requestId,
htmlRequestId: outerWorkStore.htmlRequestId,
isDraftMode: false, isDraftMode: false,
......
...@@ -117,6 +117,14 @@ export interface WorkStore { ...@@ -117,6 +117,14 @@ export interface WorkStore {
isUnstableNoStore?: boolean isUnstableNoStore?: boolean
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
/**
* Dev-only request identity used by local request insights. requestId
* identifies one server request, while htmlRequestId groups requests that
* originated from the same browser page.
*/
requestId?: string
htmlRequestId?: string
/** /**
* This only exists because it's needed in use-cache-wrapper * This only exists because it's needed in use-cache-wrapper
*/ */
......
...@@ -137,6 +137,8 @@ export function createWorkStore({ ...@@ -137,6 +137,8 @@ export function createWorkStore({
isBuildTimePrerendering: renderOpts.isBuildTimePrerendering, isBuildTimePrerendering: renderOpts.isBuildTimePrerendering,
fetchCache: renderOpts.fetchCache, fetchCache: renderOpts.fetchCache,
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate, isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
requestId: undefined,
htmlRequestId: undefined,
isDraftMode: renderOpts.isDraftMode, isDraftMode: renderOpts.isDraftMode,
......
...@@ -89,6 +89,9 @@ import type { PrerenderManifest } from '../../build' ...@@ -89,6 +89,9 @@ import type { PrerenderManifest } from '../../build'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import type { PrerenderedRoute } from '../../build/static-paths/types' import type { PrerenderedRoute } from '../../build/static-paths/types'
import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types' import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'
registerLocalSpanRecorder()
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType let PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType
......
/**
* @jest-environment node
*/
import { runInNewContext } from 'node:vm'
import { setFlagsFromString } from 'node:v8'
import { SpanStatusCode, trace } from 'next/dist/compiled/@opentelemetry/api'
import { createLocalSpan } from './local-span-recorder'
import { clearSpanStoreForTest, getSpanRecords } from './span-store'
const originalLocalSpans = process.env.NEXT_OTEL_LOCAL_SPANS
const originalDevServer = process.env.__NEXT_DEV_SERVER
setFlagsFromString('--expose-gc')
const forceGarbageCollection = runInNewContext('gc') as () => void
describe('local recording span', () => {
beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1'
})
afterEach(() => {
if (originalLocalSpans === undefined) {
delete process.env.NEXT_OTEL_LOCAL_SPANS
} else {
process.env.NEXT_OTEL_LOCAL_SPANS = originalLocalSpans
}
if (originalDevServer === undefined) {
delete process.env.__NEXT_DEV_SERVER
} else {
process.env.__NEXT_DEV_SERVER = originalDevServer
}
clearSpanStoreForTest()
})
it('records a snapshot exactly once when the span ends', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({
name: 'test.local-span',
traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef',
attributes: {
'next.phase': 'render',
},
})
span.setAttribute('next.route', '/dashboard')
expect(span.isRecording()).toBe(true)
expect(getSpanRecords()).toEqual([])
span.end()
span.setAttribute('next.after_end', true)
span.end()
expect(span.isRecording()).toBe(false)
expect(getSpanRecords()).toEqual([
expect.objectContaining({
name: 'test.local-span',
traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef',
route: '/dashboard',
status: 'ok',
attributes: {
'next.phase': 'render',
'next.route': '/dashboard',
},
}),
])
})
it('ignores undefined values when setting attributes', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({
name: 'test.local-span.attributes',
attributes: { 'next.phase': 'render' },
})
span.setAttributes({
'next.phase': undefined,
'next.route': '/dashboard',
})
span.end()
expect(getSpanRecords()).toEqual([
expect.objectContaining({
attributes: {
'next.phase': 'render',
'next.route': '/dashboard',
},
}),
])
})
it('captures status, exception, and event mutations before ending', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({ name: 'test.local-span.error' })
span.addEvent('test.event', { 'next.phase': 'render' })
span.recordException(new TypeError('boom'))
span.setStatus({ code: SpanStatusCode.ERROR, message: 'failed' })
span.end()
expect(getSpanRecords()).toEqual([
expect.objectContaining({
name: 'test.local-span.error',
status: 'error',
error: {
type: 'TypeError',
message: 'boom',
},
events: [
expect.objectContaining({
name: 'test.event',
attributes: { 'next.phase': 'render' },
}),
expect.objectContaining({
name: 'exception',
attributes: {
'exception.type': 'TypeError',
'exception.message': 'boom',
},
}),
],
}),
])
})
it('releases heavy references after ending while the span remains reachable', async () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const { span, delegateRef, attributeRef } = createEndedSpanWithReferences()
clearSpanStoreForTest()
await expectCollected(delegateRef)
await expectCollected(attributeRef)
expect(span.spanContext()).toEqual({
traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef',
traceFlags: 1,
})
})
})
function createEndedSpanWithReferences() {
const delegate = trace.wrapSpanContext({
traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef',
traceFlags: 1,
})
const attributeValue = ['retained-value']
const delegateRef = new WeakRef(delegate)
const attributeRef = new WeakRef(attributeValue)
const span = createLocalSpan({
name: 'test.local-span.retention',
delegateSpan: delegate,
attributes: {
'next.test.payload': attributeValue,
},
})
span.end()
return { span, delegateRef, attributeRef }
}
async function expectCollected(ref: WeakRef<object>): Promise<void> {
for (let attempt = 0; attempt < 10; attempt++) {
forceGarbageCollection()
await new Promise<void>((resolve) => setImmediate(resolve))
}
expect(ref.deref()).toBeUndefined()
}
This diff is collapsed.
import { runInNewContext } from 'node:vm'
import { setFlagsFromString } from 'node:v8'
import {
clearSpanStoreForTest,
getSpanRecords,
InMemorySpanStore,
isLocalSpanStoreEnabled,
isRequestInsightsEnabled,
recordSpan,
} from './span-store'
const originalLocalSpans = process.env.NEXT_OTEL_LOCAL_SPANS
const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS
const originalDevServer = process.env.__NEXT_DEV_SERVER
setFlagsFromString('--expose-gc')
const forceGarbageCollection = runInNewContext('gc') as () => void
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) {
delete process.env[name]
} else {
process.env[name] = value
}
}
describe('span store', () => {
beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1'
})
afterEach(() => {
restoreEnv('NEXT_OTEL_LOCAL_SPANS', originalLocalSpans)
restoreEnv('__NEXT_REQUEST_INSIGHTS', originalRequestInsights)
restoreEnv('__NEXT_DEV_SERVER', originalDevServer)
clearSpanStoreForTest()
})
it('keeps bounded in-memory records with OTel-compatible identity fields and links', () => {
const traceStore = new InMemorySpanStore({ maxRecords: 2 })
traceStore.record({
name: 'next.cache_component.produce',
traceId: '00000000000000000000000000000001',
spanId: '0000000000000001',
route: '/products/[id]',
attributes: {
'next.phase': 'build',
'next.artifact.kind': 'ppr-shell',
},
})
traceStore.record({
name: 'next.cache_component.consume',
traceId: '00000000000000000000000000000002',
spanId: '0000000000000002',
requestId: 'req_1',
route: '/products/[id]',
attributes: {
'next.phase': 'request',
'next.cache.status': 'hit',
'next.artifact.kind': 'ppr-shell',
},
events: [
{
name: 'next.cache.lookup',
timestamp: 1,
attributes: {
'next.cache.status': 'hit',
},
},
],
links: [
{
traceId: '00000000000000000000000000000001',
spanId: '0000000000000001',
attributes: {
'next.link.reason': 'artifact.reuse',
},
},
],
})
traceStore.record({
name: 'next.cache_component.consume',
requestId: 'req_2',
route: '/cart',
attributes: {
'next.cache.status': 'miss',
},
})
expect(traceStore.getRecords()).toHaveLength(2)
expect(traceStore.getRecords({ requestId: 'req_1' })).toEqual([
expect.objectContaining({
name: 'next.cache_component.consume',
requestId: 'req_1',
route: '/products/[id]',
attributes: expect.objectContaining({
'next.cache.status': 'hit',
}),
links: [
{
traceId: '00000000000000000000000000000001',
spanId: '0000000000000001',
attributes: {
'next.link.reason': 'artifact.reuse',
},
},
],
events: [
{
name: 'next.cache.lookup',
timestamp: 1,
attributes: {
'next.cache.status': 'hit',
},
},
],
}),
])
})
it('releases attribute payloads from evicted records', async () => {
const { traceStore, attributeRef } = createStoreWithEvictedAttribute()
expect(traceStore.getRecords()).toEqual([
expect.objectContaining({ name: 'second' }),
])
await expectCollected(attributeRef)
})
it('records to the global in-memory store only when local span capture is enabled', () => {
delete process.env.NEXT_OTEL_LOCAL_SPANS
recordSpan({
name: 'next.cache_component.consume',
requestId: 'req_1',
})
expect(getSpanRecords()).toEqual([])
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
recordSpan({
name: 'next.cache_component.consume',
requestId: 'req_1',
attributes: {
'next.cache.status': 'hit',
},
})
expect(getSpanRecords({ requestId: 'req_1' })).toEqual([
expect.objectContaining({
name: 'next.cache_component.consume',
requestId: 'req_1',
attributes: {
'next.cache.status': 'hit',
},
}),
])
})
it('does not enable local span capture outside the dev server', () => {
delete process.env.__NEXT_DEV_SERVER
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
expect(isLocalSpanStoreEnabled()).toBe(false)
recordSpan({ name: 'test.production' })
expect(getSpanRecords()).toEqual([])
})
it('shares local records across separate module instances in the same process', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
jest.isolateModules(() => {
const { recordSpan: recordSpanFromIsolatedModule } =
require('./span-store') as typeof import('./span-store')
recordSpanFromIsolatedModule({
name: 'fetch GET https://example.vercel.sh/',
spanId: '0000000000000001',
traceId: '00000000000000000000000000000001',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url': 'https://example.vercel.sh/',
},
})
})
expect(getSpanRecords()).toEqual([
expect.objectContaining({
name: 'fetch GET https://example.vercel.sh/',
spanId: '0000000000000001',
traceId: '00000000000000000000000000000001',
attributes: expect.objectContaining({
'next.span_type': 'AppRender.fetch',
'http.url': 'https://example.vercel.sh/',
}),
}),
])
})
it('treats boolean define-env request insights values as enabled', () => {
;(process.env.__NEXT_REQUEST_INSIGHTS as unknown) = true
expect(isRequestInsightsEnabled()).toBe(true)
})
})
function createStoreWithEvictedAttribute() {
const traceStore = new InMemorySpanStore({ maxRecords: 1 })
const attributeValue = ['retained-value']
const attributeRef = new WeakRef(attributeValue)
traceStore.record({
name: 'first',
attributes: { 'next.test.payload': attributeValue },
})
traceStore.record({ name: 'second' })
return { traceStore, attributeRef }
}
async function expectCollected(ref: WeakRef<object>): Promise<void> {
for (let attempt = 0; attempt < 10; attempt++) {
forceGarbageCollection()
await new Promise<void>((resolve) => setImmediate(resolve))
}
expect(ref.deref()).toBeUndefined()
}
import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'
export type SpanStoreAttributes = Record<string, AttributeValue>
export type SpanStoreLink = {
traceId: string
spanId: string
attributes?: SpanStoreAttributes
}
export type SpanStoreEvent = {
name: string
timestamp: number
attributes?: SpanStoreAttributes
}
export type SpanStoreRecord = {
name: string
timestamp: number
startTime?: number
durationMs?: number
status?: 'ok' | 'error'
traceId?: string
spanId?: string
parentSpanId?: string
requestId?: string
htmlRequestId?: string
route?: string
url?: string
attributes?: SpanStoreAttributes
links?: SpanStoreLink[]
events?: SpanStoreEvent[]
error?: {
type?: string
message?: string
}
}
export type SpanStoreFilter = {
requestId?: string
route?: string
name?: string
}
export type InMemorySpanStoreOptions = {
maxRecords?: number
}
const DEFAULT_MAX_RECORDS = 128
const LOCAL_SPAN_STORE_KEY = Symbol.for('@next/local-span-store')
export class InMemorySpanStore {
private readonly maxRecords: number
private records: SpanStoreRecord[] = []
constructor(options: InMemorySpanStoreOptions = {}) {
this.maxRecords = options.maxRecords ?? DEFAULT_MAX_RECORDS
}
record(record: Omit<SpanStoreRecord, 'timestamp'>): SpanStoreRecord {
const spanRecord = {
timestamp: Date.now(),
...record,
}
this.records.push(spanRecord)
if (this.records.length > this.maxRecords) {
this.records.splice(0, this.records.length - this.maxRecords)
}
return spanRecord
}
getRecords(filter: SpanStoreFilter = {}): SpanStoreRecord[] {
return this.records.filter(
(record) =>
(filter.requestId === undefined ||
record.requestId === filter.requestId) &&
(filter.route === undefined || record.route === filter.route) &&
(filter.name === undefined || record.name === filter.name)
)
}
clear(): void {
this.records = []
}
}
export function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {
if (!isLocalSpanStoreEnabled()) {
return
}
getLocalSpanStore().record(record)
}
export function getSpanRecords(filter?: SpanStoreFilter): SpanStoreRecord[] {
return getLocalSpanStore().getRecords(filter)
}
export function clearSpanStoreForTest(): void {
getLocalSpanStore().clear()
}
export function isLocalSpanStoreEnabled(): boolean {
if (!process.env.__NEXT_DEV_SERVER) {
return false
}
const value = process.env.NEXT_OTEL_LOCAL_SPANS
return isEnabledEnvValue(value) || isRequestInsightsEnabled()
}
export function isRequestInsightsEnabled(): boolean {
const value = process.env.__NEXT_REQUEST_INSIGHTS
return isEnabledEnvValue(value)
}
function isEnabledEnvValue(value: string | undefined): boolean {
return value === '1' || value === 'true' || (value as unknown) === true
}
function getLocalSpanStore(): InMemorySpanStore {
const globalStore = globalThis as typeof globalThis & {
[LOCAL_SPAN_STORE_KEY]?: InMemorySpanStore
}
return (globalStore[LOCAL_SPAN_STORE_KEY] ??= new InMemorySpanStore())
}
import type { FetchEventResult } from '../../web/types' import type { FetchEventResult } from '../../web/types'
import type { TextMapSetter } from '@opentelemetry/api' import type { TextMapSetter } from '@opentelemetry/api'
import type { SpanTypes } from './constants' import type { SpanTypes } from './constants'
import type { LocalSpanRecorder } from './local-span-recorder'
import { LogSpanAllowList, NextVanillaSpanAllowlist } from './constants' import { LogSpanAllowList, NextVanillaSpanAllowlist } from './constants'
import type { import type {
Context,
ContextAPI, ContextAPI,
Span, Span,
SpanOptions, SpanOptions,
...@@ -14,9 +16,22 @@ import type { ...@@ -14,9 +16,22 @@ import type {
import { isThenable } from '../../../shared/lib/is-thenable' import { isThenable } from '../../../shared/lib/is-thenable'
const NEXT_OTEL_PERFORMANCE_PREFIX = process.env.NEXT_OTEL_PERFORMANCE_PREFIX const NEXT_OTEL_PERFORMANCE_PREFIX = process.env.NEXT_OTEL_PERFORMANCE_PREFIX
const LOCAL_SPAN_RECORDER_KEY = Symbol.for('@next/local-span-recorder')
type GlobalWithLocalSpanRecorder = typeof globalThis & {
[LOCAL_SPAN_RECORDER_KEY]?: LocalSpanRecorder
}
let api: typeof import('next/dist/compiled/@opentelemetry/api') let api: typeof import('next/dist/compiled/@opentelemetry/api')
function getLocalSpanRecorder() {
if (process.env.__NEXT_DEV_SERVER) {
return (globalThis as GlobalWithLocalSpanRecorder)[LOCAL_SPAN_RECORDER_KEY]
} else {
return undefined
}
}
// we want to allow users to use their own version of @opentelemetry/api if they // we want to allow users to use their own version of @opentelemetry/api if they
// want to, so we try to require it first, and if it fails we fall back to the // want to, so we try to require it first, and if it fails we fall back to the
// version that is bundled with Next.js // version that is bundled with Next.js
...@@ -209,8 +224,9 @@ class NextTracerImpl implements NextTracer { ...@@ -209,8 +224,9 @@ class NextTracerImpl implements NextTracer {
return trace.getTracer('next.js', '0.0.1') return trace.getTracer('next.js', '0.0.1')
} }
private isTracingEnabled(): boolean { private isOpenTelemetryEnabled(): boolean {
if (this.getActiveScopeSpan()?.isRecording()) { const activeSpan = trace.getSpan(context.active())
if (activeSpan?.isRecording()) {
return true return true
} }
...@@ -239,7 +255,11 @@ class NextTracerImpl implements NextTracer { ...@@ -239,7 +255,11 @@ class NextTracerImpl implements NextTracer {
} }
public getActiveScopeSpan(): Span | undefined { public getActiveScopeSpan(): Span | undefined {
return trace.getSpan(context?.active()) const activeSpan = trace.getSpan(context.active())
if (activeSpan || !process.env.__NEXT_DEV_SERVER) {
return activeSpan
}
return getLocalSpanRecorder()?.getActiveLocalSpan()
} }
/** /**
...@@ -249,7 +269,7 @@ class NextTracerImpl implements NextTracer { ...@@ -249,7 +269,7 @@ class NextTracerImpl implements NextTracer {
* edge middleware which runs in a detached sandbox. * edge middleware which runs in a detached sandbox.
*/ */
public runWithDetachedContext<T>(fn: () => T): T { public runWithDetachedContext<T>(fn: () => T): T {
if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isTracingEnabled()) { if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled()) {
return fn() return fn()
} }
return context.with(ROOT_CONTEXT, fn) return context.with(ROOT_CONTEXT, fn)
...@@ -265,7 +285,7 @@ class NextTracerImpl implements NextTracer { ...@@ -265,7 +285,7 @@ class NextTracerImpl implements NextTracer {
if ( if (
!NEXT_OTEL_PERFORMANCE_PREFIX && !NEXT_OTEL_PERFORMANCE_PREFIX &&
!this.isTracingEnabled() && !this.isOpenTelemetryEnabled() &&
!trace.getSpanContext(activeContext) !trace.getSpanContext(activeContext)
) { ) {
return fn() return fn()
...@@ -315,8 +335,12 @@ class NextTracerImpl implements NextTracer { ...@@ -315,8 +335,12 @@ class NextTracerImpl implements NextTracer {
): T ): T
public trace<T>(...args: Array<any>) { public trace<T>(...args: Array<any>) {
const [type, fnOrOptions, fnOrEmpty] = args const [type, fnOrOptions, fnOrEmpty] = args
const tracingEnabled =
Boolean(NEXT_OTEL_PERFORMANCE_PREFIX) || this.isOpenTelemetryEnabled()
const localSpanStoreEnabled =
getLocalSpanRecorder()?.isLocalSpanStoreEnabled() ?? false
if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isTracingEnabled()) { if (!tracingEnabled && !localSpanStoreEnabled) {
return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty() return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty()
} }
...@@ -374,9 +398,12 @@ class NextTracerImpl implements NextTracer { ...@@ -374,9 +398,12 @@ class NextTracerImpl implements NextTracer {
} }
return context.with(spanContext.setValue(rootSpanIdKey, spanId), () => return context.with(spanContext.setValue(rootSpanIdKey, spanId), () =>
this.getTracerInstance().startActiveSpan( this.runWithActiveSpan(
spanName, spanName,
options, options,
spanContext,
tracingEnabled,
localSpanStoreEnabled,
(span: Span) => { (span: Span) => {
let startTime: number | undefined let startTime: number | undefined
if ( if (
...@@ -424,7 +451,13 @@ class NextTracerImpl implements NextTracer { ...@@ -424,7 +451,13 @@ class NextTracerImpl implements NextTracer {
} }
if (fn.length > 1) { if (fn.length > 1) {
try { try {
return fn(span, (err) => closeSpanWithError(span, err)) return fn(span, (err) => {
if (err) {
closeSpanWithError(span, err)
} else {
span.end()
}
})
} catch (err: any) { } catch (err: any) {
closeSpanWithError(span, err) closeSpanWithError(span, err)
throw err throw err
...@@ -465,6 +498,60 @@ class NextTracerImpl implements NextTracer { ...@@ -465,6 +498,60 @@ class NextTracerImpl implements NextTracer {
) )
} }
private runWithActiveSpan<T>(
spanName: string,
options: TracerSpanOptions,
parentContext: Context,
tracingEnabled: boolean,
localSpanStoreEnabled: boolean,
fn: (span: Span) => T
): T {
if (tracingEnabled) {
return this.getTracerInstance().startActiveSpan(
spanName,
options,
(span: Span) =>
fn(
localSpanStoreEnabled
? this.createLocalRecordingSpan(
spanName,
options,
parentContext,
span
)
: span
)
)
}
const span = this.createLocalRecordingSpan(spanName, options, parentContext)
const activeContext = trace.setSpan(context.active(), span)
return getLocalSpanRecorder()!.withLocalSpan(span, () =>
context.with(activeContext, fn, undefined, span)
)
}
private createLocalRecordingSpan(
name: string,
options: TracerSpanOptions,
parentContext: Context,
delegateSpan?: Span
): Span {
const parentSpanContext = trace.getSpanContext(parentContext)
const delegateSpanContext = delegateSpan?.spanContext()
return getLocalSpanRecorder()!.createLocalSpan({
name,
attributes: options.attributes,
links: options.links,
delegateSpan,
traceId: delegateSpanContext?.traceId ?? parentSpanContext?.traceId,
spanId: delegateSpanContext?.spanId,
parentSpanId: parentSpanContext?.spanId,
})
}
public wrap<T = (...args: Array<any>) => any>(type: SpanTypes, 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>(
type: SpanTypes, type: SpanTypes,
...@@ -518,10 +605,26 @@ class NextTracerImpl implements NextTracer { ...@@ -518,10 +605,26 @@ class NextTracerImpl implements NextTracer {
public startSpan(...args: Array<any>): Span { public startSpan(...args: Array<any>): Span {
const [type, options]: [string, TracerSpanOptions | undefined] = args as any const [type, options]: [string, TracerSpanOptions | undefined] = args as any
const spanContext = this.getSpanContext( const parentContext =
options?.parentSpan ?? this.getActiveScopeSpan() this.getSpanContext(options?.parentSpan ?? this.getActiveScopeSpan()) ??
context.active()
const localSpanStoreEnabled =
getLocalSpanRecorder()?.isLocalSpanStoreEnabled() ?? false
if (!localSpanStoreEnabled) {
return this.getTracerInstance().startSpan(type, options, parentContext)
}
const delegateSpan = this.isOpenTelemetryEnabled()
? this.getTracerInstance().startSpan(type, options, parentContext)
: undefined
return this.createLocalRecordingSpan(
type,
options ?? {},
parentContext,
delegateSpan
) )
return this.getTracerInstance().startSpan(type, options, spanContext)
} }
private getSpanContext(parentSpan?: Span) { private getSpanContext(parentSpan?: Span) {
...@@ -543,10 +646,21 @@ class NextTracerImpl implements NextTracer { ...@@ -543,10 +646,21 @@ class NextTracerImpl implements NextTracer {
if (attributes && !attributes.has(key)) { if (attributes && !attributes.has(key)) {
attributes.set(key, value) attributes.set(key, value)
} }
if (process.env.__NEXT_DEV_SERVER) {
const localSpan = getLocalSpanRecorder()?.getActiveLocalSpan()
if (localSpan) {
localSpan.setAttribute(key, value)
}
}
} }
public withSpan<T>(span: Span, fn: () => T): T { public withSpan<T>(span: Span, fn: () => T): T {
const spanContext = trace.setSpan(context.active(), span) const spanContext = trace.setSpan(context.active(), span)
const recorder = getLocalSpanRecorder()
if (recorder?.isLocalRecordingSpan(span)) {
return recorder.withLocalSpan(span, () => context.with(spanContext, fn))
}
return context.with(spanContext, fn) return context.with(spanContext, fn)
} }
} }
......
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