Unverified Commit 562d3e7f authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

test: add PPF coverage to use-cache and RDC tests (#99417)

We weren't running the use-cache/resume-data-cache test suites in PPF.
some of the tests fail due to the bug that is fixed in #98005 (although
interestingly the fetch-cache tests only fail in deploy mode, because in
`next start` we heal a bad RDC using outputs from
`.next/cache/fetch-cache`). a bunch of refactoring was needed (some
tests were producing false negatives, flakily), so i split this into a
separate PR to confirm behavior before/after the fix.

### `use-cache.test.ts`

- I've refactored the tests to use timestamps and be a bit more
debuggable. previously, they'd fail with a hydration error, and it was
hard to pinpoint the cause. including a name lets us know which cache
was mismatched, and assert that the values of the cache are consistent
across the HTML shell / resume.
- the tests for exluded caches now include more complete assertions on
what content is and isn't included in the HTML shell

### `resume-data-cache.test.ts`

This one needed quite a bit of work:

- The `use cache` and `fetch cache` tests were not independent. they
both used the same page and revalidated the same tag, which means that a
revalidation from the first test affected the outcome of the second
test. i've split them into two separate pages with two separate tags to
make the behavior consistent.
- Multiple tests fetched the same URL (with `fetch(..., { cache:
'force-cache' }`), which made them interfere with each other's fetch
caches. the URLs are now different so the tests are actually independent
- Some cache values are now tagged with a name and timestamp. The name
is used for asserting consistency, the timestamp is for improved
debuggability (provides ordering)
- The action revalidation tests weren't checking what the value from the
build-time prerender was actually supposed to be, so they were passing
even if the build-time RDC was not used at all
- The tests that use `browser()` now assert that there should be no
hydration warning, which can happen due to the PPF bug (due to
inconsistent cache values across HTML shell/resume)
- **the revalidation assertions are very flaky in deploy**, and i've had
to disable them to avoid introducing a test that fails often. i'm not
sure how they were passing before.
parent 8f4e4b64
import { Suspense } from 'react'
import { connection } from 'next/server'
import { fetchRandomWithForceCache } from '../../../utils'
async function DynamicComponent() {
await connection()
return null
}
const KEY = 'test-fetch-cache-initial'
async function getRandomNumber() {
const res = await fetchRandomWithForceCache({
key: KEY,
// no tag - this entry is not meant to be revalidated
tag: undefined,
})
const dateHeader = res.headers.get('date')
const timestamp = dateHeader ? new Date(dateHeader).getTime() : 'time_unknown'
const text = await res.text()
return `fetch-random-${timestamp}-${text}`
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { fetchRandomWithForceCache } from '../../../utils'
async function DynamicComponent() {
await connection()
return null
}
const CACHE_TAG = 'test-fetch-cache-revalidation'
async function getRandomNumber() {
const res = await fetchRandomWithForceCache({ tag: CACHE_TAG })
const dateHeader = res.headers.get('date')
const timestamp = dateHeader ? new Date(dateHeader).getTime() : 'time_unknown'
const text = await res.text()
return `fetch-random-${timestamp}-${text}`
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
export function getPhase() {
return process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
? 'buildtime'
: 'runtime'
}
...@@ -2,11 +2,13 @@ import { Suspense } from 'react' ...@@ -2,11 +2,13 @@ import { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
import { cacheTag } from 'next/cache' import { cacheTag } from 'next/cache'
import { RevalidateButton } from './revalidate-button' import { RevalidateButton } from './revalidate-button'
import { tasky } from '../../utils'
async function getCachedRandom() { async function getCachedRandom() {
'use cache' 'use cache'
cacheTag('revalidate-action-test') cacheTag('revalidate-action-test')
return Math.random() await tasky()
return `cache-random-${Math.random()}`
} }
async function DynamicContent() { async function DynamicContent() {
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
import { RevalidateButton } from './revalidate-button' import { RevalidateButton } from './revalidate-button'
import { fetchRandomWithForceCache } from '../../utils'
async function DynamicContent() { async function DynamicContent() {
// Make the page dynamic/PPR by accessing connection() // Make the page dynamic/PPR by accessing connection()
...@@ -12,10 +13,9 @@ async function DynamicContent() { ...@@ -12,10 +13,9 @@ async function DynamicContent() {
export default async function Page() { export default async function Page() {
// Use fetch with cache and tags // Use fetch with cache and tags
const cachedValue = await fetch( const cachedValue = await fetchRandomWithForceCache({
'https://next-data-api-endpoint.vercel.app/api/random', tag: 'revalidate-fetch-action-test',
{ cache: 'force-cache', next: { tags: ['revalidate-fetch-action-test'] } } }).then(async (res) => `fetch-random-${await res.text()}`)
).then((res) => res.text())
return ( return (
<div> <div>
......
import { revalidateTag } from 'next/cache' import { revalidateTag } from 'next/cache'
export function POST() { export function POST(req: Request) {
revalidateTag('test', 'minutes') const tag = new URL(req.url).searchParams.get('tag')
if (!tag) {
return new Response('Expected "tag" search param to be set', {
status: 400,
})
}
revalidateTag(tag, 'minutes')
return new Response(null, { status: 200 }) return new Response(null, { status: 200 })
} }
...@@ -8,7 +8,7 @@ async function getCachedRandomNumber() { ...@@ -8,7 +8,7 @@ async function getCachedRandomNumber() {
await new Promise((resolve) => setTimeout(resolve, 100)) await new Promise((resolve) => setTimeout(resolve, 100))
return Math.random() return `cache-random-${Math.random()}`
} }
async function getUncachedRandomNumber() { async function getUncachedRandomNumber() {
......
import React, { Suspense } from 'react'
import { connection } from 'next/server'
import { getPhase } from '../../next-phase'
import { tasky } from '../../../utils'
async function getRandomNumber() {
'use cache'
// no cacheTag - this cache is not meant to be revalidated
await tasky()
return `cache-random-${getPhase()}-${Date.now()}-${Math.random()}`
}
async function DynamicComponent() {
await connection()
return null
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
...@@ -2,11 +2,16 @@ import React, { Suspense } from 'react' ...@@ -2,11 +2,16 @@ import React, { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
import { cacheTag } from 'next/cache' import { cacheTag } from 'next/cache'
import { getPhase } from '../../next-phase'
import { tasky } from '../../../utils'
const CACHE_TAG = 'test-use-cache-revalidation'
async function getRandomNumber() { async function getRandomNumber() {
'use cache' 'use cache'
cacheTag('test') cacheTag(CACHE_TAG)
return Math.random() await tasky()
return `cache-random-${getPhase()}-${Date.now()}-${Math.random()}`
} }
async function DynamicComponent() { async function DynamicComponent() {
...@@ -16,17 +21,12 @@ async function DynamicComponent() { ...@@ -16,17 +21,12 @@ async function DynamicComponent() {
export default async function Page() { export default async function Page() {
const randomNumber = await getRandomNumber() const randomNumber = await getRandomNumber()
const anotherRandomNumber = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache', next: { tags: ['test'] } }
).then((res) => res.text())
return ( return (
<> <main>
<p id="random-number">{randomNumber}</p> <p id="random-number">{randomNumber}</p>
<p id="another-random-number">{anotherRandomNumber}</p>
<Suspense> <Suspense>
<DynamicComponent /> <DynamicComponent />
</Suspense> </Suspense>
</> </main>
) )
} }
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./resume-data-cache.test')
import { nextTestSetup } from 'e2e-utils' import { NextInstance, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { assertNoConsoleErrors, gate, retry } from 'next-test-utils'
import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param' import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
import cheerio from 'cheerio'
// RDC and resume renders do not function in the same way in dev.
// This test suite asserts on production behavior.
// @force-gate !dev
describe('resume-data-cache', () => { describe('resume-data-cache', () => {
const { next, isNextDev } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
if (isNextDev) { describe('should have consistent data between static and dynamic renders', () => {
it('is skipped', () => {}) type TestCase = {
return name: string
} path: string
valuePattern: RegExp
it.each([ }
{ name: 'use cache', id: 'random-number' },
{ name: 'fetch cache', id: 'another-random-number' },
])(
'should have consistent data between static and dynamic renders with $name',
async ({ id }) => {
// First render the page statically, getting the random number from the
// HTML.
let $ = await next.render$('/')
const first = $(`p#${id}`).text()
// Then get the Prefetch RSC and validate that it also contains the same
// random number.
await retry(async () => {
const url = new URL('/', 'http://localhost')
url.searchParams.set(
'_rsc',
await computeCacheBustingSearchParam(
'1',
'/__PAGE__',
undefined,
undefined
)
)
const rsc = await next
.fetch(url.toString(), {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/__PAGE__',
},
})
.then((res) => res.text())
expect(rsc).toContain(first)
})
// Then get the dynamic RSC and validate that it also contains the same const htmlId = 'random-number'
// random number.
await retry(async () => { const testInitial = async ({ name, path, valuePattern }: TestCase) => {
const rsc = await next // First, extract the random number from the prerender.
.fetch('/', { const initialRSC = await fetchStaticPageSegment(next, path).then((res) =>
headers: { res.text()
RSC: '1', )
}, const initialValue = getValueFromText(initialRSC, valuePattern)
}) console.log(`${name} - value from prerender: ${initialValue}`)
.then((res) => res.text())
expect(rsc).toContain(first) // Dynamic HTML should use the same value.
}) const html = await next.render(path)
const valueFromHTML = cheerio.load(html)(`p#${htmlId}`).text()
expect(valueFromHTML).toBe(initialValue)
// The value should be consistent across shell and resume.
expectConsistentCacheValue(html, valuePattern, initialValue)
// Dynamic RSC should use the same value.
const rsc = await fetchRSC(next, path).then((res) => res.text())
expect(rsc).toContain(initialValue)
// We should not have multiple values for the cache in RSC.
expectConsistentCacheValue(rsc, valuePattern, initialValue)
}
// Then revalidate the page. Note: Dynamic RSC requests don't trigger const testRevalidation = async ({
name,
path,
cacheTag,
valuePattern,
}: TestCase & { cacheTag: string }) => {
const initialValue = await getPrerenderedValueFromPageSegment(
next,
path,
valuePattern
)
console.log(`${name} - initial value: ${initialValue}`)
// Then revalidate the cached data. Note: Dynamic RSC requests don't trigger
// actual revalidation - they only mark tags as needing revalidation. // actual revalidation - they only mark tags as needing revalidation.
// The actual revalidation only occurs when accessing a static resource again. // The actual revalidation only occurs when accessing a static resource again.
await next.fetch('/revalidate', { method: 'POST' }) await next.fetch(`/revalidate?tag=${cacheTag}`, { method: 'POST' })
// Then get the dynamic RSC again and validate that it still contains the // Then get the dynamic RSC again and validate that it still contains the
// same random number. The first request will get the stale data, but the // same random number. The first request will get the stale data, but the
// second request will get the fresh data as it'll eventually have // second request will get the fresh data as it'll eventually have
// revalidated. // revalidated.
const rsc = await next const rsc = await fetchRSC(next, path).then((res) => res.text())
.fetch('/', { // TODO: this seems to be race-y in deploy
headers: { if (!(await gate('deploy'))) {
RSC: '1', expect(rsc).toContain(initialValue)
}, }
// In deploy mode, revalidation seems to take a while to propagate
const POST_REVALIDATION_RETRY = 10_000
// When the revalidation prerender completes, segment prefetches should start
// containing a new value.
const revalidatedValue = await retry(
async () => {
const rsc = await fetchStaticPageSegment(next, path).then((res) =>
res.text()
)
expect(rsc).not.toContain(initialValue)
return getValueFromText(rsc, valuePattern)
},
POST_REVALIDATION_RETRY,
undefined,
`${name} - segment prefetch should change`
)
console.log(`${name} - revalidated value: ${revalidatedValue}`)
// Dynamic HTML should use the revalidated value.
await retry(
async () => {
const html = await next.render(path)
const valueFromHTML = cheerio.load(html)(`p#${htmlId}`).text()
expect(valueFromHTML).toBe(revalidatedValue)
// The value should be consistent across shell and resume.
expectConsistentCacheValue(html, valuePattern, revalidatedValue)
},
POST_REVALIDATION_RETRY,
undefined,
`${name} - dynamic HTML should contain the revalidated cache value`
)
// Dynamic RSC requests should also use the revalidated value.
await retry(
async () => {
const rsc = await fetchRSC(next, path).then((res) => res.text())
expect(rsc).toContain(revalidatedValue)
// We should not have multiple values for the cache in RSC.
expectConsistentCacheValue(rsc, valuePattern, revalidatedValue)
},
POST_REVALIDATION_RETRY,
undefined,
`${name} - dynamic RSC should contain the revalidated cache value`
)
}
describe('use cache', () => {
const valuePattern = /cache-random-.+?-\d+-\d+\.\d+/
// @gate !partialPrefetchingGlobal
it('initial', async () => {
await testInitial({
name: 'use cache - initial',
path: '/use-cache/initial',
valuePattern,
}) })
.then((res) => res.text())
expect(rsc).toContain(first)
// We then expect after the background revalidation has been completed,
// the dynamic RSC to get the fresh data.
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
},
})
.then((res) => res.text())
expect(rsc).not.toContain(first)
}) })
// This proves that the dynamic RSC was able to use the resume data cache // TODO: propagation of RDC after revalidation seems very flaky in deploy mode,
// (RDC) from the static render to ensure that the data is consistent // so we're skipping this test in deploy until we figure out why
// between the static and dynamic renders. Let's now try to render the // @force-gate !deploy
// page statically and see that the random number changes. // @gate !partialPrefetchingGlobal
it('after revalidation', async () => {
$ = await next.render$('/') await testRevalidation({
const random2 = $(`p#${id}`).text() name: 'use cache - revalidation',
expect(random2).not.toBe(first) path: '/use-cache/revalidation',
cacheTag: 'test-use-cache-revalidation',
// Then get the Prefetch RSC and validate that it also contains the new valuePattern,
// random number. })
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/__PAGE__',
},
})
.then((res) => res.text())
expect(rsc).toContain(random2)
}) })
})
describe('fetch cache', () => {
const valuePattern = /fetch-random-\d+-\d+\.\d+/
// Then get the dynamic RSC again and validate that it also contains the // @gate !(partialPrefetchingGlobal && deploy)
// new random number. it('initial', async () => {
await retry(async () => { await testInitial({
const rsc = await next name: 'fetch cache - initial',
.fetch('/', { path: '/fetch-cache/initial',
headers: { valuePattern,
RSC: '1', })
},
})
.then((res) => res.text())
expect(rsc).toContain(random2)
}) })
// This proves that the dynamic RSC was able to use the resume data cache // TODO: propagation of RDC after revalidation seems very flaky in deploy mode,
// (RDC) from the static render to ensure that the data is consistent // so we're skipping this test in deploy until we figure out why
// between the static and dynamic renders. // @force-gate !deploy
} // @force-gate !partialPrefetchingGlobal
) it('after revalidation', async () => {
await testRevalidation({
name: 'fetch cache - revalidation',
path: '/fetch-cache/revalidation',
cacheTag: 'test-fetch-cache-revalidation',
valuePattern,
})
})
})
})
// @gate !partialPrefetchingGlobal
it('should use RDC for server action re-renders', async () => { it('should use RDC for server action re-renders', async () => {
const browser = await next.browser('/server-action') const url = '/server-action'
const valuePattern = /cache-random-\d+\.\d+/
const prerenderedCachedValue = await getPrerenderedValueFromPageSegment(
next,
url,
valuePattern
)
// The values of the cache entry should be consistent across shell/resume.
expectConsistentCacheValue(
await next.render(url),
valuePattern,
prerenderedCachedValue
)
const browser = await next.browser(url, {
pushErrorAsConsoleLog: true,
})
// Get the initial values // Get the initial values
const initialCachedValue = await browser const initialCachedValue = await browser
...@@ -148,6 +200,12 @@ describe('resume-data-cache', () => { ...@@ -148,6 +200,12 @@ describe('resume-data-cache', () => {
.elementByCss('#uncached-random') .elementByCss('#uncached-random')
.text() .text()
expect(initialCachedValue).toBe(prerenderedCachedValue)
// There should be no hydration errors due to a buildtime cache being
// replaced by a new runtime cache
await assertNoConsoleErrors(browser)
await browser.elementByCss('#refresh-button').click() await browser.elementByCss('#refresh-button').click()
// Wait for the action to complete and verify: // Wait for the action to complete and verify:
...@@ -170,12 +228,30 @@ describe('resume-data-cache', () => { ...@@ -170,12 +228,30 @@ describe('resume-data-cache', () => {
}) })
}) })
// @gate !partialPrefetchingGlobal
it('should see fresh data after updateTag in server action with use cache', async () => { it('should see fresh data after updateTag in server action with use cache', async () => {
// This test verifies that when a server action calls updateTag(), // This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data. // the subsequent re-render sees fresh data instead of stale RDC data.
// This is the "read your own writes" behavior for 'use cache'. // This is the "read your own writes" behavior for 'use cache'.
const url = '/revalidate-action'
const browser = await next.browser('/revalidate-action') const valuePattern = /cache-random-\d+\.\d+/
const prerenderedCachedValue = await getPrerenderedValueFromPageSegment(
next,
url,
valuePattern
)
// The values of the cache entry should be consistent across shell/resume.
expectConsistentCacheValue(
await next.render(url),
valuePattern,
prerenderedCachedValue
)
const browser = await next.browser(url, {
pushErrorAsConsoleLog: true,
})
// Get the initial cached value from the page render // Get the initial cached value from the page render
const initialCachedValue = await browser const initialCachedValue = await browser
...@@ -185,6 +261,12 @@ describe('resume-data-cache', () => { ...@@ -185,6 +261,12 @@ describe('resume-data-cache', () => {
.elementByCss('#uncached-value') .elementByCss('#uncached-value')
.text() .text()
expect(initialCachedValue).toBe(prerenderedCachedValue)
// There should be no hydration errors due to a buildtime cache being
// replaced by a new runtime cache
await assertNoConsoleErrors(browser)
// Click the revalidate button to trigger the server action // Click the revalidate button to trigger the server action
await browser.elementByCss('#revalidate-button').click() await browser.elementByCss('#revalidate-button').click()
...@@ -211,12 +293,29 @@ describe('resume-data-cache', () => { ...@@ -211,12 +293,29 @@ describe('resume-data-cache', () => {
}) })
}) })
// @gate !(partialPrefetchingGlobal && deploy)
it('should see fresh data after updateTag in server action with fetch cache', async () => { it('should see fresh data after updateTag in server action with fetch cache', async () => {
// This test verifies that when a server action calls updateTag(), // This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data. // the subsequent re-render sees fresh data instead of stale RDC data.
// This is the "read your own writes" behavior for fetch cache. // This is the "read your own writes" behavior for fetch cache.
const url = '/revalidate-fetch-action'
const browser = await next.browser('/revalidate-fetch-action') const valuePattern = /fetch-random-\d+\.\d+/
const prerenderedCachedValue = await getPrerenderedValueFromPageSegment(
next,
url,
valuePattern
)
// The values of the cache entry should be consistent across shell/resume.
expectConsistentCacheValue(
await next.render(url),
valuePattern,
prerenderedCachedValue
)
const browser = await next.browser(url, {
pushErrorAsConsoleLog: true,
})
// Get the initial cached value from the page render // Get the initial cached value from the page render
const initialCachedValue = await browser const initialCachedValue = await browser
...@@ -226,6 +325,12 @@ describe('resume-data-cache', () => { ...@@ -226,6 +325,12 @@ describe('resume-data-cache', () => {
.elementByCss('#uncached-value') .elementByCss('#uncached-value')
.text() .text()
expect(initialCachedValue).toBe(prerenderedCachedValue)
// There should be no hydration errors due to a buildtime cache being
// replaced by a new runtime cache
await assertNoConsoleErrors(browser)
// Click the revalidate button to trigger the server action // Click the revalidate button to trigger the server action
await browser.elementByCss('#revalidate-button').click() await browser.elementByCss('#revalidate-button').click()
...@@ -252,3 +357,102 @@ describe('resume-data-cache', () => { ...@@ -252,3 +357,102 @@ describe('resume-data-cache', () => {
}) })
}) })
}) })
function expectConsistentCacheValue(
text: string,
valuePattern: RegExp,
expectedValue: string
) {
expect(getUniqueRegexMatches(text, valuePattern)).toEqual([expectedValue])
}
function getUniqueRegexMatches(text: string, pattern: RegExp) {
const uniqueMatches = new Set<string>()
for (const match of text.matchAll(
new RegExp(pattern.source, pattern.flags + 'g')
)) {
// `matchAll` returns a match array for each occurence.
// We don't care about groups, so just take the whole match.
uniqueMatches.add(match[0])
}
return [...uniqueMatches]
}
async function getPrerenderedValueFromPageSegment(
next: NextInstance,
url: string,
valuePattern: RegExp
) {
const prerendered = await fetchStaticPageSegment(next, url).then((res) =>
res.text()
)
return getValueFromText(prerendered, valuePattern)
}
function getValueFromText(text: string, valuePattern: RegExp) {
const values = getUniqueRegexMatches(text, valuePattern)
if (values.length === 0) {
throw new Error(
`Value pattern not found in prerender: ${valuePattern.source}\n\nText:\n\n{text}`
)
}
if (values.length > 1) {
throw new Error(
`Found multiple values matching pattern: ${valuePattern.source}\n\nText:\n${text}`
)
}
return values[0]
}
async function fetchRSC(next: NextInstance, url: string) {
return await fetchWithRSCCacheBuster(next, url, {
headers: {
RSC: '1',
},
})
}
async function fetchStaticPageSegment(next: NextInstance, url: string) {
const pathname = new URL(url, 'http://__n').pathname
return await fetchWithRSCCacheBuster(next, url, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': pathname + '/__PAGE__',
},
})
}
async function fetchWithRSCCacheBuster(
next: NextInstance,
rawUrl: string,
opts: RequestInit
): Promise<Response> {
// convert to Headers to normalize header casing
const headers = new Headers(opts.headers ?? {})
const urlObject = new URL(rawUrl, next.url)
urlObject.searchParams.set(
'_rsc',
await computeCacheBustingSearchParam(
(headers.get('next-router-prefetch') ?? undefined) as Parameters<
typeof computeCacheBustingSearchParam
>[0],
headers.get('next-router-segment-prefetch') ?? undefined,
headers.get('next-router-state-tree') ?? undefined,
headers.get('next-url') ?? undefined
)
)
const url = urlObject.href
const response = await next.fetch(url, {
...opts,
headers,
})
if (response.url !== url) {
console.error('URL mismatch with response (likely redirect)', {
url,
'response.url': response.url,
})
}
return response
}
export async function tasky() {
// make cache-misses noticeable
await new Promise((resolve) => setTimeout(resolve))
}
/**
* A wrapper meant to ensure fetches with independent tags are cached separately
* so that tests don't interfere with each others' fetch caches.
* */
export async function fetchRandomWithForceCache(
opts: { tag: string } | { key: string; tag: undefined }
) {
let key: string
let tag: string | undefined
if ('key' in opts) {
key = opts.key
tag = undefined
} else {
key = tag = opts.tag
}
return fetch(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent(key)}`,
{ cache: 'force-cache', next: { tags: tag !== undefined ? [tag] : [] } }
)
}
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function getCachedRandom() { async function getCachedNow() {
'use cache' 'use cache'
// Long-lived (stale >= MIN_PREFETCHABLE_STALE, expire >= // Long-lived (stale >= MIN_PREFETCHABLE_STALE, expire >=
// MIN_PRERENDERABLE_EXPIRE): stays in the static shell. // MIN_PRERENDERABLE_EXPIRE): stays in the static shell.
cacheLife({ stale: 60, revalidate: 100, expire: 1000 }) cacheLife({ stale: 60, revalidate: 100, expire: 1000 })
return Math.random()
await tasky()
return `prerenderable: ${Date.now()}`
} }
async function ShortStaleCache() { async function NonPrefetchableCache() {
'use cache' 'use cache'
// Long expire (>= MIN_PRERENDERABLE_EXPIRE, 5min) and a non-zero revalidate, // Long expire (>= MIN_PRERENDERABLE_EXPIRE, 5min) and a non-zero revalidate,
// but a stale time below MIN_PREFETCHABLE_STALE (30s). This isolates the // but a stale time below MIN_PREFETCHABLE_STALE (30s). This isolates the
...@@ -17,18 +20,17 @@ async function ShortStaleCache() { ...@@ -17,18 +20,17 @@ async function ShortStaleCache() {
// because of its short stale time, not because of a short expire or // because of its short stale time, not because of a short expire or
// revalidate: 0. // revalidate: 0.
cacheLife({ stale: 18, revalidate: 100, expire: 1000 }) cacheLife({ stale: 18, revalidate: 100, expire: 1000 })
return <p id="y">{new Date().toISOString()}</p> return <p id="non-prefetchable">{`non-prefetchable: ${Date.now()}`}</p>
} }
export default async function Page() { export default async function Page() {
const x = await getCachedRandom() const cachedNow = await getCachedNow()
return ( return (
<> <main>
<p id="x">{x}</p> <p id="prerenderable">{cachedNow}</p>
<Suspense fallback={<p id="y">Loading...</p>}> <Suspense fallback={<p id="non-prefetchable">Loading...</p>}>
<ShortStaleCache /> <NonPrefetchableCache />
</Suspense> </Suspense>
</> </main>
) )
} }
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function getCachedRandom() { async function getCachedNow() {
'use cache' 'use cache'
// prerenderable and prefetchable.
cacheLife('frequent') cacheLife('frequent')
return Math.random()
await tasky()
return `prerenderable: ${Date.now()}`
} }
async function DynamicCache() { async function NonPrerenderableCache() {
'use cache' 'use cache'
cacheLife({ revalidate: 99, expire: 299, stale: 18 }) // Not prerenderable and not prefetchable.
return <p id="y">{new Date().toISOString()}</p> cacheLife({
revalidate: 99,
expire: 299, // < MIN_PRERENDERABLE_EXPIRE
stale: 18, // < MIN_PREFETCHABLE_STALE
})
return <p id="non-prerenderable">{`non-prerenderable: ${Date.now()}`}</p>
} }
async function Dynamic() { async function Dynamic() {
...@@ -20,17 +29,16 @@ async function Dynamic() { ...@@ -20,17 +29,16 @@ async function Dynamic() {
} }
export default async function Page() { export default async function Page() {
const x = await getCachedRandom() const cachedNow = await getCachedNow()
return ( return (
<> <main>
<p id="x">{x}</p> <p id="prerenderable">{cachedNow}</p>
<Suspense fallback={<p id="y">Loading...</p>}> <Suspense fallback={<p id="non-prerenderable">Loading...</p>}>
<DynamicCache /> <NonPrerenderableCache />
</Suspense> </Suspense>
<Suspense> <Suspense>
<Dynamic /> <Dynamic />
</Suspense> </Suspense>
</> </main>
) )
} }
import { connection } from 'next/server' import { connection } from 'next/server'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function revalidateZero() { async function revalidateZero() {
'use cache: remote' 'use cache: remote'
cacheLife({ revalidate: 0 }) cacheLife({ revalidate: 0 })
return new Date().toISOString() await tasky()
return Date.now()
} }
async function lowExpire() { async function lowExpire() {
'use cache: remote' 'use cache: remote'
cacheLife({ expire: 5 }) cacheLife({ expire: 5 })
return new Date().toISOString() await tasky()
return Date.now()
} }
async function OuterCacheNoExplicit() { async function OuterCacheNoExplicit() {
'use cache: remote' 'use cache: remote'
// No explicit cacheLife - this would error during prerendering, but is // No explicit cacheLife - this would error during prerendering, but is
// allowed at request time (after connection()). // allowed at request time (after connection()).
await tasky()
return ( return (
<> <>
<p> <p>
<code>revalidate=0</code>:{' '} <code>revalidate=0</code>:{' '}
<span id="revalidate-zero">{await revalidateZero()}</span> <span id="revalidate-zero">{`bare-revalidate-zero: ${await revalidateZero()}`}</span>
</p> </p>
<p> <p>
<code>expire=5</code>: <span id="low-expire">{await lowExpire()}</span> <code>expire=5</code>:{' '}
<span id="low-expire">{`bare-low-expire: ${await lowExpire()}`}</span>
</p> </p>
</> </>
) )
...@@ -38,16 +42,16 @@ async function OuterCacheExplicitShort() { ...@@ -38,16 +42,16 @@ async function OuterCacheExplicitShort() {
'use cache: remote' 'use cache: remote'
// Explicit short cacheLife - excluded from prerender, becomes a dynamic hole. // Explicit short cacheLife - excluded from prerender, becomes a dynamic hole.
cacheLife({ revalidate: 0, expire: 5 }) cacheLife({ revalidate: 0, expire: 5 })
await tasky()
return ( return (
<> <>
<p> <p>
Explicit <code>revalidate=0</code>:{' '} Explicit <code>revalidate=0</code>:{' '}
<span id="explicit-revalidate-zero">{await revalidateZero()}</span> <span id="explicit-revalidate-zero">{`explicit-revalidate-zero: ${await revalidateZero()}`}</span>
</p> </p>
<p> <p>
Explicit <code>expire=5</code>:{' '} Explicit <code>expire=5</code>:{' '}
<span id="explicit-low-expire">{await lowExpire()}</span> <span id="explicit-low-expire">{`explicit-low-expire: ${await lowExpire()}`}</span>
</p> </p>
</> </>
) )
...@@ -58,16 +62,16 @@ async function OuterCacheExplicitLong() { ...@@ -58,16 +62,16 @@ async function OuterCacheExplicitLong() {
// Explicit long cacheLife - included in prerender despite short-lived inner // Explicit long cacheLife - included in prerender despite short-lived inner
// caches. // caches.
cacheLife('default') cacheLife('default')
await tasky()
return ( return (
<> <>
<p> <p>
Explicit long (<code>revalidate=0</code> inner):{' '} Explicit long (<code>revalidate=0</code> inner):{' '}
<span id="explicit-long-revalidate-zero">{await revalidateZero()}</span> <span id="explicit-long-revalidate-zero">{`explicit-long-revalidate-zero: ${await revalidateZero()}`}</span>
</p> </p>
<p> <p>
Explicit long (<code>expire=5</code> inner):{' '} Explicit long (<code>expire=5</code> inner):{' '}
<span id="explicit-long-low-expire">{await lowExpire()}</span> <span id="explicit-long-low-expire">{`explicit-long-low-expire: ${await lowExpire()}`}</span>
</p> </p>
</> </>
) )
...@@ -81,7 +85,7 @@ async function Dynamic() { ...@@ -81,7 +85,7 @@ async function Dynamic() {
export default async function Page() { export default async function Page() {
return ( return (
<> <main>
<p id="static">Static content</p> <p id="static">Static content</p>
<Suspense fallback={<p id="dynamic">Loading...</p>}> <Suspense fallback={<p id="dynamic">Loading...</p>}>
<Dynamic /> <Dynamic />
...@@ -90,6 +94,6 @@ export default async function Page() { ...@@ -90,6 +94,6 @@ export default async function Page() {
<OuterCacheExplicitShort /> <OuterCacheExplicitShort />
</Suspense> </Suspense>
<OuterCacheExplicitLong /> <OuterCacheExplicitLong />
</> </main>
) )
} }
process.env.__NEXT_CACHE_COMPONENTS = 'true'
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./use-cache.test')
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
waitForNoErrorToast, waitForNoErrorToast,
retry, retry,
waitFor, waitFor,
gate,
} from 'next-test-utils' } from 'next-test-utils'
import type { Playwright } from 'e2e-utils' import type { Playwright } from 'e2e-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
...@@ -565,8 +566,8 @@ describe('use-cache', () => { ...@@ -565,8 +566,8 @@ describe('use-cache', () => {
'/cache-fetch-no-store', '/cache-fetch-no-store',
'/cache-life', '/cache-life',
// Without cache components this page is fully static. With cache // Without cache components this page is fully static. With cache
// components its short-stale cache becomes a dynamic hole. // components its non-prefetchable cache becomes a dynamic hole.
!withCacheComponents && '/cache-life-short-stale', !withCacheComponents && '/cache-life-non-prefetchable',
'/cache-tag', '/cache-tag',
'/directive-in-node-modules/with-handler', '/directive-in-node-modules/with-handler',
'/directive-in-node-modules/without-handler', '/directive-in-node-modules/without-handler',
...@@ -609,11 +610,11 @@ describe('use-cache', () => { ...@@ -609,11 +610,11 @@ describe('use-cache', () => {
if (withCacheComponents) { if (withCacheComponents) {
expect( expect(
routes['/cache-life-with-dynamic'].initialRevalidateSeconds routes['/cache-life-non-prerenderable'].initialRevalidateSeconds
).toBe(100) ).toBe(100)
expect(routes['/cache-life-with-dynamic'].initialExpireSeconds).toBe( expect(
300 routes['/cache-life-non-prerenderable'].initialExpireSeconds
) ).toBe(300)
} }
// default expireTime // default expireTime
...@@ -632,7 +633,9 @@ describe('use-cache', () => { ...@@ -632,7 +633,9 @@ describe('use-cache', () => {
if (withCacheComponents) { if (withCacheComponents) {
const cacheLifeWithDynamicMeta = JSON.parse( const cacheLifeWithDynamicMeta = JSON.parse(
await next.readFile('.next/server/app/cache-life-with-dynamic.meta') await next.readFile(
'.next/server/app/cache-life-non-prerenderable.meta'
)
) )
expect(cacheLifeWithDynamicMeta.headers['x-nextjs-stale-time']).toBe( expect(cacheLifeWithDynamicMeta.headers['x-nextjs-stale-time']).toBe(
'30' '30'
...@@ -658,44 +661,115 @@ describe('use-cache', () => { ...@@ -658,44 +661,115 @@ describe('use-cache', () => {
}) })
if (withCacheComponents) { if (withCacheComponents) {
it('should omit dynamic caches from prerendered shells', async () => { // @gate !partialPrefetchingGlobal
const browser = await next.browser('/cache-life-with-dynamic', { it('should omit non-prerenderable caches from prerendered shells', async () => {
const cacheValues = {
prerenderable: /(?<!non-)prerenderable: \d+/,
'non-prerenderable': /non-prerenderable: \d+/,
}
const browser = await next.browser('/cache-life-non-prerenderable', {
disableJavaScript: true, disableJavaScript: true,
}) })
expect(await browser.elementById('y').text()).toBe('Loading...') const html = await browser.eval(
() => document.documentElement.outerHTML
)
// Both caches should have a consistent value across the HTML document
// (note: this includes the HTML shell, streamed resume HTML, and the RSC payload)
expect(
getUniqueRegexMatches(html, cacheValues.prerenderable)
).toHaveLength(1)
expect(
getUniqueRegexMatches(html, cacheValues['non-prerenderable'])
).toHaveLength(1)
expect(await browser.elementById('prerenderable').text()).toMatch(
cacheValues.prerenderable
)
// The un-hydrated HTML should be showing a fallback for the non-prerenderable cache.
expect(await browser.elementById('non-prerenderable').text()).toBe(
'Loading...'
)
}) })
it('should omit caches with a short stale time from prerendered shells', async () => { // @gate !partialPrefetchingGlobal
it('should omit non-prefetchable caches from prerendered shells', async () => {
const cacheValues = {
prerenderable: /prerenderable: \d+/,
'non-prefetchable': /non-prefetchable: \d+/,
}
// Disable JS as a hack to see what's included in the static shell // Disable JS as a hack to see what's included in the static shell
let browser = await next.browser('/cache-life-short-stale', { {
disableJavaScript: true, const browser = await next.browser('/cache-life-non-prefetchable', {
}) disableJavaScript: true,
})
expect(await browser.elementById('x').text()).toBeTruthy() const html = await browser.eval(
// We expect the cache to be excluded, so it's showing a suspense fallback () => document.documentElement.outerHTML
expect(await browser.elementById('y').text()).toBe('Loading...') )
// If we let JS run, we should see the cache's actual value // Both caches should have a consistent value across the HTML document
browser = await next.browser('/cache-life-short-stale', { // (note: this includes the HTML shell, streamed resume HTML, and the RSC payload)
pushErrorAsConsoleLog: true, expect(
}) getUniqueRegexMatches(html, cacheValues.prerenderable)
).toHaveLength(1)
expect(
getUniqueRegexMatches(html, cacheValues['non-prefetchable'])
).toHaveLength(1)
expect(await browser.elementById('prerenderable').text()).toMatch(
cacheValues.prerenderable
)
// We expect the non-prefetchable cache to be excluded from the HTML shell,
// so should showing a suspense fallback
expect(await browser.elementById('non-prefetchable').text()).toBe(
'Loading...'
)
await retry(async () => { await browser.close()
expect(await browser.elementById('y').text()).toBeDateString() }
})
// If we let JS run, we should see the cache's actual value
// (NOTE: can't enable JS without recreating `browser()`)
{
const browser = await next.browser('/cache-life-non-prefetchable', {
pushErrorAsConsoleLog: true,
})
expect(await browser.elementById('prerenderable').text()).toMatch(
cacheValues.prerenderable
)
await retry(async () => {
expect(
await browser.elementById('non-prefetchable').text()
).toMatch(cacheValues['non-prefetchable'])
})
await assertNoConsoleErrors(browser) await assertNoConsoleErrors(browser)
}
}) })
} }
it('should not have hydration errors when resuming a partial shell with dynamic caches', async () => { // @gate !partialPrefetchingGlobal
const browser = await next.browser('/cache-life-with-dynamic', { it('should not have hydration errors when resuming a partial shell with non-prerenderable caches', async () => {
const cacheValues = {
prerenderable: /(?<!non-)prerenderable: \d+/,
'non-prerenderable': /non-prerenderable: \d+/,
}
const browser = await next.browser('/cache-life-non-prerenderable', {
pushErrorAsConsoleLog: true, pushErrorAsConsoleLog: true,
}) })
expect(await browser.elementById('prerenderable').text()).toMatch(
cacheValues.prerenderable
)
await retry(async () => { await retry(async () => {
expect(await browser.elementById('y').text()).not.toBe('Loading...') expect(await browser.elementById('non-prerenderable').text()).toMatch(
cacheValues['non-prerenderable']
)
}) })
// There should be no hydration errors due to a buildtime date being // There should be no hydration errors due to a buildtime date being
...@@ -1267,9 +1341,10 @@ describe('use-cache', () => { ...@@ -1267,9 +1341,10 @@ describe('use-cache', () => {
}) })
if (withCacheComponents) { if (withCacheComponents) {
// @gate !partialPrefetchingGlobal || dev
it('can resume a cached generateMetadata function', async () => { it('can resume a cached generateMetadata function', async () => {
// In dev the initial request fills the caches while streaming the // In dev the initial request fills the caches while streaming the
// response. The second request will have filled caches and server a // response. The second request will have filled caches and serves a
// prod-like shell. // prod-like shell.
if (isNextDev) { if (isNextDev) {
await next.fetch('/generate-metadata-resume/nested') await next.fetch('/generate-metadata-resume/nested')
...@@ -1438,6 +1513,7 @@ describe('use-cache', () => { ...@@ -1438,6 +1513,7 @@ describe('use-cache', () => {
).toBe(description) ).toBe(description)
}) })
// @gate !partialPrefetchingGlobal || dev
it('can resume a cached generateViewport function', async () => { it('can resume a cached generateViewport function', async () => {
// First load the page with JavaScript disabled, to ensure that the // First load the page with JavaScript disabled, to ensure that the
// generateViewport result was included in the prerendered shell. // generateViewport result was included in the prerendered shell.
...@@ -1579,47 +1655,101 @@ describe('use-cache', () => { ...@@ -1579,47 +1655,101 @@ describe('use-cache', () => {
}) })
} }
// @gate !partialPrefetchingGlobal || dev
it('should allow nested short-lived caches after connection()', async () => { it('should allow nested short-lived caches after connection()', async () => {
const cacheValues = {
'revalidate-zero': /bare-revalidate-zero: \d+/,
'low-expire': /bare-low-expire: \d+/,
'explicit-revalidate-zero': /explicit-revalidate-zero: \d+/,
'explicit-low-expire': /explicit-low-expire: \d+/,
'explicit-long-revalidate-zero': /explicit-long-revalidate-zero: \d+/,
'explicit-long-low-expire': /explicit-long-low-expire: \d+/,
}
// In dev the initial request fills the caches while streaming the
// response. The second request will have filled caches and serves a
// prod-like shell.
if (isNextDev) {
await next.fetch('/short-lived-caches')
}
// Check the prerendered shell (no JS). // Check the prerendered shell (no JS).
let browser = await next.browser('/short-lived-caches', { {
disableJavaScript: true, const browser = await next.browser('/short-lived-caches', {
}) disableJavaScript: true,
})
const html = await browser.eval(() => document.documentElement.outerHTML)
// Static content should be in the shell.
expect(await browser.elementById('static').text()).toBe('Static content')
// Static content should be in the shell. // Explicit long cacheLife should be in the shell despite short-lived inner
expect(await browser.elementById('static').text()).toBe('Static content') // caches.
const expectIncluded = async (id: keyof typeof cacheValues) => {
// Look for elements within <main> to exlude streaming fizz chunks.
// NOTE: content being present in the shell is only reliable in cacheComponents
if (await gate('cacheComponents')) {
expect(await browser.elementByCss(`main #${id}`).text()).toMatch(
cacheValues[id]
)
}
// The cache will be present in HTML shell, streaming HTML, and the RSC payload.
// It should have consistent values across all of those.
expect(getUniqueRegexMatches(html, cacheValues[id])).toHaveLength(1)
}
await expectIncluded('explicit-long-revalidate-zero')
await expectIncluded('explicit-long-low-expire')
// For the other caches, the outer cache was omitted from the prerender, so they
// should not be visible in the HTML shell.
const expectExcluded = async (id: keyof typeof cacheValues) => {
// Look for elements within <main> to exlude streaming fizz chunks.
// NOTE: content being present in the shell is only reliable in cacheComponents
if (await gate('cacheComponents')) {
expect(await browser.locator(`main #${id}`).count()).toBe(0)
}
// The cache will be present in streaming HTML and the RSC payload.
// It should have consistent values across both of those.
expect(getUniqueRegexMatches(html, cacheValues[id])).toHaveLength(1)
}
await expectExcluded('revalidate-zero')
await expectExcluded('low-expire')
await expectExcluded('explicit-revalidate-zero')
await expectExcluded('explicit-low-expire')
// Explicit long cacheLife should be in the shell despite short-lived inner await browser.close()
// caches. }
expect(
await browser.elementById('explicit-long-revalidate-zero').text()
).toBeDateString()
expect(
await browser.elementById('explicit-long-low-expire').text()
).toBeDateString()
// Now check with JS enabled to verify dynamic content loads. // Now check with JS enabled to verify dynamic content loads.
browser = await next.browser('/short-lived-caches', { {
pushErrorAsConsoleLog: true, const browser = await next.browser('/short-lived-caches', {
}) pushErrorAsConsoleLog: true,
})
// Dynamic content should eventually render. // Dynamic content should eventually render.
await retry(async () => { await retry(async () => {
// No explicit outer cacheLife (after connection()). // No explicit outer cacheLife (after connection()).
expect( expect(await browser.elementById('revalidate-zero').text()).toMatch(
await browser.elementById('revalidate-zero').text() cacheValues['revalidate-zero']
).toBeDateString() )
expect(await browser.elementById('low-expire').text()).toBeDateString() expect(await browser.elementById('low-expire').text()).toMatch(
cacheValues['low-expire']
)
// Explicit short cacheLife - excluded from prerender. // Explicit short cacheLife - excluded from prerender.
expect( expect(
await browser.elementById('explicit-revalidate-zero').text() await browser.elementById('explicit-revalidate-zero').text()
).toBeDateString() ).toMatch(cacheValues['explicit-revalidate-zero'])
expect( expect(await browser.elementById('explicit-low-expire').text()).toMatch(
await browser.elementById('explicit-low-expire').text() cacheValues['explicit-low-expire']
).toBeDateString() )
}) })
await assertNoConsoleErrors(browser) await assertNoConsoleErrors(browser)
}
}) })
it('should dedupe shared inner caches across different outer caches', async () => { it('should dedupe shared inner caches across different outer caches', async () => {
...@@ -1828,3 +1958,15 @@ function extractResumeDataCacheFromPostponedState( ...@@ -1828,3 +1958,15 @@ function extractResumeDataCacheFromPostponedState(
undefined undefined
) )
} }
function getUniqueRegexMatches(text: string, pattern: RegExp) {
const uniqueMatches = new Set<string>()
for (const match of text.matchAll(
new RegExp(pattern.source, pattern.flags + 'g')
)) {
// `matchAll` returns a match array for each occurence.
// We don't care about groups, so just take the whole match.
uniqueMatches.add(match[0])
}
return [...uniqueMatches]
}
export async function tasky() {
// make cache-misses noticeable
await new Promise((resolve) => setTimeout(resolve))
}
...@@ -176,6 +176,10 @@ export const conditions: Record<string, Condition> = { ...@@ -176,6 +176,10 @@ export const conditions: Record<string, Condition> = {
'Cache Components are enabled for the fixture', 'Cache Components are enabled for the fixture',
(config) => config.cacheComponents (config) => config.cacheComponents
), ),
partialPrefetchingGlobal: lazyCondition(
'Partial Prefetching is enabled globally for the fixture (does not check `export const prefetch = "partial"`)',
(config) => config.partialPrefetching
),
ppr: lazyCondition( ppr: lazyCondition(
'partial prerendering is enabled (implied by `cacheComponents`)', 'partial prerendering is enabled (implied by `cacheComponents`)',
(config) => config.experimental?.ppr (config) => config.experimental?.ppr
......
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