Unverified Commit 53481e3f authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add 2nd cloned body to FinalizationRegistry. Only used RuntimeStyles component for webpack (#88577)

### What?

Reduces memory retention in two areas: response stream cleanup in
`cloneResponse` and unnecessary runtime style initialization in
Turbopack mode. Also adds a test fixture for standalone mode fetch
memory leak detection.

### Why?

Based on the reproduction provided in #85914, investigating potential
sources of memory retention. When a `ReadableStream` is tee'd, both
branches must be cancelled to release connection resources — previously
only one branch was registered for GC cancellation. Additionally,
`RuntimeStyles` and `_N_E_STYLE_LOAD` were always initialized even in
Turbopack mode where they are unused.

### How?

**`clone-response.ts`**: Register both `cloned1` and `cloned2` bodies
with the `FinalizationRegistry` so that when either response is garbage
collected, its stream branch is properly cancelled.

**`app-router.tsx`**: Guard `_N_E_STYLE_LOAD` and style tracking `Set`
initialization behind `!process.env.TURBOPACK && typeof window !==
'undefined'`. Rename the component to `RuntimeStylesForWebpack` and skip
rendering it entirely when using Turbopack.

Fixes #85914

---------
Co-authored-by: 's avatarUnghee Lee <unghee66@gmail.com>
parent a2409549
......@@ -523,7 +523,7 @@ function Router({
return (
<>
<HistoryUpdater appRouterState={state} />
<RuntimeStyles />
{process.env.TURBOPACK ? null : <RuntimeStylesForWebpack />}
<NavigationPromisesContext.Provider
value={instrumentedNavigationPromises}
>
......@@ -583,24 +583,30 @@ export default function AppRouter({
)
}
const runtimeStyles = new Set<string>()
let runtimeStyleChanged = new Set<() => void>()
globalThis._N_E_STYLE_LOAD = function (href: string) {
let len = runtimeStyles.size
runtimeStyles.add(href)
if (runtimeStyles.size !== len) {
runtimeStyleChanged.forEach((cb) => cb())
let runtimeStyles: Set<string> | undefined
let runtimeStyleChanged: Set<() => void> | undefined
if (!process.env.TURBOPACK && typeof window !== 'undefined') {
runtimeStyles = new Set<string>()
runtimeStyleChanged = new Set<() => void>()
globalThis._N_E_STYLE_LOAD = function (href: string) {
if (!runtimeStyles || !runtimeStyleChanged) return Promise.resolve()
let len = runtimeStyles.size
runtimeStyles.add(href)
if (runtimeStyles.size !== len) {
runtimeStyleChanged.forEach((cb) => cb())
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return Promise.resolve()
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return Promise.resolve()
}
function RuntimeStyles() {
function RuntimeStylesForWebpack() {
const [, forceUpdate] = React.useState(0)
const renderedStylesSize = runtimeStyles.size
const renderedStylesSize = runtimeStyles?.size ?? 0
useEffect(() => {
if (!runtimeStyles || !runtimeStyleChanged) return
const changed = () => forceUpdate((c) => c + 1)
runtimeStyleChanged.add(changed)
if (renderedStylesSize !== runtimeStyles.size) {
......@@ -612,7 +618,7 @@ function RuntimeStyles() {
}, [renderedStylesSize, forceUpdate])
const dplId = getDeploymentIdQueryOrEmptyString()
return [...runtimeStyles].map((href, i) => (
return [...(runtimeStyles || [])].map((href, i) => (
<link
key={i}
rel="stylesheet"
......
......@@ -46,24 +46,6 @@ export function cloneResponse(original: Response): [Response, Response] {
writable: false,
})
// The Fetch Standard allows users to skip consuming the response body by
// relying on garbage collection to release connection resources.
// https://github.com/nodejs/undici?tab=readme-ov-file#garbage-collection
//
// To cancel the stream you then need to cancel both resulting branches.
// Teeing a stream will generally lock it for the duration, preventing other
// readers from locking it.
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee
// cloned2 is stored in a react cache and cloned for subsequent requests.
// It is the original request, and is is garbage collected by a
// FinalizationRegistry in Undici, but since we're tee-ing the stream
// ourselves, we need to cancel clone1's stream (the response returned from
// our dedupe fetch) when clone1 is reclaimed, otherwise we leak memory.
if (registry && cloned1.body) {
registry.register(cloned1, new WeakRef(cloned1.body))
}
const cloned2 = new Response(body2, {
status: original.status,
statusText: original.statusText,
......@@ -78,5 +60,23 @@ export function cloneResponse(original: Response): [Response, Response] {
writable: false,
})
// The Fetch Standard allows users to skip consuming the response body by
// relying on garbage collection to release connection resources.
// https://github.com/nodejs/undici?tab=readme-ov-file#garbage-collection
//
// To cancel the stream you then need to cancel both resulting branches.
// Teeing a stream will generally lock it for the duration, preventing other
// readers from locking it.
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee
if (registry) {
if (cloned1.body) {
registry.register(cloned1, new WeakRef(cloned1.body))
}
if (cloned2.body) {
registry.register(cloned2, new WeakRef(cloned2.body))
}
}
return [cloned1, cloned2]
}
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