Commit 961fb0ae authored by Jude Gao's avatar Jude Gao

embed data ingestion and terminal reporting

parent 2b831d1e
...@@ -969,5 +969,6 @@ ...@@ -969,5 +969,6 @@
"968": "Invariant: getNextConfigEdge must only be called in edge runtime", "968": "Invariant: getNextConfigEdge must only be called in edge runtime",
"969": "Invariant: nextConfig couldn't be loaded", "969": "Invariant: nextConfig couldn't be loaded",
"970": "process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled", "970": "process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled",
"971": "The NEXT_DEPLOYMENT_ID environment variable value \"%s\" does not match the provided deploymentId \"%s\" in the config." "971": "The NEXT_DEPLOYMENT_ID environment variable value \"%s\" does not match the provided deploymentId \"%s\" in the config.",
"972": "Fetch call site"
} }
...@@ -5,14 +5,6 @@ ...@@ -5,14 +5,6 @@
* - next/script with `beforeInteractive` strategy * - next/script with `beforeInteractive` strategy
*/ */
// Initialize waterfall detector FIRST (before any fetch calls can be made)
// This must be at the very top to patch fetch before other code runs
if (process.env.__NEXT_PROFILER_BUILD) {
// Import synchronously to ensure fetch is patched immediately
const { initWaterfallDetector } = (require('./waterfall-detector') as typeof import('./waterfall-detector'))
initWaterfallDetector()
}
import { getAssetPrefix } from './asset-prefix' import { getAssetPrefix } from './asset-prefix'
import { setAttributesFromProps } from './set-attributes-from-props' import { setAttributesFromProps } from './set-attributes-from-props'
......
/* global location */ /* global location */
// Initialize waterfall detector FIRST (before any fetch calls can be made)
// This must be at the very top to patch fetch before other code runs
if (process.env.__NEXT_PROFILER_BUILD) {
const { initWaterfallDetector } = (require('./waterfall-detector') as typeof import('./waterfall-detector'))
initWaterfallDetector()
}
// imports polyfill from `@next/polyfill-module` after build. // imports polyfill from `@next/polyfill-module` after build.
import '../build/polyfills/polyfill-module' import '../build/polyfills/polyfill-module'
import type Router from '../shared/lib/router/router' import type Router from '../shared/lib/router/router'
......
...@@ -284,6 +284,17 @@ async function analyzeWaterfalls() { ...@@ -284,6 +284,17 @@ async function analyzeWaterfalls() {
console.log('') console.log('')
console.log(' No data fetches were made during initial page load.') console.log(' No data fetches were made during initial page load.')
console.log(' This is ideal - all data is being fetched on the server.') console.log(' This is ideal - all data is being fetched on the server.')
// Send report to server
sendReportToServer({
type: 'no-fetches',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
timestamp: Date.now(),
totalFetches: 0,
totalCommits: commitEvents.length,
renderTriggeringFetches: [],
waterfallChains: [],
})
return return
} }
...@@ -399,6 +410,17 @@ async function analyzeWaterfalls() { ...@@ -399,6 +410,17 @@ async function analyzeWaterfalls() {
' Client-side fetches were made, but none triggered React re-renders.' ' Client-side fetches were made, but none triggered React re-renders.'
) )
console.log(' No waterfall patterns found.') console.log(' No waterfall patterns found.')
// Send report to server
sendReportToServer({
type: 'no-waterfall',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
timestamp: Date.now(),
totalFetches: fetchEvents.length,
totalCommits: commitEvents.length,
renderTriggeringFetches: [],
waterfallChains: [],
})
} else if (chains.length === 0 && renderTriggeringFetches.length > 0) { } else if (chains.length === 0 && renderTriggeringFetches.length > 0) {
// Fetches triggered renders but no waterfall chain detected // Fetches triggered renders but no waterfall chain detected
console.log( console.log(
...@@ -435,6 +457,21 @@ async function analyzeWaterfalls() { ...@@ -435,6 +457,21 @@ async function analyzeWaterfalls() {
} }
console.log('') console.log('')
}) })
// Send report to server
sendReportToServer({
type: 'render-blocking',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
timestamp: Date.now(),
totalFetches: fetchEvents.length,
totalCommits: commitEvents.length,
renderTriggeringFetches: renderTriggeringFetches.map((f) => ({
url: f.url,
stackTrace: f.stackTrace,
parsedFrames: f.parsedFrames,
})),
waterfallChains: [],
})
} else { } else {
console.log( console.log(
'%c[Waterfall Detector] Waterfall patterns detected!', '%c[Waterfall Detector] Waterfall patterns detected!',
...@@ -529,6 +566,27 @@ async function analyzeWaterfalls() { ...@@ -529,6 +566,27 @@ async function analyzeWaterfalls() {
) )
console.log(' in the component tree, or use Promise.all() to parallelize.') console.log(' in the component tree, or use Promise.all() to parallelize.')
console.log('') console.log('')
// Send report to server
sendReportToServer({
type: 'waterfall',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
timestamp: Date.now(),
totalFetches: fetchEvents.length,
totalCommits: commitEvents.length,
renderTriggeringFetches: renderTriggeringFetches.map((f) => ({
url: f.url,
stackTrace: f.stackTrace,
parsedFrames: f.parsedFrames,
})),
waterfallChains: chains.map((chain) =>
chain.map((f) => ({
url: f.url,
stackTrace: f.stackTrace,
parsedFrames: f.parsedFrames,
}))
),
})
} }
} }
...@@ -577,14 +635,61 @@ function parseStackFrames(stack: string): StackFrame[] { ...@@ -577,14 +635,61 @@ function parseStackFrames(stack: string): StackFrame[] {
/** /**
* Resolve stack frames - currently returns frames as-is * Resolve stack frames - currently returns frames as-is
* Source map resolution is not available without a server endpoint * Source map resolution happens server-side after the report is sent
*/ */
async function resolveStackFrames(frames: StackFrame[]): Promise<StackFrame[]> { async function resolveStackFrames(frames: StackFrame[]): Promise<StackFrame[]> {
// Source map resolution removed - frames are returned as-is // Stack frames are sent raw to the server, which resolves them using source maps
// The browser DevTools will still resolve source maps when viewing errors in the console
return frames return frames
} }
/**
* Report structure sent to the server for processing
*/
interface WaterfallReport {
type: 'waterfall' | 'render-blocking' | 'no-waterfall' | 'no-fetches'
pageUrl: string
timestamp: number
totalFetches: number
totalCommits: number
renderTriggeringFetches: Array<{
url: string
stackTrace: string
parsedFrames: StackFrame[]
}>
waterfallChains: Array<
Array<{
url: string
stackTrace: string
parsedFrames: StackFrame[]
}>
>
}
/**
* Send the waterfall report to the server for source map resolution and logging
*/
async function sendReportToServer(report: WaterfallReport): Promise<void> {
try {
const response = await originalFetch('/__nextjs_profiler_ingest', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(report),
})
if (!response.ok) {
console.warn(
'[Waterfall Detector] Failed to send report to server:',
response.status
)
}
} catch (error) {
// Silently fail - don't disrupt the user experience
console.warn('[Waterfall Detector] Could not send report to server:', error)
}
}
/** /**
* Filter stack frames to show only user code * Filter stack frames to show only user code
*/ */
...@@ -616,6 +721,24 @@ function truncateUrl(url: string, maxLength: number = 60): string { ...@@ -616,6 +721,24 @@ function truncateUrl(url: string, maxLength: number = 60): string {
return url.slice(0, maxLength - 3) + '...' return url.slice(0, maxLength - 3) + '...'
} }
/**
* Disable waterfall detection (called on client-side navigation)
*/
export function disableWaterfallDetector() {
if (hasAnalyzed) return
// Mark as analyzed to stop all tracking
hasAnalyzed = true
isInitialLoad = false
// Clean up timers
if (settleTimer) clearTimeout(settleTimer)
if (idleTimer) clearTimeout(idleTimer)
if (maxWindowTimer) clearTimeout(maxWindowTimer)
log('Disabled (client-side navigation detected)')
}
/** /**
* Initialize waterfall detection * Initialize waterfall detection
*/ */
......
...@@ -4,11 +4,23 @@ ...@@ -4,11 +4,23 @@
* The `private-next-instrumentation-client` module is automatically aliased to * The `private-next-instrumentation-client` module is automatically aliased to
* the `instrumentation-client.ts` file in the project root by webpack or turbopack. * the `instrumentation-client.ts` file in the project root by webpack or turbopack.
*/ */
// Initialize waterfall detector FIRST (before any other code runs)
// This must happen before the instrumentation client is loaded to patch fetch early
let disableWaterfallDetector: (() => void) | null = null
if (process.env.__NEXT_PROFILER_BUILD) {
const waterfallDetector =
require('../client/waterfall-detector') as typeof import('../client/waterfall-detector')
waterfallDetector.initWaterfallDetector()
disableWaterfallDetector = waterfallDetector.disableWaterfallDetector
}
let userHooks: Record<string, any> = {}
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const measureName = 'Client Instrumentation Hook' const measureName = 'Client Instrumentation Hook'
const startTime = performance.now() const startTime = performance.now()
// eslint-disable-next-line @next/internal/typechecked-require -- Not a module. // eslint-disable-next-line @next/internal/typechecked-require -- Not a module.
module.exports = require('private-next-instrumentation-client') userHooks = require('private-next-instrumentation-client')
const endTime = performance.now() const endTime = performance.now()
const duration = endTime - startTime const duration = endTime - startTime
...@@ -23,5 +35,22 @@ if (process.env.NODE_ENV === 'development') { ...@@ -23,5 +35,22 @@ if (process.env.NODE_ENV === 'development') {
} }
} else { } else {
// eslint-disable-next-line @next/internal/typechecked-require -- Not a module. // eslint-disable-next-line @next/internal/typechecked-require -- Not a module.
module.exports = require('private-next-instrumentation-client') userHooks = require('private-next-instrumentation-client')
}
// Compose onRouterTransitionStart: disable waterfall detector, then call user hook
const userOnRouterTransitionStart = userHooks.onRouterTransitionStart
const composedOnRouterTransitionStart =
disableWaterfallDetector || userOnRouterTransitionStart
? (url: string, navigationType: 'push' | 'replace' | 'traverse') => {
// Disable waterfall detector on any client-side navigation
disableWaterfallDetector?.()
// Call user's hook if provided
userOnRouterTransitionStart?.(url, navigationType)
}
: undefined
module.exports = {
...userHooks,
onRouterTransitionStart: composedOnRouterTransitionStart,
} }
...@@ -1632,6 +1632,7 @@ export interface NextConfigRuntime { ...@@ -1632,6 +1632,7 @@ export interface NextConfigRuntime {
skipProxyUrlNormalize: NextConfigComplete['skipProxyUrlNormalize'] skipProxyUrlNormalize: NextConfigComplete['skipProxyUrlNormalize']
pageExtensions: NextConfigComplete['pageExtensions'] pageExtensions: NextConfigComplete['pageExtensions']
useFileSystemPublicRoutes: NextConfigComplete['useFileSystemPublicRoutes'] useFileSystemPublicRoutes: NextConfigComplete['useFileSystemPublicRoutes']
profiler?: NextConfigComplete['profiler']
experimental: Pick< experimental: Pick<
NextConfigComplete['experimental'], NextConfigComplete['experimental'],
...@@ -1761,6 +1762,7 @@ export function getNextConfigRuntime( ...@@ -1761,6 +1762,7 @@ export function getNextConfigRuntime(
skipProxyUrlNormalize: config.skipProxyUrlNormalize, skipProxyUrlNormalize: config.skipProxyUrlNormalize,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
useFileSystemPublicRoutes: config.useFileSystemPublicRoutes, useFileSystemPublicRoutes: config.useFileSystemPublicRoutes,
profiler: config.profiler,
experimental, experimental,
} }
......
This diff is collapsed.
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