Unverified Commit 43dc6643 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Perf: Move chunkloading instrumentation to separate function (#91382)

## What?

The chunkloading instrumentation causes a GC root because of writing to
`globalThis.__next_require__` / `globalThis.__next_chunk_load__`.
Splitting it into a separate function reduces the scope being retained
in memory.

Switch onHeaders to use for loop which is faster.
parent 58a4c7b1
...@@ -2129,54 +2129,24 @@ function ErrorApp<T>({ ...@@ -2129,54 +2129,24 @@ function ErrorApp<T>({
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
export type BinaryStreamOf<T> = ReadableStream<Uint8Array> export type BinaryStreamOf<T> = ReadableStream<Uint8Array>
async function renderToHTMLOrFlightImpl( /**
req: BaseNextRequest, * Extracted to a separate function to prevent V8 from retaining the entire
res: BaseNextResponse, * `renderToHTMLOrFlightImpl` closure scope through globalThis.__next_require__.
url: ReturnType<typeof parseRelativeUrl>, * V8 shares a single Context object per scope for all closures; by creating
pagePath: string, * these closures in their own function scope, the globalThis references only
query: NextParsedUrlQuery, * retain `instrumented` and `cacheComponents`, not request-specific data like
renderOpts: RenderOpts, * req/res/workStore.
workStore: WorkStore, */
parsedRequestHeaders: ParsedRequestHeaders, function installGlobalModuleLoadingHandlers(
postponedState: PostponedState | null, ComponentMod: AppPageModule,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined, cacheComponents: boolean
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
) { ) {
const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) {
res.statusCode = 404
}
// A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to
// avoid that resources can be deduped by React Float if the same resource is
// rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
const requestTimestamp = Date.now()
const {
ComponentMod,
nextFontManifest,
serverActions,
assetPrefix = '',
enableTainting,
cacheComponents,
setIsrStatus,
} = renderOpts
const { cachedNavigations } = renderOpts.experimental
// We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) {
const instrumented = wrapClientComponentLoader(ComponentMod) const instrumented = wrapClientComponentLoader(ComponentMod)
// When we are prerendering if there is a cacheSignal for tracking // When we are prerendering if there is a cacheSignal for tracking
// cache reads we track calls to `loadChunk` and `require`. This allows us // cache reads we track calls to `loadChunk` and `require`. This allows us
// to treat chunk/module loading with similar semantics as cache reads to avoid // to treat chunk/module loading with similar semantics as cache reads to avoid
// module loading from causing a prerender to abort too early. // module loading from causing a prerender to abort too early.
const shouldTrackModuleLoading = () => { const shouldTrackModuleLoading = () => {
if (!cacheComponents) { if (!cacheComponents) {
return false return false
...@@ -2209,26 +2179,71 @@ async function renderToHTMLOrFlightImpl( ...@@ -2209,26 +2179,71 @@ async function renderToHTMLOrFlightImpl(
} }
} }
const __next_require__: typeof instrumented.require = (...args) => { // @ts-expect-error
globalThis.__next_require__ = (
...args: Parameters<typeof instrumented.require>
) => {
const exportsOrPromise = instrumented.require(...args) const exportsOrPromise = instrumented.require(...args)
if (shouldTrackModuleLoading()) { if (shouldTrackModuleLoading()) {
// requiring an async module returns a promise.
trackPendingImport(exportsOrPromise) trackPendingImport(exportsOrPromise)
} }
return exportsOrPromise return exportsOrPromise
} }
// @ts-expect-error
globalThis.__next_require__ = __next_require__
const __next_chunk_load__: typeof instrumented.loadChunk = (...args) => { // @ts-expect-error
globalThis.__next_chunk_load__ = (
...args: Parameters<typeof instrumented.loadChunk>
) => {
const loadingChunk = instrumented.loadChunk(...args) const loadingChunk = instrumented.loadChunk(...args)
if (shouldTrackModuleLoading()) { if (shouldTrackModuleLoading()) {
trackPendingChunkLoad(loadingChunk) trackPendingChunkLoad(loadingChunk)
} }
return loadingChunk return loadingChunk
} }
// @ts-expect-error }
globalThis.__next_chunk_load__ = __next_chunk_load__
async function renderToHTMLOrFlightImpl(
req: BaseNextRequest,
res: BaseNextResponse,
url: ReturnType<typeof parseRelativeUrl>,
pagePath: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts,
workStore: WorkStore,
parsedRequestHeaders: ParsedRequestHeaders,
postponedState: PostponedState | null,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
) {
const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) {
res.statusCode = 404
}
// A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to
// avoid that resources can be deduped by React Float if the same resource is
// rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
const requestTimestamp = Date.now()
const {
ComponentMod,
nextFontManifest,
serverActions,
assetPrefix = '',
enableTainting,
cacheComponents,
setIsrStatus,
} = renderOpts
const { cachedNavigations } = renderOpts.experimental
// We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) {
installGlobalModuleLoadingHandlers(ComponentMod, cacheComponents)
} }
if (process.env.__NEXT_DEV_SERVER && setIsrStatus && !cacheComponents) { if (process.env.__NEXT_DEV_SERVER && setIsrStatus && !cacheComponents) {
...@@ -3377,9 +3392,9 @@ async function renderToStream( ...@@ -3377,9 +3392,9 @@ async function renderToStream(
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
nonce, nonce,
onHeaders: (headers: Headers) => { onHeaders: (headers: Headers) => {
headers.forEach((value, key) => { for (const [key, value] of headers) {
appendHeader(key, value) appendHeader(key, value)
}) }
}, },
maxHeadersLength: reactMaxHeadersLength, maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent, bootstrapScriptContent,
......
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