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

request insights: expose dev snapshots to tools and HMR (3/5) (#93976)

## What

Adds the `experimental.requestInsights` flag, a private dev snapshot
endpoint, and HMR snapshot/update transport so running dev servers can
expose recent request insights to tools and browser clients.

Stack:

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

## Review Focus

- Dev-only gating for `experimental.requestInsights`.
- Private endpoint behavior when enabled and disabled.
- HMR snapshot/update shape and client-side retention.

## Proof In This PR

- `pnpm --filter=next types`
- Stack-tip Cache Components smoke verifies the endpoint and HMR-fed
overlay state against a running dev server.

## Deferred Coverage

- A dedicated isolated dev-server transport test can follow if reviewers
want cheaper per-PR coverage than the stack-tip smoke.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 510d00b5
...@@ -28,6 +28,8 @@ import { ...@@ -28,6 +28,8 @@ import {
ACTION_REFRESH, ACTION_REFRESH,
ACTION_RENDERING_INDICATOR_HIDE, ACTION_RENDERING_INDICATOR_HIDE,
ACTION_RENDERING_INDICATOR_SHOW, ACTION_RENDERING_INDICATOR_SHOW,
ACTION_REQUEST_INSIGHTS_SNAPSHOT,
ACTION_REQUEST_INSIGHTS_UPDATE,
ACTION_STATIC_INDICATOR, ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION, ACTION_UNHANDLED_REJECTION,
...@@ -88,6 +90,8 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) { ...@@ -88,6 +90,8 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_REFRESH: case ACTION_REFRESH:
case ACTION_RENDERING_INDICATOR_HIDE: case ACTION_RENDERING_INDICATOR_HIDE:
case ACTION_RENDERING_INDICATOR_SHOW: case ACTION_RENDERING_INDICATOR_SHOW:
case ACTION_REQUEST_INSIGHTS_SNAPSHOT:
case ACTION_REQUEST_INSIGHTS_UPDATE:
case ACTION_CACHE_INDICATOR: case ACTION_CACHE_INDICATOR:
case ACTION_INSTANT_ERRORS_CLEAR: case ACTION_INSTANT_ERRORS_CLEAR:
case ACTION_INSTANT_NAVS_TOGGLE: case ACTION_INSTANT_NAVS_TOGGLE:
......
...@@ -183,6 +183,8 @@ export function getDefineEnv({ ...@@ -183,6 +183,8 @@ export function getDefineEnv({
'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean( 'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean(
config.experimental.coldCacheBadge config.experimental.coldCacheBadge
), ),
'process.env.__NEXT_REQUEST_INSIGHTS':
dev && !!config.experimental.requestInsights,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true, 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,
......
...@@ -322,6 +322,8 @@ export function processMessage( ...@@ -322,6 +322,8 @@ export function processMessage(
dispatcher.onDevIndicator(message.devIndicator) dispatcher.onDevIndicator(message.devIndicator)
if ('devToolsConfig' in message) if ('devToolsConfig' in message)
dispatcher.onDevToolsConfig(message.devToolsConfig) dispatcher.onDevToolsConfig(message.devToolsConfig)
if ('requestInsights' in message && message.requestInsights)
dispatcher.onRequestInsightsSnapshot(message.requestInsights)
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
// Compilation with errors (e.g. syntax error or missing modules). // Compilation with errors (e.g. syntax error or missing modules).
...@@ -476,6 +478,10 @@ export function processMessage( ...@@ -476,6 +478,10 @@ export function processMessage(
dispatcher.onDevToolsConfig(message.data) dispatcher.onDevToolsConfig(message.data)
return return
} }
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE: {
dispatcher.onRequestInsightsUpdate(message.insight)
return
}
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: { case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: {
const { requestId, chunk } = message const { requestId, chunk } = message
const { writer } = getOrCreateDebugChannelReadableWriterPair(requestId) const { writer } = getOrCreateDebugChannelReadableWriterPair(requestId)
......
...@@ -393,6 +393,7 @@ function processMessage(message: HmrMessageSentToBrowser) { ...@@ -393,6 +393,7 @@ function processMessage(message: HmrMessageSentToBrowser) {
dispatcher.onDevToolsConfig(message.data) dispatcher.onDevToolsConfig(message.data)
break break
case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR: case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER: case HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER:
// Only relevant for app router. // Only relevant for app router.
......
...@@ -124,6 +124,7 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -124,6 +124,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA: case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA:
case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR: case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE:
case HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER: case HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER:
// Most of these action types are handled in // Most of these action types are handled in
// src/client/dev/hot-reloader/pages/hot-reloader-pages.ts and // src/client/dev/hot-reloader/pages/hot-reloader-pages.ts and
......
...@@ -23,6 +23,8 @@ import { ...@@ -23,6 +23,8 @@ import {
type DispatcherEvent, type DispatcherEvent,
ACTION_CACHE_INDICATOR, ACTION_CACHE_INDICATOR,
ACTION_INSTANT_NAVS_TOGGLE, ACTION_INSTANT_NAVS_TOGGLE,
ACTION_REQUEST_INSIGHTS_SNAPSHOT,
ACTION_REQUEST_INSIGHTS_UPDATE,
} from './dev-overlay/shared' } from './dev-overlay/shared'
import type { FlightRouterState } from '../shared/lib/app-router-types' import type { FlightRouterState } from '../shared/lib/app-router-types'
...@@ -50,6 +52,10 @@ import type { SegmentNodeState } from './userspace/app/segment-explorer-node' ...@@ -50,6 +52,10 @@ import type { SegmentNodeState } from './userspace/app/segment-explorer-node'
import type { DevToolsConfig } from './dev-overlay/shared' import type { DevToolsConfig } from './dev-overlay/shared'
import type { SegmentTrieData } from '../shared/lib/mcp-page-metadata-types' import type { SegmentTrieData } from '../shared/lib/mcp-page-metadata-types'
import { EventQueue } from './dev-overlay/event-queue' import { EventQueue } from './dev-overlay/event-queue'
import type {
RequestInsight,
RequestInsightsSnapshot,
} from './shared/request-insights'
export interface Dispatcher { export interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -78,6 +84,8 @@ export interface Dispatcher { ...@@ -78,6 +84,8 @@ export interface Dispatcher {
tree: FlightRouterState | null tree: FlightRouterState | null
): void ): void
instantNavsToggle(): void instantNavsToggle(): void
onRequestInsightsSnapshot(snapshot: RequestInsightsSnapshot): void
onRequestInsightsUpdate(insight: RequestInsight): void
} }
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1] type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
...@@ -233,6 +241,16 @@ export const dispatcher: Dispatcher = { ...@@ -233,6 +241,16 @@ export const dispatcher: Dispatcher = {
instantNavsToggle: createQueuable((dispatch: Dispatch) => { instantNavsToggle: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_INSTANT_NAVS_TOGGLE }) dispatch({ type: ACTION_INSTANT_NAVS_TOGGLE })
}), }),
onRequestInsightsSnapshot: createQueuable(
(dispatch: Dispatch, snapshot: RequestInsightsSnapshot) => {
dispatch({ type: ACTION_REQUEST_INSIGHTS_SNAPSHOT, snapshot })
}
),
onRequestInsightsUpdate: createQueuable(
(dispatch: Dispatch, insight: RequestInsight) => {
dispatch({ type: ACTION_REQUEST_INSIGHTS_UPDATE, insight })
}
),
} }
function DevOverlayRoot({ function DevOverlayRoot({
......
...@@ -8,6 +8,10 @@ import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-ser ...@@ -8,6 +8,10 @@ import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-ser
import { parseStack } from '../../server/lib/parse-stack' import { parseStack } from '../../server/lib/parse-stack'
import { isConsoleError } from '../shared/console-error' import { isConsoleError } from '../shared/console-error'
import type { CacheIndicatorState } from './cache-indicator' import type { CacheIndicatorState } from './cache-indicator'
import type {
RequestInsight,
RequestInsightsSnapshot,
} from '../shared/request-insights'
import { readInstantNavCookieState } from './components/instant-navs/instant-nav-cookie' import { readInstantNavCookieState } from './components/instant-navs/instant-nav-cookie'
import { isBlockingRouteInNavError } from './container/errors' import { isBlockingRouteInNavError } from './container/errors'
import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic'
...@@ -77,6 +81,7 @@ export interface OverlayState { ...@@ -77,6 +81,7 @@ export interface OverlayState {
readonly theme: 'light' | 'dark' | 'system' readonly theme: 'light' | 'dark' | 'system'
readonly hideShortcut: string | null readonly hideShortcut: string | null
readonly instantNavs: boolean readonly instantNavs: boolean
readonly requestInsights: readonly RequestInsight[]
} }
type DevtoolsPanelName = string type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent> export type OverlayDispatch = React.Dispatch<DispatcherEvent>
...@@ -111,6 +116,8 @@ export const ACTION_DEVTOOLS_CONFIG = 'devtools-config' ...@@ -111,6 +116,8 @@ export const ACTION_DEVTOOLS_CONFIG = 'devtools-config'
export const ACTION_INSTANT_NAVS_TOGGLE = 'instant-navs-toggle' export const ACTION_INSTANT_NAVS_TOGGLE = 'instant-navs-toggle'
export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset' export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset'
export const ACTION_INSTANT_ERRORS_CLEAR = 'instant-errors-clear' export const ACTION_INSTANT_ERRORS_CLEAR = 'instant-errors-clear'
export const ACTION_REQUEST_INSIGHTS_SNAPSHOT = 'request-insights-snapshot'
export const ACTION_REQUEST_INSIGHTS_UPDATE = 'request-insights-update'
export const STORAGE_KEY_PANEL_POSITION_PREFIX = export const STORAGE_KEY_PANEL_POSITION_PREFIX =
'__nextjs-dev-tools-panel-position' '__nextjs-dev-tools-panel-position'
...@@ -240,6 +247,16 @@ interface InstantErrorsClearAction { ...@@ -240,6 +247,16 @@ interface InstantErrorsClearAction {
currentPath: string currentPath: string
} }
interface RequestInsightsSnapshotAction {
type: typeof ACTION_REQUEST_INSIGHTS_SNAPSHOT
snapshot: RequestInsightsSnapshot
}
interface RequestInsightsUpdateAction {
type: typeof ACTION_REQUEST_INSIGHTS_UPDATE
insight: RequestInsight
}
export type DispatcherEvent = export type DispatcherEvent =
| BuildOkAction | BuildOkAction
| BuildErrorAction | BuildErrorAction
...@@ -268,6 +285,8 @@ export type DispatcherEvent = ...@@ -268,6 +285,8 @@ export type DispatcherEvent =
| CacheOnlyToggleAction | CacheOnlyToggleAction
| InstantNavResetAction | InstantNavResetAction
| InstantErrorsClearAction | InstantErrorsClearAction
| RequestInsightsSnapshotAction
| RequestInsightsUpdateAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8 // 1st group: new frame + v8
...@@ -353,6 +372,7 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -353,6 +372,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
theme: 'system', theme: 'system',
hideShortcut: null, hideShortcut: null,
instantNavs: hasInstantNavsCookie, instantNavs: hasInstantNavsCookie,
requestInsights: [],
} }
function getInitialState( function getInitialState(
...@@ -583,6 +603,16 @@ export function useErrorOverlayReducer( ...@@ -583,6 +603,16 @@ export function useErrorOverlayReducer(
} }
return { ...state, errors: remaining } return { ...state, errors: remaining }
} }
case ACTION_REQUEST_INSIGHTS_SNAPSHOT: {
return { ...state, requestInsights: action.snapshot.requests }
}
case ACTION_REQUEST_INSIGHTS_UPDATE: {
const requests = state.requestInsights.filter(
(request) => request.requestId !== action.insight.requestId
)
requests.push(action.insight)
return { ...state, requestInsights: requests.slice(-100) }
}
default: { default: {
return state return state
} }
......
import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api' type RequestInsightAttributeValue =
| string
| number
| boolean
| Array<null | undefined | string>
| Array<null | undefined | number>
| Array<null | undefined | boolean>
export type RequestInsightSpan = { export type RequestInsightSpan = {
name: string name: string
...@@ -8,16 +14,16 @@ export type RequestInsightSpan = { ...@@ -8,16 +14,16 @@ export type RequestInsightSpan = {
traceId?: string traceId?: string
spanId?: string spanId?: string
parentSpanId?: string parentSpanId?: string
attributes?: Record<string, AttributeValue> attributes?: Record<string, RequestInsightAttributeValue>
links?: Array<{ links?: Array<{
traceId: string traceId: string
spanId: string spanId: string
attributes?: Record<string, AttributeValue> attributes?: Record<string, RequestInsightAttributeValue>
}> }>
events?: Array<{ events?: Array<{
name: string name: string
timestamp: number timestamp: number
attributes?: Record<string, AttributeValue> attributes?: Record<string, RequestInsightAttributeValue>
}> }>
error?: { error?: {
type?: string type?: string
......
...@@ -465,6 +465,12 @@ export default abstract class Server< ...@@ -465,6 +465,12 @@ export default abstract class Server<
// TODO: should conf be normalized to prevent missing // TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided // values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigRuntime this.nextConfig = conf as NextConfigRuntime
if (
(dev || process.env.__NEXT_DEV_SERVER) &&
this.nextConfig.experimental.requestInsights
) {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
}
if (this.nextConfig.experimental.runtimeServerDeploymentId) { if (this.nextConfig.experimental.runtimeServerDeploymentId) {
if (!process.env.NEXT_DEPLOYMENT_ID) { if (!process.env.NEXT_DEPLOYMENT_ID) {
......
...@@ -258,6 +258,7 @@ export const experimentalSchema = { ...@@ -258,6 +258,7 @@ export const experimentalSchema = {
externalMiddlewareRewritesResolve: z.boolean().optional(), externalMiddlewareRewritesResolve: z.boolean().optional(),
externalProxyRewritesResolve: z.boolean().optional(), externalProxyRewritesResolve: z.boolean().optional(),
exposeTestingApiInProductionBuild: z.boolean().optional(), exposeTestingApiInProductionBuild: z.boolean().optional(),
requestInsights: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(), fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(), fetchCacheKeyPrefix: z.string().optional(),
forceSwcTransforms: z.boolean().optional(), forceSwcTransforms: z.boolean().optional(),
......
...@@ -566,6 +566,12 @@ export interface ExperimentalConfig { ...@@ -566,6 +566,12 @@ export interface ExperimentalConfig {
* Do not enable in user-facing production deployments. * Do not enable in user-facing production deployments.
*/ */
exposeTestingApiInProductionBuild?: boolean exposeTestingApiInProductionBuild?: boolean
/**
* Show Request Insights in the dev tools indicator. Request Insights records
* the local framework spans needed to explain App Router request, render,
* fetch, and cache behavior without requiring an external OTEL collector.
*/
requestInsights?: boolean
extensionAlias?: Record<string, any> extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
...@@ -2140,6 +2146,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2140,6 +2146,7 @@ export const defaultConfig = Object.freeze({
fullySpecified: false, fullySpecified: false,
swcTraceProfiling: false, swcTraceProfiling: false,
forceSwcTransforms: false, forceSwcTransforms: false,
requestInsights: false,
swcPlugins: undefined, swcPlugins: undefined,
largePageDataBytes: 128 * 1000, // 128KB by default largePageDataBytes: 128 * 1000, // 128KB by default
disablePostcssPresetEnv: undefined, disablePostcssPresetEnv: undefined,
...@@ -2303,6 +2310,7 @@ export interface NextConfigRuntime { ...@@ -2303,6 +2310,7 @@ export interface NextConfigRuntime {
| 'exposeTestingApiInProductionBuild' | 'exposeTestingApiInProductionBuild'
| 'supportsImmutableAssets' | 'supportsImmutableAssets'
| 'instantInsights' | 'instantInsights'
| 'requestInsights'
> & { > & {
// Pick on @internal fields generates invalid .d.ts files // Pick on @internal fields generates invalid .d.ts files
/** @internal */ /** @internal */
...@@ -2373,6 +2381,7 @@ export function getNextConfigRuntime( ...@@ -2373,6 +2381,7 @@ export function getNextConfigRuntime(
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild, exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
supportsImmutableAssets: ex.supportsImmutableAssets, supportsImmutableAssets: ex.supportsImmutableAssets,
instantInsights: ex.instantInsights, instantInsights: ex.instantInsights,
requestInsights: ex.requestInsights,
trustHostHeader: ex.trustHostHeader, trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile, isExperimentalCompile: ex.isExperimentalCompile,
......
...@@ -31,6 +31,10 @@ import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types' ...@@ -31,6 +31,10 @@ import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import { devIndicatorServerState } from './dev-indicator-server-state' import { devIndicatorServerState } from './dev-indicator-server-state'
import { createBinaryHmrMessageData } from './messages' import { createBinaryHmrMessageData } from './messages'
import type { NextConfigComplete } from '../config-shared' import type { NextConfigComplete } from '../config-shared'
import {
getRequestInsightsSnapshot,
isRequestInsightsEnabled,
} from '../lib/trace/request-insights'
function isMiddlewareStats(stats: webpack.Stats) { function isMiddlewareStats(stats: webpack.Stats) {
for (const key of stats.compilation.entrypoints.keys()) { for (const key of stats.compilation.entrypoints.keys()) {
...@@ -207,6 +211,10 @@ export class WebpackHotMiddleware { ...@@ -207,6 +211,10 @@ export class WebpackHotMiddleware {
}, },
devIndicator: devIndicatorServerState, devIndicator: devIndicatorServerState,
devToolsConfig: this.devToolsConfig, devToolsConfig: this.devToolsConfig,
requestInsights:
this.config.experimental.requestInsights || isRequestInsightsEnabled()
? getRequestInsightsSnapshot()
: undefined,
}) })
} }
} }
......
...@@ -123,6 +123,10 @@ import { ...@@ -123,6 +123,10 @@ import {
} from './hot-reloader-shared-utils' } from './hot-reloader-shared-utils'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware' import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { formatCompilationIssues } from '../mcp/tools/utils/format-compilation-issues' import { formatCompilationIssues } from '../mcp/tools/utils/format-compilation-issues'
import {
getRequestInsightsSnapshot,
isRequestInsightsEnabled,
} from '../lib/trace/request-insights'
import { resolvePathToRoute } from '../mcp/tools/utils/resolve-path-to-route' import { resolvePathToRoute } from '../mcp/tools/utils/resolve-path-to-route'
import { handleErrorStateResponse } from '../mcp/tools/get-errors' import { handleErrorStateResponse } from '../mcp/tools/get-errors'
import { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata' import { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'
...@@ -1468,6 +1472,11 @@ export async function createHotReloaderTurbopack( ...@@ -1468,6 +1472,11 @@ export async function createHotReloaderTurbopack(
}, },
devIndicator: devIndicatorServerState, devIndicator: devIndicatorServerState,
devToolsConfig, devToolsConfig,
requestInsights:
nextConfig.experimental.requestInsights ||
isRequestInsightsEnabled()
? getRequestInsightsSnapshot()
: undefined,
} }
sendToClient(client, syncMessage) sendToClient(client, syncMessage)
......
...@@ -13,6 +13,10 @@ import type { ...@@ -13,6 +13,10 @@ import type {
ServerCacheStatus, ServerCacheStatus,
} from '../../next-devtools/dev-overlay/cache-indicator' } from '../../next-devtools/dev-overlay/cache-indicator'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared' import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import type {
RequestInsight,
RequestInsightsSnapshot,
} from '../../next-devtools/shared/request-insights'
import type { ReactDebugChannelForBrowser } from './debug-channel' import type { ReactDebugChannelForBrowser } from './debug-channel'
import type { AnyStream } from '../app-render/stream-ops' import type { AnyStream } from '../app-render/stream-ops'
...@@ -38,6 +42,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER { ...@@ -38,6 +42,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
DEVTOOLS_CONFIG = 'devtoolsConfig', DEVTOOLS_CONFIG = 'devtoolsConfig',
REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState', REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState',
REQUEST_PAGE_METADATA = 'requestPageMetadata', REQUEST_PAGE_METADATA = 'requestPageMetadata',
REQUEST_INSIGHTS_UPDATE = 'requestInsightsUpdate',
// Binary messages: // Binary messages:
REACT_DEBUG_CHUNK = 0, REACT_DEBUG_CHUNK = 0,
...@@ -83,6 +88,7 @@ export interface SyncMessage { ...@@ -83,6 +88,7 @@ export interface SyncMessage {
debug?: DebugInfo debug?: DebugInfo
devIndicator: DevIndicatorServerState devIndicator: DevIndicatorServerState
devToolsConfig?: DevToolsConfig devToolsConfig?: DevToolsConfig
requestInsights?: RequestInsightsSnapshot
} }
export interface BuiltMessage { export interface BuiltMessage {
...@@ -179,6 +185,11 @@ export interface CacheIndicatorMessage { ...@@ -179,6 +185,11 @@ export interface CacheIndicatorMessage {
state: CacheIndicatorState state: CacheIndicatorState
} }
export interface RequestInsightsUpdateMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE
insight: RequestInsight
}
export type HmrMessageSentToBrowser = export type HmrMessageSentToBrowser =
| TurbopackMessage | TurbopackMessage
| TurbopackConnectedMessage | TurbopackConnectedMessage
...@@ -201,6 +212,7 @@ export type HmrMessageSentToBrowser = ...@@ -201,6 +212,7 @@ export type HmrMessageSentToBrowser =
| RequestCurrentErrorStateMessage | RequestCurrentErrorStateMessage
| RequestPageMetadataMessage | RequestPageMetadataMessage
| CacheIndicatorMessage | CacheIndicatorMessage
| RequestInsightsUpdateMessage
export type BinaryHmrMessageSentToBrowser = Extract< export type BinaryHmrMessageSentToBrowser = Extract<
HmrMessageSentToBrowser, HmrMessageSentToBrowser,
......
...@@ -9,6 +9,8 @@ import { ...@@ -9,6 +9,8 @@ import {
type HmrMessageSentToBrowser, type HmrMessageSentToBrowser,
type NextJsHotReloaderInterface, type NextJsHotReloaderInterface,
} from '../dev/hot-reloader-types' } from '../dev/hot-reloader-types'
import { isRequestInsightsEnabled } from './trace/span-store'
import { subscribeRequestInsights } from './trace/request-insights'
/** /**
* The DevBundlerService provides an interface to perform tasks with the * The DevBundlerService provides an interface to perform tasks with the
...@@ -16,10 +18,10 @@ import { ...@@ -16,10 +18,10 @@ import {
*/ */
export class DevBundlerService { export class DevBundlerService {
public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>> public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>
public close: NextJsHotReloaderInterface['close']
public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus'] public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']
public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel'] public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']
public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser'] public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']
private unsubscribeRequestInsights?: () => void
constructor( constructor(
private readonly bundler: DevBundler, private readonly bundler: DevBundler,
...@@ -35,11 +37,24 @@ export class DevBundlerService { ...@@ -35,11 +37,24 @@ export class DevBundlerService {
const { hotReloader } = bundler const { hotReloader } = bundler
this.close = hotReloader.close.bind(hotReloader)
this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader) this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader)
this.setReactDebugChannel = this.setReactDebugChannel =
hotReloader.setReactDebugChannel.bind(hotReloader) hotReloader.setReactDebugChannel.bind(hotReloader)
this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader) this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader)
if (isRequestInsightsEnabled()) {
this.unsubscribeRequestInsights = subscribeRequestInsights((insight) => {
hotReloader.send({
type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE,
insight,
})
})
}
}
public close: NextJsHotReloaderInterface['close'] = () => {
this.unsubscribeRequestInsights?.()
this.bundler.hotReloader.close()
} }
public ensurePage: typeof this.bundler.hotReloader.ensurePage = async ( public ensurePage: typeof this.bundler.hotReloader.ensurePage = async (
......
...@@ -61,6 +61,10 @@ import { ...@@ -61,6 +61,10 @@ import {
isChromeDevtoolsWorkspaceUrl, isChromeDevtoolsWorkspaceUrl,
} from './chrome-devtools-workspace' } from './chrome-devtools-workspace'
import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared' import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'
import {
getRequestInsightsSnapshot,
isRequestInsightsEnabled,
} from './trace/request-insights'
const debug = setupDebug('next:router-server:main') const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) => const isNextFont = (pathname: string | null) =>
...@@ -239,6 +243,48 @@ export async function initialize(opts: { ...@@ -239,6 +243,48 @@ export async function initialize(opts: {
filterInternalHeaders(req.headers) filterInternalHeaders(req.headers)
} }
if (opts.dev && req.url) {
if (config.experimental.requestInsights) {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
}
const urlParts = req.url.split('?', 1)
const pathname = removePathPrefix(urlParts[0] || '', config.basePath)
if (pathname === '/__nextjs_request_insights') {
if (
development &&
blockCrossSiteDEV(
req,
res,
development.config.allowedDevOrigins,
opts.hostname
)
) {
return
}
res.setHeader('Content-Type', 'application/json; charset=utf-8')
if (
!config.experimental.requestInsights &&
!isRequestInsightsEnabled()
) {
res.statusCode = 404
res.end(
JSON.stringify({
error:
'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',
})
)
return
}
res.statusCode = 200
res.end(JSON.stringify(getRequestInsightsSnapshot()))
return
}
}
if ( if (
!opts.minimalMode && !opts.minimalMode &&
config.i18n && config.i18n &&
......
...@@ -222,6 +222,14 @@ export default class NextNodeServer extends BaseServer< ...@@ -222,6 +222,14 @@ export default class NextNodeServer extends BaseServer<
if (this.renderOpts.nextScriptWorkers) { if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true) process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
} }
if (
(isDev || process.env.__NEXT_DEV_SERVER) &&
this.nextConfig.experimental.requestInsights
) {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
} else {
delete process.env.__NEXT_REQUEST_INSIGHTS
}
if (!this.minimalMode) { if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode) this.imageResponseCache = new ResponseCache(this.minimalMode)
......
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