Unverified Commit 33173924 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Cache] Make caches error if called after prerender aborts (#96426)

Closes #96339

Caches that started filling after a prerender was aborted would produce
an empty stream, because an aborted `renderSignal` made [the signal we
pass to `prerender()` inside `use-cache-wrapper`] be aborted
immediately. So we produced an empty entry and saved it, essentially
poisoning the cache.

Fixed by removing `renderSignal` from the `AbortSignal.any(...)` we pass
in and returning a rejected promise before we get to the cache filling
codepath. This should not be observable to userspace because the
prerender is already aborted.
parent 4fd843fb
...@@ -91,6 +91,17 @@ export function makeDynamicHangingPromise<T>( ...@@ -91,6 +91,17 @@ export function makeDynamicHangingPromise<T>(
) )
} }
export function makeUntrackedHangingPromise<T>(
signal: AbortSignal,
route: string,
expression: string
): Promise<T> {
return makeHangingPromiseWithError(
signal,
new HangingPromiseRejectionError(route, expression)
)
}
/** /**
* Constructs a promise that never resolves, standing in for *runtime* data: * Constructs a promise that never resolves, standing in for *runtime* data:
* data that hangs during a static prerender but is available during a runtime * data that hangs during a static prerender but is available during a runtime
......
...@@ -42,6 +42,7 @@ import { ...@@ -42,6 +42,7 @@ import {
makeDynamicHangingPromise, makeDynamicHangingPromise,
makeRuntimeHangingPromise, makeRuntimeHangingPromise,
makeStageHangingPromise, makeStageHangingPromise,
makeUntrackedHangingPromise,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -1283,7 +1284,7 @@ async function generateCacheEntryImpl( ...@@ -1283,7 +1284,7 @@ async function generateCacheEntryImpl(
switch (outerWorkUnitStore.type) { switch (outerWorkUnitStore.type) {
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender': case 'prerender': {
const timeoutAbortController = new AbortController() const timeoutAbortController = new AbortController()
const timer = setTimeout( const timer = setTimeout(
() => { () => {
...@@ -1299,7 +1300,6 @@ async function generateCacheEntryImpl( ...@@ -1299,7 +1300,6 @@ async function generateCacheEntryImpl(
const abortSignal = dynamicAccessAbortSignal const abortSignal = dynamicAccessAbortSignal
? AbortSignal.any([ ? AbortSignal.any([
dynamicAccessAbortSignal, dynamicAccessAbortSignal,
outerWorkUnitStore.renderSignal,
timeoutAbortController.signal, timeoutAbortController.signal,
]) ])
: timeoutAbortController.signal : timeoutAbortController.signal
...@@ -1357,6 +1357,7 @@ async function generateCacheEntryImpl( ...@@ -1357,6 +1357,7 @@ async function generateCacheEntryImpl(
stream = prelude stream = prelude
} }
break break
}
case 'request': case 'request':
// TODO: We should just check if the render is abandonable. This is // TODO: We should just check if the render is abandonable. This is
// relevant in restart-on-cache-miss in general, so when we implement that // relevant in restart-on-cache-miss in general, so when we implement that
...@@ -1640,6 +1641,51 @@ export async function cache( ...@@ -1640,6 +1641,51 @@ export async function cache(
) )
} }
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore === undefined) {
throw new InvariantError(
'"use cache" cannot be used outside of App Router. Expected a WorkUnitStore.'
)
}
// In a prerender, tasky IO may result in cache reads that start
// after the prerender has already been aborted:
//
// await setTimeout(100) // we can't abort this uncached IO...
// await cachedData() // ...so we'll still get here even though the prerender aborted
//
// The prerender is over, so we should just return an erroring promise.
// (NOTE: we also shouldn't fill this cache, because it's behind uncached IO,
// so semantically it is not part of the prerender)
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime': {
if (workUnitStore.renderSignal.aborted) {
// We don't know if the cache itself is dynamic or runtime data,
// but the prerender is over, so it doesn't need to participate
// in runtime data tracking at all.
return makeUntrackedHangingPromise<never>(
workUnitStore.renderSignal,
workStore.route,
'"use cache" called after prerender ended'
)
}
break
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-client':
case 'validation-client':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
// Probe re-executions (the dev-server's hang-detection worker) short-circuit // Probe re-executions (the dev-server's hang-detection worker) short-circuit
// further down before any handler is consulted, so we skip handler selection // further down before any handler is consulted, so we skip handler selection
// entirely and the worker can boot without registering handlers at all. // entirely and the worker can boot without registering handlers at all.
...@@ -1705,13 +1751,6 @@ export async function cache( ...@@ -1705,13 +1751,6 @@ export async function cache(
return error return error
} }
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore === undefined) {
throw new InvariantError(
'"use cache" cannot be used outside of App Router. Expected a WorkUnitStore.'
)
}
const outerOwnerStack = const outerOwnerStack =
process.env.NODE_ENV !== 'production' process.env.NODE_ENV !== 'production'
? captureOuterOwnerStack(workUnitStore) ? captureOuterOwnerStack(workUnitStore)
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<LinkAccordion href="/uses-cache">/uses-cache</LinkAccordion>
</main>
)
}
import { revalidatePath, revalidateTag } from 'next/cache'
/** Evicts the entry so the prefetch's fill actually runs. */
export async function POST() {
revalidateTag('data', { expire: 0 })
revalidatePath('/uses-cache')
return Response.json({ ok: true })
}
import { cacheLife, cacheTag } from 'next/cache'
import { Suspense } from 'react'
export default function Page() {
return (
<main>
This page uses a cache
<Suspense fallback={<p id="fallback">Loading…</p>}>
<Late />
</Suspense>
</main>
)
}
async function Late() {
// In a prerender, this will resolve after the prerender is already aborted
// (both in prospective and final prerenders)
await new Promise((resolve) => setTimeout(resolve, 1000))
try {
const result = await getCachedData()
return <p id="data">{result}</p>
} finally {
console.log('after-cache-read')
}
}
async function getCachedData(): Promise<string> {
'use cache'
cacheLife('hours')
cacheTag('data')
console.log('running getCachedData')
return 'cached-data: ' + Date.now()
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import * as Playwright from 'playwright'
import { createRouterAct } from '../../../lib/router-act'
import { setTimeout } from 'timers/promises'
import { retry } from '../../../lib/next-test-utils'
describe('use cache called after tasky uncached IO', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
skipDeployment: true, // reads cli logs
})
if (isNextStart) {
it('does not store an incomplete cache entry in the cache handler', async () => {
// This is a regression test against for a bug:
// https://github.com/vercel/next.js/issues/96339
// If a cache read was initiated after the prerender was aborted (due to tasky IO),
// we'd try filling the cache, immediately abort the fill (because it was tied to
// renderSignal, which was already aborted), and then save the empty cache entry,
// effectively poisoning future reads of that cache.
// Revalidate /uses-cache (and, just to be safe, the cache that it references)
// so that we have a fresh prerender we can assert on
await next.fetch('/revalidate-uses-cache', { method: 'POST' })
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p) {
page = p
},
})
const act = createRouterAct(page)
// Prefetch the page, triggering a fresh prerender
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/uses-cache"]')
.click()
}, [
{
// Sanity check: the prefetch should not include the cache
includes: 'cached-data',
block: 'reject',
},
])
// Wait for the call to the "use cache" function to finish.
// Before the bugfix, reading the cache would result in an incorrect value
// being stored in the cache handler, so we need to make sure the cache
// is finished before we proceed.
await retry(
() => {
expect(next.cliOutput).toContain('after-cache-read')
},
5000,
200
)
await setTimeout(500)
// Navigate to the page. The response should include the cache
await act(
async () => {
await browser.elementByCss('a[href="/uses-cache"]').click()
},
{ includes: 'cached-data' }
)
// The bug manifested as the cache read throwing "Error: Connection closed."
// If we can observe the cache's value, then everything is ok.
expect(await browser.elementByCss('#data').text()).toMatch(
/cached-data: \d+/
)
})
} else {
it('resolves in dev', async () => {
// There's no prefetching in dev, so the best we can do is
// test that the cache resolves as expected.
const browser = await next.browser('/uses-cache')
expect(await browser.elementByCss('#data').text()).toMatch(
/cached-data: \d+/
)
})
}
})
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