Unverified Commit b7d438cf authored by Shu Ding's avatar Shu Ding Committed by GitHub

Invalidate prefetch cache when a tag or path has been revalidated on the server (#50848)

This makes sure that if `revalidateTag` is called in a Server Action, the client router cache and prefetch cache are invalidated correctly so following navigations won't reuse the cache that might hold stale data.

Similar case for `revalidatePath`. I left a TODO where we can't just invalidate the subtree under the revalidate paths because of current implementation limitations. To ensure correctness, we just do the same as `revalidateTag`.
parent 2010928d
...@@ -30,6 +30,10 @@ type FetchServerActionResult = { ...@@ -30,6 +30,10 @@ type FetchServerActionResult = {
redirectLocation: URL | undefined redirectLocation: URL | undefined
actionResult?: ActionResult actionResult?: ActionResult
actionFlightData?: FlightData | undefined | null actionFlightData?: FlightData | undefined | null
revalidatedParts: {
tag: boolean
paths: string[]
}
} }
async function fetchServerAction( async function fetchServerAction(
...@@ -60,6 +64,21 @@ async function fetchServerAction( ...@@ -60,6 +64,21 @@ async function fetchServerAction(
}) })
const location = res.headers.get('x-action-redirect') const location = res.headers.get('x-action-redirect')
let revalidatedParts: FetchServerActionResult['revalidatedParts']
try {
const revalidatedHeader = JSON.parse(
res.headers.get('x-action-revalidated') || '[0,[]]'
)
revalidatedParts = {
tag: !!revalidatedHeader[0],
paths: revalidatedHeader[1] || [],
}
} catch (e) {
revalidatedParts = {
tag: false,
paths: [],
}
}
const redirectLocation = location const redirectLocation = location
? new URL(addBasePath(location), window.location.origin) ? new URL(addBasePath(location), window.location.origin)
...@@ -77,6 +96,7 @@ async function fetchServerAction( ...@@ -77,6 +96,7 @@ async function fetchServerAction(
return { return {
actionFlightData: result as FlightData, actionFlightData: result as FlightData,
redirectLocation, redirectLocation,
revalidatedParts,
} }
// otherwise it's a tuple of [actionResult, actionFlightData] // otherwise it's a tuple of [actionResult, actionFlightData]
} else { } else {
...@@ -86,11 +106,13 @@ async function fetchServerAction( ...@@ -86,11 +106,13 @@ async function fetchServerAction(
actionResult, actionResult,
actionFlightData, actionFlightData,
redirectLocation, redirectLocation,
revalidatedParts,
} }
} }
} }
return { return {
redirectLocation, redirectLocation,
revalidatedParts,
} }
} }
...@@ -116,10 +138,27 @@ export function serverActionReducer( ...@@ -116,10 +138,27 @@ export function serverActionReducer(
} }
try { try {
// suspends until the server action is resolved. // suspends until the server action is resolved.
const { actionResult, actionFlightData, redirectLocation } = const {
readRecordValue( actionResult,
action.mutable.inFlightServerAction! actionFlightData,
) as Awaited<FetchServerActionResult> redirectLocation,
revalidatedParts,
} = readRecordValue(
action.mutable.inFlightServerAction!
) as Awaited<FetchServerActionResult>
// Invalidate the cache for the revalidated parts. This has to be done before the
// cache is updated with the action's flight data again.
if (revalidatedParts.tag) {
// Invalidate everything if the tag is set.
state.prefetchCache.clear()
} else if (revalidatedParts.paths.length > 0) {
// Invalidate all subtrees that are below the revalidated paths, and invalidate
// all the prefetch cache.
// TODO-APP: Currently the prefetch cache doesn't have subtree information,
// so we need to invalidate the entire cache if a path was revalidated.
state.prefetchCache.clear()
}
if (redirectLocation) { if (redirectLocation) {
// the redirection might have a flight data associated with it, so we'll populate the cache with it // the redirection might have a flight data associated with it, so we'll populate the cache with it
......
...@@ -43,6 +43,7 @@ export interface ServerActionMutable { ...@@ -43,6 +43,7 @@ export interface ServerActionMutable {
serverActionApplied?: boolean serverActionApplied?: boolean
previousTree?: FlightRouterState previousTree?: FlightRouterState
previousUrl?: string previousUrl?: string
prefetchCache?: AppRouterState['prefetchCache']
} }
/** /**
......
...@@ -127,6 +127,30 @@ function fetchIPv4v6( ...@@ -127,6 +127,30 @@ function fetchIPv4v6(
}) })
} }
async function addRevalidationHeader(
res: ServerResponse,
staticGenerationStore: StaticGenerationStore
) {
await Promise.all(staticGenerationStore.pendingRevalidates || [])
// If a tag was revalidated, the client router needs to invalidate all the
// client router cache as they may be stale. And if a path was revalidated, the
// client needs to invalidate all subtrees below that path.
// To keep the header size small, we use a tuple of [isTagRevalidated ? 1 : 0, [paths]]
// instead of a JSON object.
// TODO-APP: Currently the prefetch cache doesn't have subtree information,
// so we need to invalidate the entire cache if a path was revalidated.
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty.
res.setHeader(
'x-action-revalidated',
JSON.stringify([staticGenerationStore.revalidatedTags?.length ? 1 : 0, []])
)
}
async function createRedirectRenderResult( async function createRedirectRenderResult(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -350,7 +374,7 @@ export async function handleAction({ ...@@ -350,7 +374,7 @@ export async function handleAction({
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
await Promise.all(staticGenerationStore.pendingRevalidates || []) await addRevalidationHeader(res, staticGenerationStore)
actionResult = await generateFlight({ actionResult = await generateFlight({
actionResult: Promise.resolve(returnVal), actionResult: Promise.resolve(returnVal),
...@@ -367,7 +391,7 @@ export async function handleAction({ ...@@ -367,7 +391,7 @@ export async function handleAction({
// if it's a fetch action, we don't want to mess with the status code // if it's a fetch action, we don't want to mess with the status code
// and we'll handle it on the client router // and we'll handle it on the client router
await Promise.all(staticGenerationStore.pendingRevalidates || []) await addRevalidationHeader(res, staticGenerationStore)
if (isFetchAction) { if (isFetchAction) {
return createRedirectRenderResult( return createRedirectRenderResult(
...@@ -394,7 +418,8 @@ export async function handleAction({ ...@@ -394,7 +418,8 @@ export async function handleAction({
} else if (isNotFoundError(err)) { } else if (isNotFoundError(err)) {
res.statusCode = 404 res.statusCode = 404
await Promise.all(staticGenerationStore.pendingRevalidates || []) await addRevalidationHeader(res, staticGenerationStore)
if (isFetchAction) { if (isFetchAction) {
const promise = Promise.reject(err) const promise = Promise.reject(err)
try { try {
......
...@@ -502,6 +502,61 @@ createNextDescribe( ...@@ -502,6 +502,61 @@ createNextDescribe(
return newRandomNumber !== randomNumber ? 'success' : 'failure' return newRandomNumber !== randomNumber ? 'success' : 'failure'
}, 'success') }, 'success')
}) })
it.each(['tag', 'path'])(
'should invalidate client cache when %s is revalidate',
async (type) => {
const browser = await next.browser('/revalidate')
await browser.refresh()
const thankYouNext = await browser
.elementByCss('#thankyounext')
.text()
await browser.elementByCss('#another').click()
await check(async () => {
return browser.elementByCss('#title').text()
}, 'another route')
const newThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
// Should be the same number
expect(thankYouNext).toEqual(newThankYouNext)
await browser.elementByCss('#back').click()
if (type === 'tag') {
await browser.elementByCss('#revalidate-thankyounext').click()
} else {
await browser.elementByCss('#revalidate-path').click()
}
// Should be different
let revalidatedThankYouNext
await check(async () => {
revalidatedThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
return thankYouNext !== revalidatedThankYouNext
? 'success'
: 'failure'
}, 'success')
await browser.elementByCss('#another').click()
// The other page should be revalidated too
await check(async () => {
const newThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
return revalidatedThankYouNext === newThankYouNext
? 'success'
: 'failure'
}, 'success')
}
)
}) })
} }
) )
import { revalidateTag } from 'next/cache'
import Link from 'next/link'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
next: { revalidate: 3600, tags: ['thankyounext'] },
}
).then((res) => res.text())
return (
<>
<h1 id="title">another route</h1>
<Link href="/revalidate" id="back">
Back
</Link>
<p>
{' '}
revalidate (tags: thankyounext): <span id="thankyounext">{data}</span>
</p>
<form>
<button
id="revalidate-tag"
formAction={async () => {
'use server'
revalidateTag('thankyounext')
}}
>
revalidate thankyounext
</button>
</form>
</>
)
}
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
revalidateTag, revalidateTag,
} from 'next/cache' } from 'next/cache'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import Link from 'next/link'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
...@@ -11,14 +12,14 @@ export default async function Page() { ...@@ -11,14 +12,14 @@ export default async function Page() {
const data = await fetch( const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page', 'https://next-data-api-endpoint.vercel.app/api/random?page',
{ {
next: { revalidate: 360, tags: ['thankyounext'] }, next: { revalidate: 3600, tags: ['thankyounext'] },
} }
).then((res) => res.text()) ).then((res) => res.text())
const data2 = await fetch( const data2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=b', 'https://next-data-api-endpoint.vercel.app/api/random?a=b',
{ {
next: { revalidate: 360, tags: ['thankyounext', 'justputit'] }, next: { revalidate: 3600, tags: ['thankyounext', 'justputit'] },
} }
).then((res) => res.text()) ).then((res) => res.text())
...@@ -45,7 +46,14 @@ export default async function Page() { ...@@ -45,7 +46,14 @@ export default async function Page() {
<p>/revalidate</p> <p>/revalidate</p>
<p> <p>
{' '} {' '}
revalidate (tags: thankyounext): <span id="thankyounext">{data}</span> revalidate (tags: thankyounext): <span id="thankyounext">
{data}
</span>{' '}
<span>
<Link href="/revalidate-2" id="another">
/revalidate/another-route
</Link>
</span>
</p> </p>
<p> <p>
revalidate (tags: thankyounext, justputit):{' '} revalidate (tags: thankyounext, justputit):{' '}
......
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