Unverified Commit 40a91948 authored by Josh Story's avatar Josh Story Committed by GitHub

Include async module evaluation in client loading metrics (#99427)

## Summary

Include async client-module evaluation in loading metrics. A module with
top-level `await` can make `require()` return a Promise; measuring only
until that return omits the subsequent evaluation wait. This follows
#99322 and addresses [Hendrik’s
review](https://github.com/vercel/next.js/pull/99322#discussion_r4132744744).

Observe native Promise resolution and rejection while preserving the
original return value and per-render attribution. Synchronous modules
keep their existing behavior, including exports named `then` and thrown
errors.

## Verification

- End-to-end regression: a real Client Component waits five seconds
during top-level `await`; an HTML request must report more than one
second of accumulated loading time through the standard Performance API.
The pre-fix code reported only 38 ms; the fixed code passes.
- Replaced the PR-added mocked-loader tests. The existing eight logger
tests remain unchanged and pass.
- Full client-loading group: dev Webpack and production Turbopack, 6
passed each. Types, lint, formatting, and the full build pass.

<!-- NEXT_JS_LLM -->
parent 1e0b765e
...@@ -119,11 +119,25 @@ export function wrapClientComponentLoader( ...@@ -119,11 +119,25 @@ export function wrapClientComponentLoader(
const startTime = performance.now() const startTime = performance.now()
tracker.beginRequire(startTime) tracker.beginRequire(startTime)
let result: ReturnType<AppPageModule['__next_app__']['require']>
try { try {
return ComponentMod.__next_app__.require(...args) result = ComponentMod.__next_app__.require(...args)
} finally { } catch (error) {
tracker.finishRequire(startTime, performance.now()) tracker.finishRequire(startTime, performance.now())
throw error
} }
// Webpack and Turbopack return native Promises for async modules. A
// synchronous module may export `then`, so do not probe arbitrary exports.
if (result instanceof Promise) {
const onSettled = () => {
tracker.finishRequire(startTime, performance.now())
}
result.then(onSettled, onSettled)
} else {
tracker.finishRequire(startTime, performance.now())
}
return result
}, },
loadChunk: (...args) => { loadChunk: (...args) => {
const tracker = workAsyncStorage.getStore()?.clientComponentLoadTracker const tracker = workAsyncStorage.getStore()?.clientComponentLoadTracker
......
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
const measureName =
'client-component-loading-test:next-client-component-loading'
export async function DELETE() {
performance.clearMeasures(measureName)
return new Response(null, { status: 204 })
}
export async function GET() {
return Response.json(
performance
.getEntriesByName(measureName, 'measure')
.map((entry) => entry.duration)
)
}
'use client'
if (typeof window === 'undefined') {
await new Promise((resolve) => setTimeout(resolve, 5_000))
}
export default function AsyncClient() {
return <span id="slow-async-client">async client component</span>
}
import { connection } from 'next/server'
import AsyncClient from './async-client'
export default async function Page() {
await connection()
return <AsyncClient />
}
...@@ -58,6 +58,7 @@ function setup({ useDirectEntrypointHandler, useNodeMiddleware }) { ...@@ -58,6 +58,7 @@ function setup({ useDirectEntrypointHandler, useNodeMiddleware }) {
env: { env: {
TEST_OTEL_COLLECTOR_PORT: String(COLLECTOR_PORT), TEST_OTEL_COLLECTOR_PORT: String(COLLECTOR_PORT),
TEST_CLIENT_COMPONENT_GATE_PORT: String(CLIENT_COMPONENT_GATE_PORT), TEST_CLIENT_COMPONENT_GATE_PORT: String(CLIENT_COMPONENT_GATE_PORT),
NEXT_OTEL_PERFORMANCE_PREFIX: 'client-component-loading-test',
NEXT_TELEMETRY_DISABLED: '1', NEXT_TELEMETRY_DISABLED: '1',
}, },
} }
...@@ -471,6 +472,26 @@ describe.each( ...@@ -471,6 +472,26 @@ describe.each(
await flush() await flush()
expect(loadingSpans(traceId)).toEqual([earlySpan]) expect(loadingSpans(traceId)).toEqual([earlySpan])
}) })
it('includes async client module evaluation in HTML loading duration', async () => {
const measurePath = '/api/app/test/client-component-measure'
const reset = await next.fetch(measurePath, { method: 'DELETE' })
expect(reset.status).toBe(204)
const response = await next.fetch('/app/test/slow-async-client', {
headers: { traceparent: traceparent(newTraceId()) },
})
expect(response.status).toBe(200)
expect(await response.text()).toContain(
'<span id="slow-async-client">async client component</span>'
)
const measurements = await next.fetch(measurePath)
expect(measurements.status).toBe(200)
const durations = (await measurements.json()) as number[]
expect(durations).toHaveLength(1)
expect(durations[0]).toBeGreaterThan(1_000)
})
}) })
} }
......
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