Commit 2de49121 authored by Jiachi Liu's avatar Jiachi Liu

highlight reasons

parent aef7c344
......@@ -57,9 +57,43 @@ const panelScript = `
}
};
// Match dynamic accesses to their enclosing suspense boundary
function matchDynamicToBoundary(boundaries, dynamicAccesses) {
var boundaryReasons = {}; // boundaryId -> [expressions]
dynamicAccesses.forEach(function(api) {
if (!api.frames.length) return;
var apiPath = api.frames.map(function(f) { return f.componentName; }).join('/');
// Find the boundary whose path is a prefix of the api path (nearest ancestor)
var bestMatch = null;
var bestMatchLen = 0;
boundaries.forEach(function(b) {
if (!b.frames.length) return;
var boundaryPath = b.frames.map(function(f) { return f.componentName; }).join('/');
// Check if boundary path is prefix of api path (or equal)
if (apiPath.indexOf(boundaryPath) === 0 && boundaryPath.length > bestMatchLen) {
bestMatch = b.id;
bestMatchLen = boundaryPath.length;
}
});
if (bestMatch) {
if (!boundaryReasons[bestMatch]) boundaryReasons[bestMatch] = [];
if (boundaryReasons[bestMatch].indexOf(api.expression) === -1) {
boundaryReasons[bestMatch].push(api.expression);
}
}
});
return boundaryReasons;
}
// Build tree from boundaries and dynamic accesses
function buildTree(boundaries, dynamicAccesses) {
var root = { name: 'Root', children: {}, boundaries: [], apis: [] };
function buildTree(boundaries, dynamicAccesses, boundaryReasons) {
var root = { name: 'Root', children: {}, boundaries: [], apis: [], reasons: [] };
// Add boundaries to tree
boundaries.forEach(function(b) {
......@@ -70,11 +104,15 @@ const panelScript = `
path.forEach(function(frame) {
var name = frame.componentName;
if (!node.children[name]) {
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], frame: frame };
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], reasons: [], frame: frame };
}
node = node.children[name];
});
node.boundaries.push(b);
// Attach reasons to this boundary node
if (boundaryReasons[b.id]) {
node.reasons = node.reasons.concat(boundaryReasons[b.id]);
}
});
// Add dynamic APIs to tree
......@@ -85,7 +123,7 @@ const panelScript = `
path.forEach(function(frame) {
var name = frame.componentName;
if (!node.children[name]) {
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], frame: frame };
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], reasons: [], frame: frame };
}
node = node.children[name];
});
......@@ -106,10 +144,10 @@ const panelScript = `
if (depth > 0) {
var hasSuspense = node.boundaries.length > 0;
var hasApis = node.apis.length > 0;
var hasReasons = node.reasons && node.reasons.length > 0;
html += '<div style="border-bottom:1px solid #f5f5f5;">';
html += '<div onclick="window.__sp.toggle(\\'' + path + '\\')" style="padding:8px 12px 8px ' + (12 + indent) + 'px;cursor:pointer;display:flex;align-items:center;gap:6px;">';
html += '<div onclick="window.__sp.toggle(\\'' + path + '\\')" style="padding:8px 12px 8px ' + (12 + indent) + 'px;cursor:pointer;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">';
if (hasChildren) {
html += '<span style="color:#999;font-size:9px;width:10px;">' + (isExpanded ? '▼' : '▶') + '</span>';
......@@ -122,10 +160,8 @@ const panelScript = `
if (hasSuspense) {
html += '<span style="background:#e8e8e8;color:#666;padding:1px 6px;border-radius:3px;font-size:10px;">suspense</span>';
}
if (hasApis) {
var apiNames = [];
node.apis.forEach(function(a) { if (apiNames.indexOf(a.expression) === -1) apiNames.push(a.expression); });
html += '<span style="color:#888;font-size:11px;margin-left:auto;">' + apiNames.join(', ') + '</span>';
if (hasReasons) {
html += '<span style="color:#c41e3a;font-size:11px;margin-left:auto;">← ' + node.reasons.join(', ') + '</span>';
}
html += '</div></div>';
......@@ -146,7 +182,8 @@ const panelScript = `
var sp = window.__sp;
if (sp.isOpen) {
var tree = buildTree(boundaries, dynamicAccesses);
var boundaryReasons = matchDynamicToBoundary(boundaries, dynamicAccesses);
var tree = buildTree(boundaries, dynamicAccesses, boundaryReasons);
var treeHtml = '';
Object.keys(tree.children).forEach(function(key) {
treeHtml += renderNode(tree.children[key], 1, key);
......
import type { NonStaticRenderStage } from './app-render/staged-rendering'
import type { RequestStore } from './app-render/work-unit-async-storage.external'
import React from 'react'
import { trackDynamicAPIAccess } from './app-render/suspense-boundary-collector'
export function isHangingPromiseRejectionError(
err: unknown
......@@ -41,6 +43,13 @@ export function makeHangingPromise<T>(
route: string,
expression: string
): Promise<T> {
// Track the dynamic access for suspense profiling
const ownerStack =
process.env.NODE_ENV !== 'production' && React.captureOwnerStack
? React.captureOwnerStack()
: null
trackDynamicAPIAccess(expression, ownerStack)
if (signal.aborted) {
return Promise.reject(new HangingPromiseRejectionError(route, expression))
} else {
......
......@@ -30,6 +30,8 @@ import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
import { trackDynamicAPIAccess } from '../app-render/suspense-boundary-collector'
import React from 'react'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -528,6 +530,20 @@ function instrumentParamsPromiseWithDevWarnings(
warnForSyncAccess(workStore.route, expression)
}
}
// Track when params are awaited for suspense profiling
if (prop === 'then') {
const originalThen = target.then.bind(target)
return function (
onfulfilled?: ((value: Params) => any) | null,
onrejected?: ((reason: any) => any) | null
) {
const ownerStack = React.captureOwnerStack
? React.captureOwnerStack()
: null
trackDynamicAPIAccess('`params`', ownerStack)
return originalThen(onfulfilled, onrejected)
}
}
return ReflectAdapter.get(target, prop, receiver)
},
set(target, prop, value, receiver) {
......
import { Suspense } from 'react'
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
// Component that uses cookies - triggers dynamic API
async function CookieCounter() {
// =============================================================================
// Case 1: cookies() - Request-specific data (no "use cache")
// =============================================================================
async function CookieContent() {
const cookieStore = await cookies()
const allCookies = cookieStore.getAll()
return (
<div data-testid="cookie-counter">
<div data-testid="cookie-content">
Cookie count: {allCookies.length}
</div>
)
}
// Component that uses headers - triggers dynamic API
async function HeaderInfo() {
// =============================================================================
// Case 2: headers() - Request-specific data (no "use cache")
// =============================================================================
async function HeaderContent() {
const headersList = await headers()
const userAgent = headersList.get('user-agent') || 'Unknown'
return (
<div data-testid="header-info">
<div data-testid="header-content">
User Agent: {userAgent.slice(0, 50)}...
</div>
)
}
// Regular async component (no dynamic API)
async function SlowComponent({ id, delay }: { id: string; delay: number }) {
await new Promise((resolve) => setTimeout(resolve, delay))
return <div data-testid={`content-${id}`}>Content {id} loaded</div>
}
// Wrapper components to make boundaries identifiable
function CookieSection() {
// =============================================================================
// Case 3: connection() - Explicitly opt into dynamic rendering
// =============================================================================
async function ConnectionContent() {
await connection()
return (
<Suspense fallback={<div data-testid="cookies-loading">Loading cookies...</div>}>
<CookieCounter />
</Suspense>
)
}
function HeaderSection() {
return (
<Suspense fallback={<div data-testid="headers-loading">Loading headers...</div>}>
<HeaderInfo />
</Suspense>
<div data-testid="connection-content">
Connection established at: {Date.now()}
</div>
)
}
function RegularSection() {
// =============================================================================
// Case 4: Static async content (for comparison)
// =============================================================================
async function StaticAsyncContent() {
await new Promise((resolve) => setTimeout(resolve, 50))
return (
<Suspense fallback={<div data-testid="regular-loading">Loading regular...</div>}>
<SlowComponent id="regular" delay={100} />
</Suspense>
<div data-testid="static-async-content">
This content is static async
</div>
)
}
export default function DynamicPage() {
return (
<div data-testid="dynamic-page-root">
<h1>Dynamic API Test</h1>
<h1>Dynamic API Test Cases</h1>
<p>
These cases demonstrate dynamic APIs that trigger dynamic rendering.
</p>
<section>
<h2>1. cookies() - Request cookies</h2>
<Suspense
fallback={<div data-testid="cookie-loading">Loading cookies...</div>}
>
<CookieContent />
</Suspense>
</section>
<section>
<h2>2. headers() - Request headers</h2>
<Suspense
fallback={<div data-testid="header-loading">Loading headers...</div>}
>
<HeaderContent />
</Suspense>
</section>
<section>
<h2>Dynamic APIs (will opt out of static rendering)</h2>
<CookieSection />
<HeaderSection />
<h2>3. connection() - Explicit dynamic opt-in</h2>
<Suspense
fallback={
<div data-testid="connection-loading">Loading connection...</div>
}
>
<ConnectionContent />
</Suspense>
</section>
<section>
<h2>Regular Async (no dynamic API)</h2>
<RegularSection />
<h2>4. Static async content (for comparison)</h2>
<Suspense
fallback={
<div data-testid="static-async-loading">Loading static...</div>
}
>
<StaticAsyncContent />
</Suspense>
</section>
</div>
)
......
import { Suspense } from 'react'
// Cached component that awaits params promise - triggers dynamic IO
async function DynamicContent({
params,
}: {
params: Promise<{ slug: string }>
}) {
'use cache'
const { slug } = await params
await new Promise((resolve) => setTimeout(resolve, 100))
return (
<div data-testid="dynamic-content">
<p>Loaded content for: {slug}</p>
</div>
)
}
// Static cached content that doesn't depend on params
async function StaticHeader() {
'use cache'
return (
<header data-testid="static-header">
<h1>Item Details</h1>
<p>This header is static and can be prerendered</p>
</header>
)
}
export default function ItemPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<div data-testid="item-page-root">
{/* Static cached part - can be prerendered */}
<Suspense
fallback={<div data-testid="header-loading">Loading header...</div>}
>
<StaticHeader />
</Suspense>
{/* Dynamic part - params promise unpacked under Suspense boundary */}
<main>
<Suspense
fallback={
<div data-testid="param-loading">Loading item details...</div>
}
>
<DynamicContent params={params} />
</Suspense>
</main>
{/* Another static section */}
<footer data-testid="static-footer">
<p>Static footer content</p>
</footer>
</div>
)
}
/** @type {import('next').NextConfig} */
module.exports = {
cacheComponents: true,
experimental: {
serverSourceMaps: true,
suspenseProfiling: true,
},
}
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