Unverified Commit 510d00b5 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

request insights: derive request history and fetch data (2/5) (#93975)

## What

Builds the bounded request history store on top of local spans and fetch
metrics. Request Insights now keeps the last 100 requests, dedupes fetch
records, and preserves raw span details for later verbose consumers.

Stack:

1. request insights: record local framework spans (1/5)
2. request insights: derive request history and fetch data (2/5) ←
current
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

- The request insight schema shared by server, tools, and DevTools.
- Fetch cache/status mapping from existing `AppRender.fetch` spans.
- Dedupe between completed fetch spans and direct fetch metrics.

## Proof In This PR

- `pnpm jest packages/next/src/server/lib/trace/request-insights.test.ts
packages/next/src/server/lib/patch-fetch.test.ts --runInBand`
- `pnpm --filter=next types`

## Deferred Coverage

- Browser/HMR transport, CLI/MCP access, and the visual panel are later
PRs.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent fab0afcb
import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'
export type RequestInsightSpan = {
name: string
startTime: number
durationMs?: number
status?: 'ok' | 'error'
traceId?: string
spanId?: string
parentSpanId?: string
attributes?: Record<string, AttributeValue>
links?: Array<{
traceId: string
spanId: string
attributes?: Record<string, AttributeValue>
}>
events?: Array<{
name: string
timestamp: number
attributes?: Record<string, AttributeValue>
}>
error?: {
type?: string
message?: string
}
}
export type RequestInsightFetch = {
url?: string
method?: string
statusCode?: number
startTime?: number
durationMs?: number
cacheStatus?: string
cacheReason?: string
index?: number
}
export type RequestInsight = {
requestId: string
htmlRequestId: string
route?: string
url?: string
startTime: number
durationMs?: number
status: 'ok' | 'error' | 'pending'
spans: RequestInsightSpan[]
fetches: RequestInsightFetch[]
}
export type RequestInsightsSnapshot = {
requests: RequestInsight[]
}
...@@ -3,8 +3,31 @@ import type { WorkUnitStore } from '../app-render/work-unit-async-storage.extern ...@@ -3,8 +3,31 @@ import type { WorkUnitStore } from '../app-render/work-unit-async-storage.extern
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch' import { createPatchedFetcher } from './patch-fetch'
import { registerLocalSpanRecorder } from './trace/local-span-recorder'
import {
setSpanRecorderForTest,
type SpanStoreRecord,
} from './trace/span-store'
const originalDevServer = process.env.__NEXT_DEV_SERVER
const spanRecords: SpanStoreRecord[] = []
describe('createPatchedFetcher', () => { describe('createPatchedFetcher', () => {
beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1'
registerLocalSpanRecorder()
})
afterEach(() => {
if (originalDevServer === undefined) {
delete process.env.__NEXT_DEV_SERVER
} else {
process.env.__NEXT_DEV_SERVER = originalDevServer
}
setSpanRecorderForTest(undefined)
spanRecords.length = 0
})
it('should not buffer a streamed response', async () => { it('should not buffer a streamed response', async () => {
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn() const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
let streamChunk: () => void let streamChunk: () => void
...@@ -94,4 +117,50 @@ describe('createPatchedFetcher', () => { ...@@ -94,4 +117,50 @@ describe('createPatchedFetcher', () => {
// Setting a lower timeout than default, because the test will fail with a // Setting a lower timeout than default, because the test will fail with a
// timeout when we regress and buffer the response. // timeout when we regress and buffer the response.
}, 1000) }, 1000)
it('records fetch outcome attributes on local AppRender.fetch spans', async () => {
setSpanRecorderForTest((span) => spanRecords.push(span))
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockResolvedValue(new Response('ok', { status: 201 }))
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const workUnitAsyncStorage = new AsyncLocalStorage<WorkUnitStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage,
})
const workStore: Partial<WorkStore> = {
page: '/',
route: '/',
shouldTrackFetchMetrics: true,
}
await workAsyncStorage.run(workStore as WorkStore, async () => {
await patchedFetch('https://example.com/api', {
cache: 'no-store',
})
})
expect(
spanRecords.filter(
(span) => span.name === 'fetch GET https://example.com/api'
)
).toEqual([
expect.objectContaining({
name: 'fetch GET https://example.com/api',
status: 'ok',
attributes: expect.objectContaining({
'next.span_type': 'AppRender.fetch',
'http.url': 'https://example.com/api',
'http.method': 'GET',
'http.status_code': 201,
'next.fetch.idx': 2,
'next.fetch.cache_status': 'skip',
'next.fetch.cache_reason': 'cache: no-store',
}),
}),
])
})
}) })
...@@ -4,6 +4,10 @@ import type { ...@@ -4,6 +4,10 @@ import type {
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import { AppRenderSpan, NextNodeServerSpan } from './trace/constants' import { AppRenderSpan, NextNodeServerSpan } from './trace/constants'
import {
isRequestInsightsEnabled,
recordRequestInsightFetch,
} from './trace/request-insights'
import { getTracer, SpanKind } from './trace/tracer' import { getTracer, SpanKind } from './trace/tracer'
import { import {
CACHE_ONE_YEAR_SECONDS, CACHE_ONE_YEAR_SECONDS,
...@@ -31,6 +35,7 @@ import { cloneResponse } from './clone-response' ...@@ -31,6 +35,7 @@ import { cloneResponse } from './clone-response'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { RenderStage } from '../app-render/staged-rendering' import { RenderStage } from '../app-render/staged-rendering'
import { encodeCacheTag } from './encode-cache-tag' import { encodeCacheTag } from './encode-cache-tag'
import type { Span } from './trace/tracer'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -125,19 +130,49 @@ export function validateTags(tags: any[], description: string) { ...@@ -125,19 +130,49 @@ export function validateTags(tags: any[], description: string) {
function trackFetchMetric( function trackFetchMetric(
workStore: WorkStore, workStore: WorkStore,
span: Span | undefined,
ctx: Omit<FetchMetric, 'end' | 'idx'> ctx: Omit<FetchMetric, 'end' | 'idx'>
) { ) {
const metric = {
...ctx,
end: performance.timeOrigin + performance.now(),
idx: workStore.nextFetchId || 0,
}
span?.setAttributes({
'http.status_code': metric.status,
'next.fetch.idx': metric.idx,
'next.fetch.cache_status': metric.cacheStatus,
'next.fetch.cache_reason': metric.cacheReason,
})
if (isRequestInsightsEnabled() && workStore.requestId) {
recordRequestInsightFetch(
{
requestId: workStore.requestId,
htmlRequestId: workStore.htmlRequestId,
route: workStore.route,
},
{
url: metric.url,
method: metric.method,
statusCode: metric.status,
startTime: metric.start,
durationMs: metric.end - metric.start,
cacheStatus: metric.cacheStatus,
cacheReason: metric.cacheReason,
index: metric.idx,
}
)
}
if (!workStore.shouldTrackFetchMetrics) { if (!workStore.shouldTrackFetchMetrics) {
return return
} }
workStore.fetchMetrics ??= [] workStore.fetchMetrics ??= []
workStore.fetchMetrics.push({ workStore.fetchMetrics.push(metric)
...ctx,
end: performance.timeOrigin + performance.now(),
idx: workStore.nextFetchId || 0,
})
} }
async function createCachedPrerenderResponse( async function createCachedPrerenderResponse(
...@@ -315,7 +350,7 @@ export function createPatchedFetcher( ...@@ -315,7 +350,7 @@ export function createPatchedFetcher(
'net.peer.port': url?.port || undefined, 'net.peer.port': url?.port || undefined,
}, },
}, },
async () => { async (span) => {
// If this is an internal fetch, we should not do any special treatment. // If this is an internal fetch, we should not do any special treatment.
if (isInternal) { if (isInternal) {
return originFetch(input, init) return originFetch(input, init)
...@@ -847,7 +882,7 @@ export function createPatchedFetcher( ...@@ -847,7 +882,7 @@ export function createPatchedFetcher(
return originFetch(input, clonedInit) return originFetch(input, clonedInit)
.then(async (res) => { .then(async (res) => {
if (!isStale && fetchStart) { if (!isStale && fetchStart) {
trackFetchMetric(workStore, { trackFetchMetric(workStore, span, {
start: fetchStart, start: fetchStart,
url: fetchUrl, url: fetchUrl,
cacheReason: cacheReasonOverride || cacheReason, cacheReason: cacheReasonOverride || cacheReason,
...@@ -1059,7 +1094,7 @@ export function createPatchedFetcher( ...@@ -1059,7 +1094,7 @@ export function createPatchedFetcher(
if (cachedFetchData) { if (cachedFetchData) {
if (fetchStart) { if (fetchStart) {
trackFetchMetric(workStore, { trackFetchMetric(workStore, span, {
start: fetchStart, start: fetchStart,
url: fetchUrl, url: fetchUrl,
cacheReason, cacheReason,
......
...@@ -6,10 +6,10 @@ import { runInNewContext } from 'node:vm' ...@@ -6,10 +6,10 @@ 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 { clearSpanStoreForTest, getSpanRecords } from './span-store' import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store'
const originalLocalSpans = process.env.NEXT_OTEL_LOCAL_SPANS
const originalDevServer = process.env.__NEXT_DEV_SERVER const originalDevServer = process.env.__NEXT_DEV_SERVER
const spanRecords: SpanStoreRecord[] = []
setFlagsFromString('--expose-gc') setFlagsFromString('--expose-gc')
const forceGarbageCollection = runInNewContext('gc') as () => void const forceGarbageCollection = runInNewContext('gc') as () => void
...@@ -17,24 +17,20 @@ const forceGarbageCollection = runInNewContext('gc') as () => void ...@@ -17,24 +17,20 @@ const forceGarbageCollection = runInNewContext('gc') as () => void
describe('local recording span', () => { describe('local recording span', () => {
beforeEach(() => { beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1' process.env.__NEXT_DEV_SERVER = '1'
setSpanRecorderForTest((span) => spanRecords.push(span))
}) })
afterEach(() => { afterEach(() => {
if (originalLocalSpans === undefined) {
delete process.env.NEXT_OTEL_LOCAL_SPANS
} else {
process.env.NEXT_OTEL_LOCAL_SPANS = originalLocalSpans
}
if (originalDevServer === undefined) { if (originalDevServer === undefined) {
delete process.env.__NEXT_DEV_SERVER delete process.env.__NEXT_DEV_SERVER
} else { } else {
process.env.__NEXT_DEV_SERVER = originalDevServer process.env.__NEXT_DEV_SERVER = originalDevServer
} }
clearSpanStoreForTest() setSpanRecorderForTest(undefined)
spanRecords.length = 0
}) })
it('records a snapshot exactly once when the span ends', () => { it('records a snapshot exactly once when the span ends', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({ const span = createLocalSpan({
name: 'test.local-span', name: 'test.local-span',
traceId: '0123456789abcdef0123456789abcdef', traceId: '0123456789abcdef0123456789abcdef',
...@@ -46,14 +42,14 @@ describe('local recording span', () => { ...@@ -46,14 +42,14 @@ describe('local recording span', () => {
span.setAttribute('next.route', '/dashboard') span.setAttribute('next.route', '/dashboard')
expect(span.isRecording()).toBe(true) expect(span.isRecording()).toBe(true)
expect(getSpanRecords()).toEqual([]) expect(spanRecords).toEqual([])
span.end() span.end()
span.setAttribute('next.after_end', true) span.setAttribute('next.after_end', true)
span.end() span.end()
expect(span.isRecording()).toBe(false) expect(span.isRecording()).toBe(false)
expect(getSpanRecords()).toEqual([ expect(spanRecords).toEqual([
expect.objectContaining({ expect.objectContaining({
name: 'test.local-span', name: 'test.local-span',
traceId: '0123456789abcdef0123456789abcdef', traceId: '0123456789abcdef0123456789abcdef',
...@@ -69,7 +65,6 @@ describe('local recording span', () => { ...@@ -69,7 +65,6 @@ describe('local recording span', () => {
}) })
it('ignores undefined values when setting attributes', () => { it('ignores undefined values when setting attributes', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({ const span = createLocalSpan({
name: 'test.local-span.attributes', name: 'test.local-span.attributes',
attributes: { 'next.phase': 'render' }, attributes: { 'next.phase': 'render' },
...@@ -81,7 +76,7 @@ describe('local recording span', () => { ...@@ -81,7 +76,7 @@ describe('local recording span', () => {
}) })
span.end() span.end()
expect(getSpanRecords()).toEqual([ expect(spanRecords).toEqual([
expect.objectContaining({ expect.objectContaining({
attributes: { attributes: {
'next.phase': 'render', 'next.phase': 'render',
...@@ -92,7 +87,6 @@ describe('local recording span', () => { ...@@ -92,7 +87,6 @@ describe('local recording span', () => {
}) })
it('captures status, exception, and event mutations before ending', () => { it('captures status, exception, and event mutations before ending', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const span = createLocalSpan({ name: 'test.local-span.error' }) const span = createLocalSpan({ name: 'test.local-span.error' })
span.addEvent('test.event', { 'next.phase': 'render' }) span.addEvent('test.event', { 'next.phase': 'render' })
...@@ -100,7 +94,7 @@ describe('local recording span', () => { ...@@ -100,7 +94,7 @@ describe('local recording span', () => {
span.setStatus({ code: SpanStatusCode.ERROR, message: 'failed' }) span.setStatus({ code: SpanStatusCode.ERROR, message: 'failed' })
span.end() span.end()
expect(getSpanRecords()).toEqual([ expect(spanRecords).toEqual([
expect.objectContaining({ expect.objectContaining({
name: 'test.local-span.error', name: 'test.local-span.error',
status: 'error', status: 'error',
...@@ -126,10 +120,9 @@ describe('local recording span', () => { ...@@ -126,10 +120,9 @@ describe('local recording span', () => {
}) })
it('releases heavy references after ending while the span remains reachable', async () => { it('releases heavy references after ending while the span remains reachable', async () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const { span, delegateRef, attributeRef } = createEndedSpanWithReferences() const { span, delegateRef, attributeRef } = createEndedSpanWithReferences()
clearSpanStoreForTest() spanRecords.length = 0
await expectCollected(delegateRef) await expectCollected(delegateRef)
await expectCollected(attributeRef) await expectCollected(attributeRef)
......
...@@ -6,14 +6,14 @@ import type { ...@@ -6,14 +6,14 @@ import type {
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api' import { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'
import { import {
isLocalSpanStoreEnabled, isLocalSpanRecordingEnabled,
recordSpan, recordSpan,
type SpanStoreAttributes, type SpanStoreAttributes,
type SpanStoreEvent, type SpanStoreEvent,
type SpanStoreLink, type SpanStoreLink,
} from './span-store' } from './span-store'
export { isLocalSpanStoreEnabled } from './span-store' export { isLocalSpanRecordingEnabled } from './span-store'
const TRACE_ID_HEX_LENGTH = 32 const TRACE_ID_HEX_LENGTH = 32
const SPAN_ID_HEX_LENGTH = 16 const SPAN_ID_HEX_LENGTH = 16
...@@ -75,7 +75,7 @@ export type LocalSpanRecorder = { ...@@ -75,7 +75,7 @@ export type LocalSpanRecorder = {
createLocalSpan: typeof createLocalSpan createLocalSpan: typeof createLocalSpan
getActiveLocalSpan: typeof getActiveLocalSpan getActiveLocalSpan: typeof getActiveLocalSpan
isLocalRecordingSpan: typeof isLocalRecordingSpan isLocalRecordingSpan: typeof isLocalRecordingSpan
isLocalSpanStoreEnabled: typeof isLocalSpanStoreEnabled isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled
withLocalSpan: typeof withLocalSpan withLocalSpan: typeof withLocalSpan
} }
...@@ -89,7 +89,7 @@ export function registerLocalSpanRecorder(): void { ...@@ -89,7 +89,7 @@ export function registerLocalSpanRecorder(): void {
createLocalSpan, createLocalSpan,
getActiveLocalSpan, getActiveLocalSpan,
isLocalRecordingSpan, isLocalRecordingSpan,
isLocalSpanStoreEnabled, isLocalSpanRecordingEnabled,
withLocalSpan, withLocalSpan,
} }
} }
......
import {
clearRequestInsightsForTest,
getRequestInsightsSnapshot,
recordRequestInsightFetch,
subscribeRequestInsights,
} from './request-insights'
import { recordSpan } from './span-store'
const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS
const originalDevServer = process.env.__NEXT_DEV_SERVER
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) {
delete process.env[name]
} else {
process.env[name] = value
}
}
describe('request insights', () => {
beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1'
})
afterEach(() => {
restoreEnv('__NEXT_REQUEST_INSIGHTS', originalRequestInsights)
restoreEnv('__NEXT_DEV_SERVER', originalDevServer)
clearRequestInsightsForTest()
})
it('derives request history from local span records', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
recordSpan({
name: 'render route (app) /products/[id]',
startTime: 100,
durationMs: 50,
status: 'ok',
traceId: 'trace_1',
spanId: 'span_1',
requestId: 'req_1',
htmlRequestId: 'html_1',
route: '/products/[id]',
attributes: {
'next.span_type': 'AppRender.getBodyResult',
},
events: [
{
name: 'metadata ready',
timestamp: 130,
},
],
links: [
{
traceId: 'linked_trace',
spanId: 'linked_span',
},
],
})
recordSpan({
name: 'fetch GET https://example.vercel.sh/',
startTime: 120,
durationMs: 25,
status: 'ok',
requestId: 'req_1',
htmlRequestId: 'html_1',
route: '/products/[id]',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url': 'https://example.vercel.sh/',
'http.method': 'GET',
'http.status_code': 200,
'next.fetch.idx': 1,
'next.fetch.cache_status': 'skip',
'next.fetch.cache_reason': 'cache: no-store',
},
})
expect(getRequestInsightsSnapshot()).toEqual({
requests: [
expect.objectContaining({
requestId: 'req_1',
htmlRequestId: 'html_1',
route: '/products/[id]',
durationMs: 50,
status: 'ok',
spans: expect.arrayContaining([
expect.objectContaining({
name: 'fetch GET https://example.vercel.sh/',
}),
expect.objectContaining({
traceId: 'trace_1',
spanId: 'span_1',
events: [
{
name: 'metadata ready',
timestamp: 130,
},
],
links: [
{
traceId: 'linked_trace',
spanId: 'linked_span',
},
],
}),
]),
fetches: [
{
url: 'https://example.vercel.sh/',
method: 'GET',
statusCode: 200,
startTime: 120,
durationMs: 25,
cacheStatus: 'skip',
cacheReason: 'cache: no-store',
index: 1,
},
],
}),
],
})
})
it('notifies subscribers when a request insight changes', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const listener = jest.fn()
const unsubscribe = subscribeRequestInsights(listener)
recordSpan({
name: 'render route (app) /dashboard',
requestId: 'req_2',
htmlRequestId: 'html_2',
route: '/dashboard',
})
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
requestId: 'req_2',
htmlRequestId: 'html_2',
route: '/dashboard',
})
)
unsubscribe()
})
it('records request fetch metrics when the OTel fetch span does not complete locally', () => {
recordRequestInsightFetch(
{
requestId: 'req_3',
htmlRequestId: 'html_3',
route: '/reports',
},
{
url: 'https://example.vercel.sh/api',
method: 'GET',
statusCode: 200,
startTime: 200,
durationMs: 75,
cacheStatus: 'miss',
index: 1,
}
)
expect(getRequestInsightsSnapshot()).toEqual({
requests: [
expect.objectContaining({
requestId: 'req_3',
htmlRequestId: 'html_3',
route: '/reports',
durationMs: 75,
fetches: [
expect.objectContaining({
url: 'https://example.vercel.sh/api',
startTime: 200,
durationMs: 75,
cacheStatus: 'miss',
}),
],
}),
],
})
})
it('redacts sensitive request insight payload fields', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
recordSpan({
name: 'fetch GET https://example.vercel.sh/api',
startTime: 100,
durationMs: 10,
requestId: 'req_4',
route: '/account',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://user:pass@example.vercel.sh/api?access_token=abc&delay=1&signature=sig',
'http.method': 'GET',
'custom.secret': 'should not be exposed',
},
events: [
{
name: 'fetch start',
timestamp: 100,
attributes: {
'next.span_type': 'AppRender.fetch',
'custom.secret': 'should not be exposed',
},
},
],
links: [
{
traceId: 'linked_trace',
spanId: 'linked_span',
attributes: {
'custom.secret': 'should not be exposed',
},
},
],
})
recordRequestInsightFetch(
{
requestId: 'req_4',
route: '/account',
},
{
url: 'https://example.vercel.sh/api?token=abc&keep=1',
startTime: 120,
durationMs: 5,
}
)
expect(getRequestInsightsSnapshot().requests[0]).toEqual(
expect.objectContaining({
spans: [
expect.objectContaining({
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
'http.method': 'GET',
},
events: [
{
name: 'fetch start',
timestamp: 100,
attributes: {
'next.span_type': 'AppRender.fetch',
},
},
],
links: [
{
traceId: 'linked_trace',
spanId: 'linked_span',
attributes: undefined,
},
],
}),
],
fetches: [
expect.objectContaining({
url: 'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
}),
expect.objectContaining({
url: 'https://example.vercel.sh/api?token=redacted&keep=1',
}),
],
})
)
})
})
import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'
import type {
RequestInsight,
RequestInsightFetch,
RequestInsightsSnapshot,
} from '../../../next-devtools/shared/request-insights'
import type { SpanStoreRecord } from './span-store'
export { isRequestInsightsEnabled } from './span-store'
const MAX_REQUEST_INSIGHTS = 100
const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')
type RequestInsightsListener = (insight: RequestInsight) => void
type RequestInsightIdentity = {
requestId?: string
htmlRequestId?: string
route?: string
url?: string
}
const REDACTED_VALUE = 'redacted'
const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([
'http.method',
'http.route',
'http.status_code',
'http.url',
'net.peer.name',
'net.peer.port',
'next.fetch.cache_reason',
'next.fetch.cache_status',
'next.fetch.idx',
'next.route',
'next.rsc',
'next.segment',
'next.span_name',
'next.span_type',
])
const SENSITIVE_PARAM_NAME_RE =
/(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i
class InMemoryRequestInsightsStore {
private readonly requests = new Map<string, RequestInsight>()
private readonly requestOrder: string[] = []
private readonly listeners = new Set<RequestInsightsListener>()
recordSpan(span: SpanStoreRecord): void {
if (!span.requestId) {
return
}
const insight = this.getOrCreateRequest(
span,
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.route = insight.route ?? span.route
insight.url = insight.url ?? sanitizeUrl(span.url)
insight.startTime = Math.min(insight.startTime, spanStartTime)
insight.durationMs =
Math.max(requestEndTime, spanEndTime) - insight.startTime
insight.status =
insight.status === 'error' || span.status === 'error'
? 'error'
: span.status === 'ok'
? 'ok'
: insight.status
insight.spans.push({
name: span.name,
startTime: spanStartTime,
durationMs: span.durationMs,
status: span.status,
traceId: span.traceId,
spanId: span.spanId,
parentSpanId: span.parentSpanId,
attributes: sanitizeSpanAttributes(span.attributes),
links: sanitizeSpanLinks(span.links),
events: sanitizeSpanEvents(span.events),
error: span.error,
})
const fetch = getFetchInsight(span)
if (fetch) {
this.recordFetchForInsight(insight, fetch)
}
this.notify(insight)
}
recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {
if (!identity.requestId) {
return
}
const fetchStartTime = fetch.startTime ?? Date.now()
const insight = this.getOrCreateRequest(identity, fetchStartTime)
const fetchEndTime = fetch.durationMs
? 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.notify(insight)
}
getSnapshot(): RequestInsightsSnapshot {
return {
requests: this.requestOrder
.map((requestId) => this.requests.get(requestId))
.filter((request): request is RequestInsight => request !== undefined),
}
}
subscribe(listener: RequestInsightsListener): () => void {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
clear(): void {
this.requests.clear()
this.requestOrder.length = 0
}
private notify(insight: RequestInsight): void {
for (const listener of this.listeners) {
listener(insight)
}
}
private getOrCreateRequest(
identity: RequestInsightIdentity,
startTime: number
): RequestInsight {
const requestId = identity.requestId!
let insight = this.requests.get(requestId)
if (!insight) {
insight = {
requestId,
htmlRequestId: identity.htmlRequestId ?? requestId,
route: identity.route,
url: sanitizeUrl(identity.url),
startTime,
status: 'pending',
spans: [],
fetches: [],
}
this.requests.set(requestId, insight)
this.requestOrder.push(requestId)
this.trim()
}
insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId
insight.route = insight.route ?? identity.route
insight.url = insight.url ?? sanitizeUrl(identity.url)
insight.startTime = Math.min(insight.startTime, startTime)
return insight
}
private recordFetchForInsight(
insight: RequestInsight,
fetch: RequestInsightFetch
): void {
if (
insight.fetches.some(
(existingFetch) =>
existingFetch.url === fetch.url &&
(existingFetch.index !== undefined && fetch.index !== undefined
? existingFetch.index === fetch.index
: existingFetch.startTime === fetch.startTime)
)
) {
return
}
insight.fetches.push(sanitizeFetchInsight(fetch))
}
private trim(): void {
while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {
const requestId = this.requestOrder.shift()
if (requestId) {
this.requests.delete(requestId)
}
}
}
}
export function recordRequestInsightSpan(span: SpanStoreRecord): void {
getRequestInsightsStore().recordSpan(span)
}
export function recordRequestInsightFetch(
identity: RequestInsightIdentity,
fetch: RequestInsightFetch
): void {
getRequestInsightsStore().recordFetch(identity, fetch)
}
export function getRequestInsightsSnapshot(): RequestInsightsSnapshot {
return getRequestInsightsStore().getSnapshot()
}
export function subscribeRequestInsights(
listener: RequestInsightsListener
): () => void {
return getRequestInsightsStore().subscribe(listener)
}
export function clearRequestInsightsForTest(): void {
getRequestInsightsStore().clear()
}
function getRequestInsightsStore(): InMemoryRequestInsightsStore {
const globalStore = globalThis as typeof globalThis & {
[REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore
}
return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=
new InMemoryRequestInsightsStore())
}
function getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {
const attributes = span.attributes
if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {
return null
}
return {
url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),
method: getStringAttribute(attributes['http.method']),
statusCode: getNumberAttribute(attributes['http.status_code']),
startTime: span.startTime ?? span.timestamp,
durationMs: span.durationMs,
cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),
cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),
index: getNumberAttribute(attributes['next.fetch.idx']),
}
}
function sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {
return {
...fetch,
url: sanitizeUrl(fetch.url),
}
}
function sanitizeSpanAttributes(
attributes: SpanStoreRecord['attributes']
): SpanStoreRecord['attributes'] {
if (!attributes) {
return undefined
}
const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}
for (const [key, value] of Object.entries(attributes)) {
if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {
continue
}
sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value
}
return Object.keys(sanitized).length > 0 ? sanitized : undefined
}
function sanitizeSpanEvents(
events: SpanStoreRecord['events']
): SpanStoreRecord['events'] {
return events?.map((event) => ({
...event,
attributes: sanitizeSpanAttributes(event.attributes),
}))
}
function sanitizeSpanLinks(
links: SpanStoreRecord['links']
): SpanStoreRecord['links'] {
return links?.map((link) => ({
...link,
attributes: sanitizeSpanAttributes(link.attributes),
}))
}
function sanitizeUrlAttribute(value: AttributeValue): AttributeValue {
return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value
}
function sanitizeUrl(value: string | undefined): string | undefined {
if (!value) {
return value
}
const isRelativeUrl = value.startsWith('/')
try {
const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)
url.username = ''
url.password = ''
for (const name of Array.from(url.searchParams.keys())) {
if (SENSITIVE_PARAM_NAME_RE.test(name)) {
url.searchParams.set(name, REDACTED_VALUE)
}
}
return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href
} catch {
return value
}
}
function getStringAttribute(value: AttributeValue | undefined) {
return typeof value === 'string' ? value : undefined
}
function getNumberAttribute(value: AttributeValue | undefined) {
return typeof value === 'number' ? value : undefined
}
import { runInNewContext } from 'node:vm'
import { setFlagsFromString } from 'node:v8'
import { import {
clearSpanStoreForTest, clearRequestInsightsForTest,
getSpanRecords, getRequestInsightsSnapshot,
InMemorySpanStore, } from './request-insights'
isLocalSpanStoreEnabled, import {
isLocalSpanRecordingEnabled,
isRequestInsightsEnabled, isRequestInsightsEnabled,
recordSpan, recordSpan,
setSpanRecorderForTest,
type SpanStoreRecord,
} from './span-store' } from './span-store'
const originalLocalSpans = process.env.NEXT_OTEL_LOCAL_SPANS
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
setFlagsFromString('--expose-gc')
const forceGarbageCollection = runInNewContext('gc') as () => void
function restoreEnv(name: string, value: string | undefined) { function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) { if (value === undefined) {
delete process.env[name] delete process.env[name]
...@@ -24,183 +21,86 @@ function restoreEnv(name: string, value: string | undefined) { ...@@ -24,183 +21,86 @@ function restoreEnv(name: string, value: string | undefined) {
} }
} }
describe('span store', () => { describe('span recording', () => {
beforeEach(() => { beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1' process.env.__NEXT_DEV_SERVER = '1'
delete process.env.__NEXT_REQUEST_INSIGHTS
}) })
afterEach(() => { afterEach(() => {
restoreEnv('NEXT_OTEL_LOCAL_SPANS', originalLocalSpans)
restoreEnv('__NEXT_REQUEST_INSIGHTS', originalRequestInsights) restoreEnv('__NEXT_REQUEST_INSIGHTS', originalRequestInsights)
restoreEnv('__NEXT_DEV_SERVER', originalDevServer) restoreEnv('__NEXT_DEV_SERVER', originalDevServer)
clearSpanStoreForTest() setSpanRecorderForTest(undefined)
clearRequestInsightsForTest()
}) })
it('keeps bounded in-memory records with OTel-compatible identity fields and links', () => { it('records completed spans only when there is a consumer', () => {
const traceStore = new InMemorySpanStore({ maxRecords: 2 }) const records: SpanStoreRecord[] = []
traceStore.record({ expect(isLocalSpanRecordingEnabled()).toBe(false)
name: 'next.cache_component.produce', recordSpan({ name: 'test.unconsumed' })
traceId: '00000000000000000000000000000001', expect(records).toEqual([])
spanId: '0000000000000001',
route: '/products/[id]',
attributes: {
'next.phase': 'build',
'next.artifact.kind': 'ppr-shell',
},
})
traceStore.record({ setSpanRecorderForTest((span) => records.push(span))
name: 'next.cache_component.consume', expect(isLocalSpanRecordingEnabled()).toBe(true)
traceId: '00000000000000000000000000000002', recordSpan({
spanId: '0000000000000002', name: 'test.consumed',
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: { attributes: {
'next.cache.status': 'miss', 'next.phase': 'render',
}, },
}) })
expect(traceStore.getRecords()).toHaveLength(2) expect(records).toEqual([
expect(traceStore.getRecords({ requestId: 'req_1' })).toEqual([
expect.objectContaining({ expect.objectContaining({
name: 'next.cache_component.consume', name: 'test.consumed',
requestId: 'req_1', timestamp: expect.any(Number),
route: '/products/[id]', attributes: {
attributes: expect.objectContaining({ 'next.phase': 'render',
'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 () => { it('forwards request spans directly to request insights', () => {
const { traceStore, attributeRef } = createStoreWithEvictedAttribute() process.env.__NEXT_REQUEST_INSIGHTS = 'true'
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({ recordSpan({
name: 'next.cache_component.consume', name: 'render route (app) /dashboard',
startTime: 100,
durationMs: 25,
status: 'ok',
requestId: 'req_1', requestId: 'req_1',
route: '/dashboard',
}) })
expect(getSpanRecords()).toEqual([]) expect(getRequestInsightsSnapshot()).toEqual({
requests: [
process.env.NEXT_OTEL_LOCAL_SPANS = '1' expect.objectContaining({
recordSpan({ requestId: 'req_1',
name: 'next.cache_component.consume', route: '/dashboard',
requestId: 'req_1', spans: [
attributes: { expect.objectContaining({
'next.cache.status': 'hit', name: 'render route (app) /dashboard',
}, startTime: 100,
durationMs: 25,
}),
],
}),
],
}) })
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', () => { it('does not record spans outside the dev server', () => {
const recorder = jest.fn()
delete process.env.__NEXT_DEV_SERVER delete process.env.__NEXT_DEV_SERVER
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
process.env.__NEXT_REQUEST_INSIGHTS = 'true' process.env.__NEXT_REQUEST_INSIGHTS = 'true'
setSpanRecorderForTest(recorder)
expect(isLocalSpanStoreEnabled()).toBe(false) expect(isLocalSpanRecordingEnabled()).toBe(false)
recordSpan({ name: 'test.production' }) recordSpan({ name: 'test.production', requestId: 'req_2' })
expect(getSpanRecords()).toEqual([]) expect(recorder).not.toHaveBeenCalled()
}) expect(getRequestInsightsSnapshot()).toEqual({ requests: [] })
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', () => { it('treats boolean define-env request insights values as enabled', () => {
...@@ -209,26 +109,3 @@ describe('span store', () => { ...@@ -209,26 +109,3 @@ describe('span store', () => {
expect(isRequestInsightsEnabled()).toBe(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()
}
...@@ -36,80 +36,41 @@ export type SpanStoreRecord = { ...@@ -36,80 +36,41 @@ export type SpanStoreRecord = {
} }
} }
export type SpanStoreFilter = { type SpanRecorderForTest = (span: SpanStoreRecord) => void
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 { let spanRecorderForTest: SpanRecorderForTest | undefined
private readonly maxRecords: number
private records: SpanStoreRecord[] = []
constructor(options: InMemorySpanStoreOptions = {}) { export function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {
this.maxRecords = options.maxRecords ?? DEFAULT_MAX_RECORDS if (!isLocalSpanRecordingEnabled()) {
} return
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[] { const spanRecord: SpanStoreRecord = {
return this.records.filter( timestamp: Date.now(),
(record) => ...record,
(filter.requestId === undefined ||
record.requestId === filter.requestId) &&
(filter.route === undefined || record.route === filter.route) &&
(filter.name === undefined || record.name === filter.name)
)
} }
clear(): void { spanRecorderForTest?.(spanRecord)
this.records = []
}
}
export function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void { if (isRequestInsightsEnabled() && spanRecord.requestId) {
if (!isLocalSpanStoreEnabled()) { const { recordRequestInsightSpan } =
return require('./request-insights') as typeof import('./request-insights')
recordRequestInsightSpan(spanRecord)
} }
getLocalSpanStore().record(record)
} }
export function getSpanRecords(filter?: SpanStoreFilter): SpanStoreRecord[] { export function setSpanRecorderForTest(
return getLocalSpanStore().getRecords(filter) recorder: SpanRecorderForTest | undefined
): void {
spanRecorderForTest = recorder
} }
export function clearSpanStoreForTest(): void { export function isLocalSpanRecordingEnabled(): boolean {
getLocalSpanStore().clear()
}
export function isLocalSpanStoreEnabled(): boolean {
if (!process.env.__NEXT_DEV_SERVER) { if (!process.env.__NEXT_DEV_SERVER) {
return false return false
} }
const value = process.env.NEXT_OTEL_LOCAL_SPANS return spanRecorderForTest !== undefined || isRequestInsightsEnabled()
return isEnabledEnvValue(value) || isRequestInsightsEnabled()
} }
export function isRequestInsightsEnabled(): boolean { export function isRequestInsightsEnabled(): boolean {
...@@ -120,11 +81,3 @@ export function isRequestInsightsEnabled(): boolean { ...@@ -120,11 +81,3 @@ export function isRequestInsightsEnabled(): boolean {
function isEnabledEnvValue(value: string | undefined): boolean { function isEnabledEnvValue(value: string | undefined): boolean {
return value === '1' || value === 'true' || (value as unknown) === true 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())
}
...@@ -18,14 +18,21 @@ import { ...@@ -18,14 +18,21 @@ import {
trace, trace,
} from '@opentelemetry/api' } from '@opentelemetry/api'
import { clearSpanStoreForTest, getSpanRecords } 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, 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 originalLocalSpans = process.env.NEXT_OTEL_LOCAL_SPANS const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS
const originalDevServer = process.env.__NEXT_DEV_SERVER const originalDevServer = process.env.__NEXT_DEV_SERVER
const spanRecords: SpanStoreRecord[] = []
function getSpanRecords(filter: { name?: string } = {}): SpanStoreRecord[] {
return spanRecords.filter(
(span) => filter.name === undefined || span.name === filter.name
)
}
const getter: TextMapGetter<Record<string, string | undefined>> = { const getter: TextMapGetter<Record<string, string | undefined>> = {
keys: (carrier) => Object.keys(carrier), keys: (carrier) => Object.keys(carrier),
...@@ -144,17 +151,19 @@ describe('withPropagatedContext', () => { ...@@ -144,17 +151,19 @@ describe('withPropagatedContext', () => {
}) })
}) })
describe('local span store sink', () => { describe('local span recording', () => {
beforeEach(() => { beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1' process.env.__NEXT_DEV_SERVER = '1'
delete process.env.__NEXT_REQUEST_INSIGHTS
setSpanRecorderForTest((span) => spanRecords.push(span))
registerLocalSpanRecorder() registerLocalSpanRecorder()
}) })
afterEach(() => { afterEach(() => {
if (originalLocalSpans === undefined) { if (originalRequestInsights === undefined) {
delete process.env.NEXT_OTEL_LOCAL_SPANS delete process.env.__NEXT_REQUEST_INSIGHTS
} else { } else {
process.env.NEXT_OTEL_LOCAL_SPANS = originalLocalSpans process.env.__NEXT_REQUEST_INSIGHTS = originalRequestInsights
} }
if (originalDevServer === undefined) { if (originalDevServer === undefined) {
delete process.env.__NEXT_DEV_SERVER delete process.env.__NEXT_DEV_SERVER
...@@ -162,11 +171,12 @@ describe('local span store sink', () => { ...@@ -162,11 +171,12 @@ describe('local span store sink', () => {
process.env.__NEXT_DEV_SERVER = originalDevServer process.env.__NEXT_DEV_SERVER = originalDevServer
} }
trace.disable() trace.disable()
clearSpanStoreForTest() setSpanRecorderForTest(undefined)
spanRecords.length = 0
}) })
it('does not mirror spans by default', () => { it('does not mirror spans by default', () => {
delete process.env.NEXT_OTEL_LOCAL_SPANS setSpanRecorderForTest(undefined)
const result = getTracer().trace(NodeSpan.runHandler, () => 'result') const result = getTracer().trace(NodeSpan.runHandler, () => 'result')
...@@ -176,7 +186,6 @@ describe('local span store sink', () => { ...@@ -176,7 +186,6 @@ describe('local span store sink', () => {
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
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
let receivedSpan: unknown = 'not-called' let receivedSpan: unknown = 'not-called'
const result = getTracer().trace(NodeSpan.runHandler, (span) => { const result = getTracer().trace(NodeSpan.runHandler, (span) => {
...@@ -190,8 +199,6 @@ describe('local span store sink', () => { ...@@ -190,8 +199,6 @@ describe('local span store sink', () => {
}) })
it('records sync trace calls without an OTel provider', () => { it('records sync trace calls without an OTel provider', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = getTracer().trace( const result = getTracer().trace(
NodeSpan.runHandler, NodeSpan.runHandler,
{ {
...@@ -222,8 +229,6 @@ describe('local span store sink', () => { ...@@ -222,8 +229,6 @@ describe('local span store sink', () => {
}) })
it('records app render fetch spans without an OTel provider', async () => { it('records app render fetch spans without an OTel provider', async () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = await getTracer().trace( const result = await getTracer().trace(
AppRenderSpan.fetch, AppRenderSpan.fetch,
{ {
...@@ -257,8 +262,6 @@ describe('local span store sink', () => { ...@@ -257,8 +262,6 @@ describe('local span store sink', () => {
}) })
it('mirrors span mutations made through the OTel span API', () => { it('mirrors span mutations made through the OTel span API', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = getTracer().trace( const result = getTracer().trace(
NodeSpan.runHandler, NodeSpan.runHandler,
{ spanName: 'test.mutated' }, { spanName: 'test.mutated' },
...@@ -297,8 +300,6 @@ describe('local span store sink', () => { ...@@ -297,8 +300,6 @@ describe('local span store sink', () => {
}) })
it('mirrors span status without a thrown error', () => { it('mirrors span status without a thrown error', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = getTracer().trace( const result = getTracer().trace(
NodeSpan.runHandler, NodeSpan.runHandler,
{ spanName: 'test.status' }, { spanName: 'test.status' },
...@@ -324,8 +325,6 @@ describe('local span store sink', () => { ...@@ -324,8 +325,6 @@ describe('local span store sink', () => {
}) })
it('records async trace calls when the returned promise settles', async () => { it('records async trace calls when the returned promise settles', async () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = await getTracer().trace( const result = await getTracer().trace(
NodeSpan.runHandler, NodeSpan.runHandler,
{ spanName: 'test.async' }, { spanName: 'test.async' },
...@@ -346,8 +345,6 @@ describe('local span store sink', () => { ...@@ -346,8 +345,6 @@ describe('local span store sink', () => {
}) })
it('records callback trace calls when done is called', () => { it('records callback trace calls when done is called', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const result = getTracer().trace( const result = getTracer().trace(
NodeSpan.runHandler, NodeSpan.runHandler,
{ spanName: 'test.callback' }, { spanName: 'test.callback' },
...@@ -368,8 +365,6 @@ describe('local span store sink', () => { ...@@ -368,8 +365,6 @@ describe('local span store sink', () => {
}) })
it('records callback trace calls consistently with an OTel provider', () => { it('records callback trace calls consistently with an OTel provider', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const delegateSpan = trace.wrapSpanContext({ const delegateSpan = trace.wrapSpanContext({
traceId: '0123456789abcdef0123456789abcdef', traceId: '0123456789abcdef0123456789abcdef',
spanId: '0123456789abcdef', spanId: '0123456789abcdef',
...@@ -411,8 +406,6 @@ describe('local span store sink', () => { ...@@ -411,8 +406,6 @@ describe('local span store sink', () => {
}) })
it('records direct spans with active local parent identity', () => { it('records direct spans with active local parent identity', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
const parentSpan = getTracer().startSpan(NodeSpan.runHandler, { const parentSpan = getTracer().startSpan(NodeSpan.runHandler, {
attributes: { 'next.page': 'parent' }, attributes: { 'next.page': 'parent' },
}) })
...@@ -454,8 +447,6 @@ describe('local span store sink', () => { ...@@ -454,8 +447,6 @@ describe('local span store sink', () => {
}) })
it('records thrown errors before rethrowing', () => { it('records thrown errors before rethrowing', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
expect(() => expect(() =>
getTracer().trace(NodeSpan.runHandler, { spanName: 'test.error' }, () => { getTracer().trace(NodeSpan.runHandler, { spanName: 'test.error' }, () => {
throw new Error('boom') throw new Error('boom')
...@@ -475,10 +466,11 @@ describe('local span store sink', () => { ...@@ -475,10 +466,11 @@ describe('local span store sink', () => {
}) })
it('groups local spans by existing async storage without adding extra attributes', () => { it('groups local spans by existing async storage without adding extra attributes', () => {
process.env.NEXT_OTEL_LOCAL_SPANS = '1'
jest.isolateModules(() => { jest.isolateModules(() => {
const previousAsyncLocalStorage = (globalThis as any).AsyncLocalStorage const previousAsyncLocalStorage = (globalThis as any).AsyncLocalStorage
let setIsolatedSpanRecorderForTest:
| typeof setSpanRecorderForTest
| undefined
try { try {
const { AsyncLocalStorage } = const { AsyncLocalStorage } =
require('node:async_hooks') as typeof import('node:async_hooks') require('node:async_hooks') as typeof import('node:async_hooks')
...@@ -488,8 +480,9 @@ describe('local span store sink', () => { ...@@ -488,8 +480,9 @@ describe('local span store sink', () => {
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 { getSpanRecords: getIsolatedSpanRecords } = ;({ setSpanRecorderForTest: setIsolatedSpanRecorderForTest } =
require('./span-store') as typeof import('./span-store') require('./span-store') as typeof import('./span-store'))
setIsolatedSpanRecorderForTest((span) => spanRecords.push(span))
const { registerLocalSpanRecorder: registerIsolatedLocalSpanRecorder } = const { registerLocalSpanRecorder: registerIsolatedLocalSpanRecorder } =
require('./local-span-recorder') as typeof import('./local-span-recorder') require('./local-span-recorder') as typeof import('./local-span-recorder')
registerIsolatedLocalSpanRecorder() registerIsolatedLocalSpanRecorder()
...@@ -530,7 +523,7 @@ describe('local span store sink', () => { ...@@ -530,7 +523,7 @@ describe('local span store sink', () => {
}) })
) )
const records = getIsolatedSpanRecords() const records = getSpanRecords()
const traceIds = new Set(records.map((record) => record.traceId)) const traceIds = new Set(records.map((record) => record.traceId))
const outerRecord = records.find( const outerRecord = records.find(
(record) => record.name === 'test.als.outer' (record) => record.name === 'test.als.outer'
...@@ -562,6 +555,7 @@ describe('local span store sink', () => { ...@@ -562,6 +555,7 @@ describe('local span store sink', () => {
) )
).toBe(false) ).toBe(false)
} finally { } finally {
setIsolatedSpanRecorderForTest?.(undefined)
if (previousAsyncLocalStorage === undefined) { if (previousAsyncLocalStorage === undefined) {
delete (globalThis as any).AsyncLocalStorage delete (globalThis as any).AsyncLocalStorage
} else { } else {
......
...@@ -337,10 +337,10 @@ class NextTracerImpl implements NextTracer { ...@@ -337,10 +337,10 @@ 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 localSpanStoreEnabled = const localSpanRecordingEnabled =
getLocalSpanRecorder()?.isLocalSpanStoreEnabled() ?? false getLocalSpanRecorder()?.isLocalSpanRecordingEnabled() ?? false
if (!tracingEnabled && !localSpanStoreEnabled) { if (!tracingEnabled && !localSpanRecordingEnabled) {
return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty() return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty()
} }
...@@ -403,7 +403,7 @@ class NextTracerImpl implements NextTracer { ...@@ -403,7 +403,7 @@ class NextTracerImpl implements NextTracer {
options, options,
spanContext, spanContext,
tracingEnabled, tracingEnabled,
localSpanStoreEnabled, localSpanRecordingEnabled,
(span: Span) => { (span: Span) => {
let startTime: number | undefined let startTime: number | undefined
if ( if (
...@@ -503,7 +503,7 @@ class NextTracerImpl implements NextTracer { ...@@ -503,7 +503,7 @@ class NextTracerImpl implements NextTracer {
options: TracerSpanOptions, options: TracerSpanOptions,
parentContext: Context, parentContext: Context,
tracingEnabled: boolean, tracingEnabled: boolean,
localSpanStoreEnabled: boolean, localSpanRecordingEnabled: boolean,
fn: (span: Span) => T fn: (span: Span) => T
): T { ): T {
if (tracingEnabled) { if (tracingEnabled) {
...@@ -512,7 +512,7 @@ class NextTracerImpl implements NextTracer { ...@@ -512,7 +512,7 @@ class NextTracerImpl implements NextTracer {
options, options,
(span: Span) => (span: Span) =>
fn( fn(
localSpanStoreEnabled localSpanRecordingEnabled
? this.createLocalRecordingSpan( ? this.createLocalRecordingSpan(
spanName, spanName,
options, options,
...@@ -608,10 +608,10 @@ class NextTracerImpl implements NextTracer { ...@@ -608,10 +608,10 @@ class NextTracerImpl implements NextTracer {
const parentContext = const parentContext =
this.getSpanContext(options?.parentSpan ?? this.getActiveScopeSpan()) ?? this.getSpanContext(options?.parentSpan ?? this.getActiveScopeSpan()) ??
context.active() context.active()
const localSpanStoreEnabled = const localSpanRecordingEnabled =
getLocalSpanRecorder()?.isLocalSpanStoreEnabled() ?? false getLocalSpanRecorder()?.isLocalSpanRecordingEnabled() ?? false
if (!localSpanStoreEnabled) { if (!localSpanRecordingEnabled) {
return this.getTracerInstance().startSpan(type, options, parentContext) return this.getTracerInstance().startSpan(type, options, parentContext)
} }
......
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