Unverified Commit adb41b6f authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Fix request context retention in cookies/headers/draftMode

Immediately resolved cookies(), headers(), and draftMode() promises were
created while the work and work-unit async-local stores were active. For
cookies() and headers() the promise is cached in the module-scope
CachedCookies/CachedHeaders WeakMaps, so it retained the originating
request context through its async-hooks resource store for as long as the
WeakMap entry lived - the same leak class as #96533 (fixed for
params/searchParams in #96573), in the request APIs that PR did not
cover. Per-request keys make the retention transient, but the WeakMap
ephemeron cycle (the promise resolves to its key object and captures the
store that owns the key) defeats minor GC, so every request that reads
them leaves its full request context in old space until a major GC - the
same accumulation mechanism measured in #96533 on Node 22.

Create these promises inside the work store's clean async snapshot
instead, matching the approach of #96573, so framework-created request
API promises never root the request context that produced them. No
WeakRef accessors are needed: unlike the searchParams erroring proxy,
these production paths create plain resolved promises with no deferred
store access.

draftMode() gets the same treatment for consistency, and its vestigial
draft-mode cache is removed: CachedDraftModes has been get-only since the
.set was dropped in #84179, so no immortal-key retention ever existed
there; the clean snapshot keeps all four APIs uniform regardless.

Adds an async-hooks e2e regression test proving ordinary render promises
capture the stores while cookies()/headers()/draftMode() promises do not,
covering a dynamic request (request store, exercises the per-request
WeakMap keys) and a force-static page prerendered at build time
(exercises the forceStatic override paths).

Validation: the regression test fails without the fix (both cases) and
passes with it in both bundlers; existing suites for the touched APIs
pass (draft-mode, draft-mode-middleware, dynamic-data,
headers-static-bailout); tsc/Prettier/ESLint clean; autoreview panel
findings addressed.

Related: #96533, #96573
Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 865d623a
......@@ -46,7 +46,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// When using forceStatic we override all other logic and always just return an empty
// cookies object without tracking
const underlyingCookies = createEmptyCookies()
return makeUntrackedCookies(underlyingCookies)
return makeUntrackedCookies(underlyingCookies, workStore)
}
if (workStore.dynamicShouldError) {
......@@ -106,13 +106,13 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
workUnitStore.cookies
)
} else {
return makeUntrackedCookies(workUnitStore.cookies)
return makeUntrackedCookies(workUnitStore.cookies, workStore)
}
}
case 'private-cache':
// Private caches are delayed until the runtime stage in use-cache-wrapper,
// so we don't need an additional delay here.
return makeUntrackedCookies(workUnitStore.cookies)
return makeUntrackedCookies(workUnitStore.cookies, workStore)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
......@@ -143,7 +143,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
return workUnitStore.asyncApiPromises.cookies
}
} else {
return makeUntrackedCookies(underlyingCookies)
return makeUntrackedCookies(underlyingCookies, workStore)
}
default:
workUnitStore satisfies never
......@@ -186,14 +186,20 @@ function makeHangingCookies(
}
function makeUntrackedCookies(
underlyingCookies: ReadonlyRequestCookies
underlyingCookies: ReadonlyRequestCookies,
workStore: WorkStore
): Promise<ReadonlyRequestCookies> {
const cachedCookies = CachedCookies.get(underlyingCookies)
if (cachedCookies) {
return cachedCookies
}
const promise = Promise.resolve(underlyingCookies)
// Create the promise in a clean async snapshot so the cached promise does
// not retain the request's async-local stores through its async-hooks
// resource store for as long as the WeakMap entry lives.
const promise = workStore.runInCleanSnapshot(() =>
Promise.resolve(underlyingCookies)
)
CachedCookies.set(underlyingCookies, promise)
return promise
......
......@@ -45,11 +45,11 @@ export function draftMode(): Promise<DraftMode> {
new DraftMode(workUnitStore.draftMode)
)
} else {
return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)
return createDraftModePromise(workUnitStore.draftMode, workStore)
}
}
case 'request':
return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)
return createDraftModePromise(workUnitStore.draftMode, workStore)
case 'cache':
case 'private-cache':
......@@ -63,7 +63,7 @@ export function draftMode(): Promise<DraftMode> {
)
if (draftModeProvider) {
return createOrGetCachedDraftMode(draftModeProvider, workStore)
return createDraftModePromise(draftModeProvider, workStore)
}
// Otherwise, we fall through to providing an empty draft mode.
......@@ -72,7 +72,7 @@ export function draftMode(): Promise<DraftMode> {
case 'prerender-ppr':
case 'prerender-legacy':
// Return empty draft mode
return createOrGetCachedDraftMode(null, workStore)
return createDraftModePromise(null, workStore)
case 'prerender-client':
case 'validation-client': {
const exportName = '`draftMode`'
......@@ -90,29 +90,27 @@ export function draftMode(): Promise<DraftMode> {
}
}
function createOrGetCachedDraftMode(
function createDraftModePromise(
draftModeProvider: DraftModeProvider | null,
workStore: WorkStore | undefined
): Promise<DraftMode> {
const cacheKey = draftModeProvider ?? NullDraftMode
const cachedDraftMode = CachedDraftModes.get(cacheKey)
if (cachedDraftMode) {
return cachedDraftMode
}
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
const route = workStore?.route
return createDraftModeWithDevWarnings(draftModeProvider, route)
} else if (workStore) {
// Create the promise in a clean async snapshot so it does not capture the
// request's async-local stores through its async-hooks resource store.
// Framework-created request API promises should never root the request
// context that produced them; this matches params, searchParams,
// cookies, and headers.
return workStore.runInCleanSnapshot(() =>
Promise.resolve(new DraftMode(draftModeProvider))
)
} else {
return Promise.resolve(new DraftMode(draftModeProvider))
}
}
interface CacheLifetime {}
const NullDraftMode = {}
const CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()
function createDraftModeWithDevWarnings(
underlyingProvider: null | DraftModeProvider,
route: undefined | string
......
......@@ -53,7 +53,7 @@ export function headers(): Promise<ReadonlyHeaders> {
// When using forceStatic we override all other logic and always just return an empty
// headers object without tracking
const underlyingHeaders = HeadersAdapter.seal(new Headers({}))
return makeUntrackedHeaders(underlyingHeaders)
return makeUntrackedHeaders(underlyingHeaders, workStore)
}
if (workUnitStore) {
......@@ -134,13 +134,13 @@ export function headers(): Promise<ReadonlyHeaders> {
workUnitStore.headers
)
} else {
return makeUntrackedHeaders(workUnitStore.headers)
return makeUntrackedHeaders(workUnitStore.headers, workStore)
}
}
case 'private-cache':
// Private caches are delayed until the runtime stage in use-cache-wrapper,
// so we don't need an additional delay here.
return makeUntrackedHeaders(workUnitStore.headers)
return makeUntrackedHeaders(workUnitStore.headers, workStore)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
......@@ -156,7 +156,7 @@ export function headers(): Promise<ReadonlyHeaders> {
} else if (workUnitStore.asyncApiPromises) {
return workUnitStore.asyncApiPromises.headers
} else {
return makeUntrackedHeaders(workUnitStore.headers)
return makeUntrackedHeaders(workUnitStore.headers, workStore)
}
break
default:
......@@ -193,14 +193,20 @@ function makeHangingHeaders(
}
function makeUntrackedHeaders(
underlyingHeaders: ReadonlyHeaders
underlyingHeaders: ReadonlyHeaders,
workStore: WorkStore
): Promise<ReadonlyHeaders> {
const cachedHeaders = CachedHeaders.get(underlyingHeaders)
if (cachedHeaders) {
return cachedHeaders
}
const promise = Promise.resolve(underlyingHeaders)
// Create the promise in a clean async snapshot so the cached promise does
// not retain the request's async-local stores through its async-hooks
// resource store for as long as the WeakMap entry lives.
const promise = workStore.runInCleanSnapshot(() =>
Promise.resolve(underlyingHeaders)
)
CachedHeaders.set(underlyingHeaders, promise)
return promise
......
......@@ -237,6 +237,7 @@
"test/e2e/app-dir/prefetching-not-found/prefetching-not-found.test.ts",
"test/e2e/app-dir/prerender-encoding/prerender-encoding.test.ts",
"test/e2e/app-dir/react-max-headers-length/react-max-headers-length.test.ts",
"test/e2e/app-dir/request-api-context-retention/request-api-context-retention.test.ts",
"test/e2e/app-dir/revalidate-dynamic/revalidate-dynamic.test.ts",
"test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts",
"test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts",
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { createHook } from 'node:async_hooks'
import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external'
import { workUnitAsyncStorage } from 'next/dist/server/app-render/work-unit-async-storage.external'
const promiseContextSymbol = Symbol.for('next.test.promise-context')
createHook({
init(_asyncId, type, _triggerAsyncId, resource) {
if (type === 'PROMISE') {
Object.defineProperty(resource, promiseContextSymbol, {
value: {
workStore: workAsyncStorage.getStore() !== undefined,
workUnitStore: workUnitAsyncStorage.getStore() !== undefined,
},
})
}
},
}).enable()
type PromiseContext = {
workStore: boolean
workUnitStore: boolean
}
export function getPromiseContext(promise: Promise<unknown>): PromiseContext {
const context = (
promise as unknown as Record<symbol, PromiseContext | undefined>
)[promiseContextSymbol]
if (!context) {
throw new Error('Promise was created before context tracking was enabled')
}
return context
}
import { connection } from 'next/server'
import { cookies, draftMode, headers } from 'next/headers'
import { getPromiseContext } from '../promise-context'
export default async function Page() {
await connection()
const controlContext = getPromiseContext(Promise.resolve())
const cookiesContext = getPromiseContext(cookies())
const headersContext = getPromiseContext(headers())
const draftModeContext = getPromiseContext(draftMode())
return (
<main>
<p id="control-captures-work-store">{String(controlContext.workStore)}</p>
<p id="control-captures-work-unit-store">
{String(controlContext.workUnitStore)}
</p>
<p id="cookies-captures-work-store">{String(cookiesContext.workStore)}</p>
<p id="cookies-captures-work-unit-store">
{String(cookiesContext.workUnitStore)}
</p>
<p id="headers-captures-work-store">{String(headersContext.workStore)}</p>
<p id="headers-captures-work-unit-store">
{String(headersContext.workUnitStore)}
</p>
<p id="draft-mode-captures-work-store">
{String(draftModeContext.workStore)}
</p>
<p id="draft-mode-captures-work-unit-store">
{String(draftModeContext.workUnitStore)}
</p>
</main>
)
}
import { cookies, draftMode, headers } from 'next/headers'
import { getPromiseContext } from '../promise-context'
export const dynamic = 'force-static'
export default async function Page() {
const controlContext = getPromiseContext(Promise.resolve())
const cookiesContext = getPromiseContext(cookies())
const headersContext = getPromiseContext(headers())
const draftModeContext = getPromiseContext(draftMode())
return (
<main>
<p id="control-captures-work-store">{String(controlContext.workStore)}</p>
<p id="control-captures-work-unit-store">
{String(controlContext.workUnitStore)}
</p>
<p id="cookies-captures-work-store">{String(cookiesContext.workStore)}</p>
<p id="cookies-captures-work-unit-store">
{String(cookiesContext.workUnitStore)}
</p>
<p id="headers-captures-work-store">{String(headersContext.workStore)}</p>
<p id="headers-captures-work-unit-store">
{String(headersContext.workUnitStore)}
</p>
<p id="draft-mode-captures-work-store">
{String(draftModeContext.workStore)}
</p>
<p id="draft-mode-captures-work-unit-store">
{String(draftModeContext.workUnitStore)}
</p>
</main>
)
}
import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
function expectDetachedRequestApis(html: string) {
const $ = cheerio.load(html)
expect($('#control-captures-work-store').text()).toBe('true')
expect($('#control-captures-work-unit-store').text()).toBe('true')
expect($('#cookies-captures-work-store').text()).toBe('false')
expect($('#cookies-captures-work-unit-store').text()).toBe('false')
expect($('#headers-captures-work-store').text()).toBe('false')
expect($('#headers-captures-work-unit-store').text()).toBe('false')
expect($('#draft-mode-captures-work-store').text()).toBe('false')
expect($('#draft-mode-captures-work-unit-store').text()).toBe('false')
}
describe('request api context retention', () => {
const { next, isNextStart, isNextDeploy } = nextTestSetup({
files: __dirname,
})
if (!isNextStart && !isNextDeploy) {
it.skip('only runs in production modes', () => {})
return
}
it('does not retain a dynamic request context through request apis', async () => {
const response = await next.fetch('/session-apis')
expect(response.status).toBe(200)
expectDetachedRequestApis(await response.text())
})
it('does not retain the prerender context through request apis', async () => {
// The static page is prerendered at build time. Its cookies()/headers()
// promises resolve to empty request data through the forceStatic
// override path, and draftMode() resolves to an empty DraftMode through
// the prerender branch; all of those promises must be created without
// capturing the prerender's async-local stores.
const response = await next.fetch('/static-apis')
expect(response.status).toBe(200)
expectDetachedRequestApis(await response.text())
})
})
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