Unverified Commit 300bf68f authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Fix Request Insights production tracing (#96000)

## Summary

I changed how the shared tracer accesses Request Insights from loading
the facade with a literal `require()` to reading the runtime already
registered globally by the development server. This prevents
`request-insights.js` and `request-insights-runtime.js` from appearing
in production NFT output, while keeping Request Insights behavior in
development unchanged.

I also changed the `expect.any(Function)` matcher to an existence
matcher plus an explicit `typeof` assertion so the repository's
banned-function-call checker passes without weakening the test.

This PR is stacked on #95897.

## Before: Tracer Owns Loading

- Production-used tracer
- Literal `require()`
- Request-insights facade
- Request-insights runtime
- NFT includes development modules

## After: Dev Server Owns Loading

- `next-dev-server` registers the runtime
- Global `Symbol` slot
- Tracer performs an optional lookup
- No runtime module import
- NFT excludes development modules

```js
// The production-used tracer now performs a lookup, not a load.
if (process.env.__NEXT_DEV_SERVER) {
  return globalThis[
    Symbol.for('@next/request-insights-runtime')
  ]
}
```

  ## Verification

- `pnpm exec jest packages/next/src/server/lib/trace/tracer.test.ts
packages/next/src/server/lib/trace/request-insights.test.ts
  --runInBand`
  - `pnpm --filter=next typescript`
  - `pnpm --filter=next types`
- `HEADLESS=true IS_TURBOPACK_TEST=1 TURBOPACK_BUILD=1
NEXT_TEST_MODE=start pnpm test-start-turbo
test/production/next-server-nft/
  next-server-nft.test.ts`
- `HEADLESS=true pnpm test-dev-turbo
test/development/app-dir/request-insights/request-insights.test.ts`
- `HEADLESS=true pnpm test-start-webpack
test/e2e/app-dir/app/standalone.test.ts`
  - `pnpm --filter=next build`

  <!-- NEXT_JS_LLM -->
parent 3b6f666f
...@@ -340,8 +340,9 @@ describe('request insights tracing', () => { ...@@ -340,8 +340,9 @@ describe('request insights tracing', () => {
expect(startActiveSpan).toHaveBeenCalledWith( expect(startActiveSpan).toHaveBeenCalledWith(
AppRenderSpan.fetch, AppRenderSpan.fetch,
expect.any(Object), expect.any(Object),
expect.any(Function) expect.anything()
) )
expect(typeof startActiveSpan.mock.calls[0].at(-1)).toBe('function')
expect(getRequestInsightsSnapshot().requests[0].operations).toEqual([]) expect(getRequestInsightsSnapshot().requests[0].operations).toEqual([])
}) })
......
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 { RequestInsightsRuntime } from './request-insights'
import { LogSpanAllowList, NextVanillaSpanAllowlist } from './constants' import { LogSpanAllowList, NextVanillaSpanAllowlist } from './constants'
import type { import type {
...@@ -14,15 +15,21 @@ import type { ...@@ -14,15 +15,21 @@ 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 REQUEST_INSIGHTS_RUNTIME_KEY = Symbol.for(
'@next/request-insights-runtime'
)
type GlobalWithRequestInsightsRuntime = typeof globalThis & {
[REQUEST_INSIGHTS_RUNTIME_KEY]?: RequestInsightsRuntime
}
let api: typeof import('next/dist/compiled/@opentelemetry/api') let api: typeof import('next/dist/compiled/@opentelemetry/api')
let requestInsightsFacade: typeof import('./request-insights') | undefined
function getRequestInsightsFacade() { function getRequestInsightsRuntime() {
if (process.env.__NEXT_DEV_SERVER) { if (process.env.__NEXT_DEV_SERVER) {
requestInsightsFacade ??= return (globalThis as GlobalWithRequestInsightsRuntime)[
require('./request-insights') as typeof import('./request-insights') REQUEST_INSIGHTS_RUNTIME_KEY
return requestInsightsFacade ]
} else { } else {
return undefined return undefined
} }
...@@ -277,7 +284,7 @@ class NextTracerImpl implements NextTracer { ...@@ -277,7 +284,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 {
const requestInsights = getRequestInsightsFacade() const requestInsights = getRequestInsightsRuntime()
const run = () => { const run = () => {
if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled()) { if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled()) {
return fn() return fn()
...@@ -285,8 +292,8 @@ class NextTracerImpl implements NextTracer { ...@@ -285,8 +292,8 @@ class NextTracerImpl implements NextTracer {
return context.with(ROOT_CONTEXT, fn) return context.with(ROOT_CONTEXT, fn)
} }
return requestInsights return requestInsights?.isActive()
? requestInsights.runWithDetachedRequestInsightContext(run) ? requestInsights.runDetached(run)
: run() : run()
} }
...@@ -350,10 +357,9 @@ class NextTracerImpl implements NextTracer { ...@@ -350,10 +357,9 @@ 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 requestInsights = getRequestInsightsFacade() const requestInsights = getRequestInsightsRuntime()
const openTelemetryEnabled = this.isOpenTelemetryEnabled() const openTelemetryEnabled = this.isOpenTelemetryEnabled()
const requestInsightsActive = const requestInsightsActive = requestInsights?.isActive() ?? false
requestInsights?.isRequestInsightsActive() ?? false
if ( if (
!NEXT_OTEL_PERFORMANCE_PREFIX && !NEXT_OTEL_PERFORMANCE_PREFIX &&
...@@ -392,7 +398,7 @@ class NextTracerImpl implements NextTracer { ...@@ -392,7 +398,7 @@ class NextTracerImpl implements NextTracer {
} }
const operation = requestInsightsActive const operation = requestInsightsActive
? requestInsights?.beginRequestInsightOperation({ ? requestInsights?.beginOperation({
type, type,
name: spanName, name: spanName,
category: 'nextjs', category: 'nextjs',
...@@ -437,7 +443,7 @@ class NextTracerImpl implements NextTracer { ...@@ -437,7 +443,7 @@ class NextTracerImpl implements NextTracer {
} }
} }
} finally { } finally {
requestInsights?.endRequestInsightOperation( requestInsights?.endOperation(
operation, operation,
failed ? { status: 'error', error } : { status: 'ok' } failed ? { status: 'error', error } : { status: 'ok' }
) )
...@@ -516,7 +522,7 @@ class NextTracerImpl implements NextTracer { ...@@ -516,7 +522,7 @@ class NextTracerImpl implements NextTracer {
} }
return requestInsights return requestInsights
? requestInsights.runWithRequestInsightOperation(operation, invoke) ? requestInsights.runWithOperation(operation, invoke)
: invoke() : invoke()
} }
......
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