Unverified Commit 1722e45c authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Fix client component loading span timing (#96455)

## Summary

- Measure the existing client-component loading span from its first
observed start through the latest module or chunk settlement.
- Keep overlapping and nested loads within one valid timing interval
instead of accumulating durations onto the first start time.
- Preserve the original `loadChunk` promise identity while observing
both fulfilled and rejected settlements.
- Handle rejected chunk loads without creating a second unhandled
rejecting promise.
- Avoid ending the span while another tracked load remains pending.

This corrects an existing span; it does not introduce a new span type.

## Verification

- `pnpm exec jest --runInBand
packages/next/src/server/client-component-renderer-logger.test.ts`
- The final focused Request Insights matrix passed 10 suites and 82/82
tests, including overlapping, nested, pending, fulfilled, and rejected
client loads.
- `pnpm --filter=next build`
parent ec8b5435
......@@ -2698,7 +2698,10 @@ async function prepareAppPageRender(
req.originalRequest.on('end', () => {
if ('performance' in globalThis) {
const metrics = getClientComponentLoaderMetrics({ reset: true })
if (metrics) {
if (
metrics &&
metrics.clientComponentLoadEnd >= metrics.clientComponentLoadStart
) {
getTracer()
.startSpan(NextNodeServerSpan.clientComponentLoading, {
startTime: metrics.clientComponentLoadStart,
......@@ -2708,10 +2711,7 @@ async function prepareAppPageRender(
'next.span_type': NextNodeServerSpan.clientComponentLoading,
},
})
.end(
metrics.clientComponentLoadStart +
metrics.clientComponentLoadTimes
)
.end(metrics.clientComponentLoadEnd)
}
}
})
......
import type { AppPageModule } from './route-modules/app-page/module'
import {
getClientComponentLoaderMetrics,
wrapClientComponentLoader,
} from './client-component-renderer-logger'
function createComponentModule(
require: (
...args: Parameters<AppPageModule['__next_app__']['require']>
) => unknown,
loadChunk: (
...args: Parameters<AppPageModule['__next_app__']['loadChunk']>
) => Promise<unknown>
) {
return {
__next_app__: { require, loadChunk },
} as unknown as AppPageModule
}
describe('client component renderer logger', () => {
afterEach(() => {
getClientComponentLoaderMetrics({ reset: true })
jest.restoreAllMocks()
})
it('tracks elapsed boundaries separately from sequential load time', () => {
jest
.spyOn(performance, 'now')
.mockReturnValueOnce(100)
.mockReturnValueOnce(110)
.mockReturnValueOnce(150)
.mockReturnValueOnce(160)
const loader = wrapClientComponentLoader(
createComponentModule(
() => undefined,
async () => undefined
),
true
)
loader.require('first')
loader.require('second')
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 160,
clientComponentLoadTimes: 20,
clientComponentLoadCount: 2,
})
})
it('preserves accumulated load time for nested requires', () => {
jest
.spyOn(performance, 'now')
.mockReturnValueOnce(100)
.mockReturnValueOnce(110)
.mockReturnValueOnce(120)
.mockReturnValueOnce(130)
let loader: AppPageModule['__next_app__']
loader = wrapClientComponentLoader(
createComponentModule(
(id) => {
if (id === 'outer') {
loader.require('inner')
}
},
async () => undefined
),
true
)
loader.require('outer')
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 130,
clientComponentLoadTimes: 40,
clientComponentLoadCount: 2,
})
})
it('tracks the last settlement across overlapping chunk loads', async () => {
jest
.spyOn(performance, 'now')
.mockReturnValueOnce(100)
.mockReturnValueOnce(110)
.mockReturnValueOnce(130)
.mockReturnValueOnce(170)
let resolveFirst!: () => void
let resolveSecond!: () => void
const first = new Promise<void>((resolve) => {
resolveFirst = resolve
})
const second = new Promise<void>((resolve) => {
resolveSecond = resolve
})
const loader = wrapClientComponentLoader(
createComponentModule(
() => undefined,
(id) => (id === 'first' ? first : second)
),
true
)
expect(loader.loadChunk('first')).toBe(first)
expect(loader.loadChunk('second')).toBe(second)
resolveSecond()
await second
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 130,
clientComponentLoadTimes: 20,
clientComponentLoadCount: 0,
})
resolveFirst()
await first
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 170,
clientComponentLoadTimes: 90,
clientComponentLoadCount: 0,
})
})
it('leaves the end boundary unset while a chunk load is pending', async () => {
jest
.spyOn(performance, 'now')
.mockReturnValueOnce(100)
.mockReturnValueOnce(150)
let resolveChunk!: () => void
const chunk = new Promise<void>((resolve) => {
resolveChunk = resolve
})
const loader = wrapClientComponentLoader(
createComponentModule(
() => undefined,
() => chunk
),
true
)
expect(loader.loadChunk('pending')).toBe(chunk)
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 0,
clientComponentLoadTimes: 0,
clientComponentLoadCount: 0,
})
resolveChunk()
await chunk
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 150,
clientComponentLoadTimes: 50,
clientComponentLoadCount: 0,
})
})
it('tracks rejected chunk loads without changing the returned promise', async () => {
jest
.spyOn(performance, 'now')
.mockReturnValueOnce(100)
.mockReturnValueOnce(150)
const error = new Error('chunk failed')
const chunk = Promise.reject(error)
const loader = wrapClientComponentLoader(
createComponentModule(
() => undefined,
() => chunk
),
true
)
expect(loader.loadChunk('rejected')).toBe(chunk)
await expect(chunk).rejects.toBe(error)
expect(getClientComponentLoaderMetrics()).toEqual({
clientComponentLoadStart: 100,
clientComponentLoadEnd: 150,
clientComponentLoadTimes: 50,
clientComponentLoadCount: 0,
})
})
})
......@@ -2,6 +2,7 @@ import type { AppPageModule } from './route-modules/app-page/module'
// Combined load times for loading client components
let clientComponentLoadStart = 0
let clientComponentLoadEnd = 0
let clientComponentLoadTimes = 0
let clientComponentLoadCount = 0
......@@ -28,17 +29,27 @@ export function wrapClientComponentLoader(
clientComponentLoadCount += 1
return ComponentMod.__next_app__.require(...args)
} finally {
clientComponentLoadTimes += performance.now() - startTime
const endTime = performance.now()
clientComponentLoadEnd = endTime
clientComponentLoadTimes += endTime - startTime
}
},
loadChunk: (...args) => {
const startTime = performance.now()
if (clientComponentLoadStart === 0) {
clientComponentLoadStart = startTime
}
const result = ComponentMod.__next_app__.loadChunk(...args)
// Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.
// We only need to know when it's settled.
result.finally(() => {
clientComponentLoadTimes += performance.now() - startTime
})
const onSettled = () => {
const endTime = performance.now()
clientComponentLoadEnd = endTime
clientComponentLoadTimes += endTime - startTime
}
result.then(onSettled, onSettled)
return result
},
}
......@@ -52,12 +63,14 @@ export function getClientComponentLoaderMetrics(
? undefined
: {
clientComponentLoadStart,
clientComponentLoadEnd,
clientComponentLoadTimes,
clientComponentLoadCount,
}
if (options.reset) {
clientComponentLoadStart = 0
clientComponentLoadEnd = 0
clientComponentLoadTimes = 0
clientComponentLoadCount = 0
}
......
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