Unverified Commit 678f1052 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Cache Components] Don't propagate tags/life for omitted caches (#82884)

Caches with staleness/expiration below certain thresholds are not
included in static prerenders and are treated as dynamic. However, the
logic for propagating life/tags did not factor this in, meaning that a
prerender could get `cacheLife("seconds")`, making it expire (both on
the server and in the client router cache) much earlier than necessary.
This PR fixes that.

Closes NAR-271

### Implementation notes

The solution relies on the fact that in a Cache Components prerender,
we'll first fill the caches in the prospective render, and then read
them again in the final prerender. Previously, we'd propagate cache
life/tags in the prospective render, when the cache was filled, but this
didn't factor in the fact that the final render might decide to omit the
cache, leading to the problem described earlier. After this change,
we'll be relying on the fact that the entry will be read in the final
prerender, at which point we decide if it should be included or not, and
then propagate cache life/tags if it is.

Additionally, we filter the omitted cache entries from the resume data
cache (RDC). Otherwise they would be available during the resume, which
they should not be.

To be honest, this feels a bit brittle, and perhaps we should take a
look at how we're handling this and make it cleaner, but it should work
for now.

---------
Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
parent 5146e4c5
......@@ -244,7 +244,10 @@ export async function exportAppPage(
cacheControl,
fetchMetrics,
renderResumeDataCache: renderResumeDataCache
? await stringifyResumeDataCache(renderResumeDataCache)
? await stringifyResumeDataCache(
renderResumeDataCache,
renderOpts.experimental.cacheComponents
)
: undefined,
}
} catch (err) {
......
......@@ -3932,12 +3932,15 @@ async function prerenderToStream(
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams,
resumeDataCache
resumeDataCache,
experimental.cacheComponents
)
} else {
// Dynamic Data case
metadata.postponed =
await getDynamicDataPostponedState(resumeDataCache)
metadata.postponed = await getDynamicDataPostponedState(
resumeDataCache,
experimental.cacheComponents
)
}
reactServerResult.consume()
return {
......@@ -4155,12 +4158,14 @@ async function prerenderToStream(
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams,
prerenderResumeDataCache
prerenderResumeDataCache,
experimental.cacheComponents
)
} else {
// Dynamic Data case.
metadata.postponed = await getDynamicDataPostponedState(
prerenderResumeDataCache
prerenderResumeDataCache,
experimental.cacheComponents
)
}
// Regardless of whether this is the Dynamic HTML or Dynamic Data case we need to ensure we include
......@@ -4185,7 +4190,8 @@ async function prerenderToStream(
} else if (fallbackRouteParams && fallbackRouteParams.size > 0) {
// Rendering the fallback case.
metadata.postponed = await getDynamicDataPostponedState(
prerenderResumeDataCache
prerenderResumeDataCache,
experimental.cacheComponents
)
return {
......
......@@ -21,6 +21,9 @@ export function createMockOpaqueFallbackRouteParams(
return new Map(Object.entries(params))
}
const isCacheComponentsEnabled =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
describe('getDynamicHTMLPostponedState', () => {
it('serializes a HTML postponed state with fallback params', async () => {
const key = '%%drp:slug:e9615126684e5%%'
......@@ -36,8 +39,8 @@ describe('getDynamicHTMLPostponedState', () => {
tags: [],
stale: 0,
timestamp: 0,
expire: 0,
revalidate: 0,
expire: 300,
revalidate: 1,
})
)
......@@ -45,10 +48,12 @@ describe('getDynamicHTMLPostponedState', () => {
{ [key]: key, nested: { [key]: key } },
DynamicHTMLPreludeState.Full,
fallbackRouteParams,
prerenderResumeDataCache
prerenderResumeDataCache,
isCacheComponentsEnabled
)
const parsed = parsePostponedState(state, '/blog/[slug]', { slug: '123' })
expect(parsed).toMatchInlineSnapshot(`
{
"data": [
......@@ -84,7 +89,8 @@ describe('getDynamicHTMLPostponedState', () => {
{ key: 'value' },
DynamicHTMLPreludeState.Full,
null,
createPrerenderResumeDataCache()
createPrerenderResumeDataCache(),
isCacheComponentsEnabled
)
expect(state).toMatchInlineSnapshot(`"19:[1,{"key":"value"}]null"`)
})
......@@ -98,7 +104,8 @@ describe('getDynamicHTMLPostponedState', () => {
{ [key]: key },
DynamicHTMLPreludeState.Full,
fallbackRouteParams,
createPrerenderResumeDataCache()
createPrerenderResumeDataCache(),
isCacheComponentsEnabled
)
const value = 'hello'
......@@ -118,7 +125,8 @@ describe('getDynamicHTMLPostponedState', () => {
describe('getDynamicDataPostponedState', () => {
it('serializes a data postponed state with fallback params', async () => {
const state = await getDynamicDataPostponedState(
createPrerenderResumeDataCache()
createPrerenderResumeDataCache(),
isCacheComponentsEnabled
)
expect(state).toMatchInlineSnapshot(`"4:nullnull"`)
})
......
......@@ -79,7 +79,8 @@ export async function getDynamicHTMLPostponedState(
postponed: ReactPostponed,
preludeState: DynamicHTMLPreludeState,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean
): Promise<string> {
const data: DynamicHTMLPostponedState['data'] = [preludeState, postponed]
const dataString = JSON.stringify(data)
......@@ -89,7 +90,8 @@ export async function getDynamicHTMLPostponedState(
if (!fallbackRouteParams || fallbackRouteParams.size === 0) {
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return `${dataString.length}:${dataString}${await stringifyResumeDataCache(
createRenderResumeDataCache(resumeDataCache)
createRenderResumeDataCache(resumeDataCache),
isCacheComponentsEnabled
)}`
}
......@@ -102,13 +104,14 @@ export async function getDynamicHTMLPostponedState(
const postponedString = `${replacementsString.length}${replacementsString}${dataString}`
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache(resumeDataCache)}`
return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache(resumeDataCache, isCacheComponentsEnabled)}`
}
export async function getDynamicDataPostponedState(
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean
): Promise<string> {
return `4:null${await stringifyResumeDataCache(createRenderResumeDataCache(resumeDataCache))}`
return `4:null${await stringifyResumeDataCache(createRenderResumeDataCache(resumeDataCache), isCacheComponentsEnabled)}`
}
export function parsePostponedState(
......
......@@ -4,6 +4,7 @@ import {
} from '../app-render/encryption-utils'
import type { CacheEntry } from '../lib/cache-handlers/types'
import type { CachedFetchValue } from '../response-cache/types'
import { DYNAMIC_EXPIRE } from '../use-cache/constants'
/**
* A generic cache store type that provides a subset of Map functionality
......@@ -92,12 +93,22 @@ export function parseUseCacheCacheStore(
* @returns A promise that resolves to an array of key-value pairs with serialized values
*/
export async function serializeUseCacheCacheStore(
entries: IterableIterator<[string, Promise<CacheEntry>]>
entries: IterableIterator<[string, Promise<CacheEntry>]>,
isCacheComponentsEnabled: boolean
): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> {
return Promise.all(
Array.from(entries).map(([key, value]) => {
return value
.then(async (entry) => {
if (
isCacheComponentsEnabled &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
) {
// The entry was omitted from the prerender result, and subsequently
// does not need to be included in the serialized RDC.
return null
}
const [left, right] = entry.value.tee()
entry.value = right
......
......@@ -6,8 +6,13 @@ import { createPrerenderResumeDataCache } from './resume-data-cache'
import { streamFromString } from '../stream-utils/node-web-streams-helper'
import { inflateSync } from 'node:zlib'
function createCacheWithSingleEntry() {
const isCacheComponentsEnabled =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
function createMockedCache() {
const cache = createPrerenderResumeDataCache()
// Should be included during serialization.
cache.cache.set(
'success',
Promise.resolve({
......@@ -15,7 +20,33 @@ function createCacheWithSingleEntry() {
tags: [],
stale: 0,
timestamp: 0,
expire: 0,
expire: 300,
revalidate: 1,
})
)
// Should be omitted during serialization.
cache.cache.set(
'dynamic-expire',
Promise.resolve({
value: streamFromString('value'),
tags: [],
stale: 0,
timestamp: 0,
expire: 299,
revalidate: 1,
})
)
// Should be omitted during serialization.
cache.cache.set(
'zero-revalidate',
Promise.resolve({
value: streamFromString('value'),
tags: [],
stale: 0,
timestamp: 0,
expire: 300,
revalidate: 0,
})
)
......@@ -23,8 +54,8 @@ function createCacheWithSingleEntry() {
return cache
}
function createCacheWithSingleEntryThatFails() {
const cache = createCacheWithSingleEntry()
function createMockedCacheWithEntryThatFails() {
const cache = createMockedCache()
cache.cache.set('fail', Promise.reject(new Error('Failed to serialize')))
return cache
......@@ -33,12 +64,18 @@ function createCacheWithSingleEntryThatFails() {
describe('stringifyResumeDataCache', () => {
it('serializes an empty cache', async () => {
const cache = createPrerenderResumeDataCache()
expect(await stringifyResumeDataCache(cache)).toBe('null')
expect(
await stringifyResumeDataCache(cache, isCacheComponentsEnabled)
).toBe('null')
})
it('serializes a cache with a single entry', async () => {
const cache = createCacheWithSingleEntry()
const compressed = await stringifyResumeDataCache(cache)
it('only serializes cache entries that were not excluded from the prerender result', async () => {
const cache = createMockedCache()
const compressed = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
// We have to decompress the output because the compressed string is not
// deterministic. If it fails here it's because the compressed string is
......@@ -47,14 +84,24 @@ describe('stringifyResumeDataCache', () => {
Buffer.from(compressed, 'base64')
).toString('utf-8')
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}},"encryptedBoundArgs":{}}}"`
)
if (isCacheComponentsEnabled) {
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1}},"encryptedBoundArgs":{}}}"`
)
} else {
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"dynamic-expire":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"zero-revalidate":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0}},"encryptedBoundArgs":{}}}"`
)
}
})
it('serializes a cache with a single entry that fails', async () => {
const cache = createCacheWithSingleEntryThatFails()
const compressed = await stringifyResumeDataCache(cache)
it('serializes a cache with an entry that fails', async () => {
const cache = createMockedCacheWithEntryThatFails()
const compressed = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
// We have to decompress the output because the compressed string is not
// deterministic. If it fails here it's because the compressed string is
......@@ -63,11 +110,17 @@ describe('stringifyResumeDataCache', () => {
Buffer.from(compressed, 'base64')
).toString('utf-8')
// We expect that the cache will still contain the successful entry but the
// failed entry will be ignored and omitted from the output.
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}},"encryptedBoundArgs":{}}}"`
)
// We expect that the cache will still contain the successful entries
// but the failed entry will be ignored and omitted from the output.
if (isCacheComponentsEnabled) {
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1}},"encryptedBoundArgs":{}}}"`
)
} else {
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":1},"dynamic-expire":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":299,"revalidate":1},"zero-revalidate":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":300,"revalidate":0}},"encryptedBoundArgs":{}}}"`
)
}
})
})
......@@ -78,13 +131,16 @@ describe('parseResumeDataCache', () => {
)
})
it('parses a cache with a single entry', async () => {
const cache = createCacheWithSingleEntry()
const serialized = await stringifyResumeDataCache(cache)
it('parses a filled cache', async () => {
const cache = createMockedCache()
const serialized = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
const parsed = createRenderResumeDataCache(serialized)
expect(parsed.cache.size).toBe(1)
expect(parsed.cache.size).toBe(isCacheComponentsEnabled ? 1 : 3)
expect(parsed.fetch.size).toBe(0)
})
})
......@@ -100,7 +100,8 @@ type ResumeStoreSerialized = {
* 'null' if empty
*/
export async function stringifyResumeDataCache(
resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache
resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache,
isCacheComponentsEnabled: boolean
): Promise<string> {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
......@@ -116,7 +117,10 @@ export async function stringifyResumeDataCache(
fetch: Object.fromEntries(Array.from(resumeDataCache.fetch.entries())),
cache: Object.fromEntries(
(
await serializeUseCacheCacheStore(resumeDataCache.cache.entries())
await serializeUseCacheCacheStore(
resumeDataCache.cache.entries(),
isCacheComponentsEnabled
)
).filter(
(entry): entry is [string, UseCacheCacheStoreSerialized] =>
entry !== null
......
......@@ -378,7 +378,7 @@ function propagateCacheLifeAndTags(
}
async function collectResult(
savedStream: ReadableStream,
savedStream: ReadableStream<Uint8Array>,
workStore: WorkStore,
cacheContext: CacheContext,
innerCacheStore: UseCacheStore,
......@@ -398,7 +398,7 @@ async function collectResult(
// that the stream might also error for other reasons anyway such as losing
// connection.
const buffer: any[] = []
const buffer: Uint8Array[] = []
const reader = savedStream.getReader()
try {
......@@ -410,7 +410,7 @@ async function collectResult(
}
let idx = 0
const bufferStream = new ReadableStream({
const bufferStream = new ReadableStream<Uint8Array>({
pull(controller) {
if (workStore.invalidDynamicUsageError) {
controller.error(workStore.invalidDynamicUsageError)
......@@ -451,17 +451,40 @@ async function collectResult(
tags: collectedTags === null ? [] : collectedTags,
}
// Propagate tags/revalidate to the parent context.
if (cacheContext) {
propagateCacheLifeAndTags(cacheContext, entry)
}
if (cacheContext.outerWorkUnitStore) {
const outerWorkUnitStore = cacheContext.outerWorkUnitStore
const cacheSignal = cacheContext.outerWorkUnitStore
? getCacheSignal(cacheContext.outerWorkUnitStore)
: null
// Propagate cache life & tags to the parent context if appropriate.
switch (outerWorkUnitStore.type) {
case 'prerender':
case 'prerender-runtime': {
// If we've just created a cache result, and we're filling caches for a
// Cache Components prerender, then we don't want to propagate cache
// life & tags yet, in case the entry ends up being omitted from the
// final prerender due to short expire/stale times. If it is omitted,
// then it shouldn't have any effects on the prerender. We'll decide
// whether or not this cache should have its life & tags propagated when
// we read the entry in the final prerender from the resume data cache.
break
}
case 'request':
case 'private-cache':
case 'cache':
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr': {
propagateCacheLifeAndTags(cacheContext, entry)
break
}
default: {
outerWorkUnitStore satisfies never
}
}
if (cacheSignal) {
cacheSignal.endRead()
const cacheSignal = getCacheSignal(outerWorkUnitStore)
if (cacheSignal) {
cacheSignal.endRead()
}
}
return entry
......@@ -1160,8 +1183,6 @@ export function cache(
const cachedEntry = renderResumeDataCache.cache.get(serializedCacheKey)
if (cachedEntry !== undefined) {
const existingEntry = await cachedEntry
propagateCacheLifeAndTags(cacheContext, existingEntry)
if (workUnitStore !== undefined && existingEntry !== undefined) {
if (
existingEntry.revalidate === 0 ||
......@@ -1170,11 +1191,11 @@ export function cache(
switch (workUnitStore.type) {
case 'prerender':
// In a Dynamic I/O prerender, if the cache entry has
// revalidate: 0 or if the expire time is under 5 minutes, then
// we consider this cache entry dynamic as it's not worth
// generating static pages for such data. It's better to leave a
// PPR hole that can be filled in dynamically with a potentially
// cached entry.
// revalidate: 0 or if the expire time is under 5 minutes,
// then we consider this cache entry dynamic as it's not worth
// generating static pages for such data. It's better to leave
// a dynamic hole that can be filled in during the resume with
// a potentially cached entry.
if (cacheSignal) {
cacheSignal.endRead()
}
......@@ -1184,7 +1205,8 @@ export function cache(
'dynamic "use cache"'
)
case 'prerender-runtime': {
// In a runtime prerender, we have to make sure that APIs that would hang during a static prerender
// In the final phase of a runtime prerender, we have to make
// sure that APIs that would hang during a static prerender
// are resolved with a delay, in the runtime stage.
if (workUnitStore.runtimeStagePromise) {
await workUnitStore.runtimeStagePromise
......@@ -1206,10 +1228,10 @@ export function cache(
if (existingEntry.stale < RUNTIME_PREFETCH_DYNAMIC_STALE) {
switch (workUnitStore.type) {
case 'prerender-runtime':
// In a runtime prerender, if the cache entry will become stale in less then 30 seconds,
// we consider this cache entry dynamic as it's not worth prefetching.
// It's better to leave a PPR hole that can be filled in dynamically
// with a potentially cached entry.
// In a runtime prerender, if the cache entry will become
// stale in less then 30 seconds, we consider this cache entry
// dynamic as it's not worth prefetching. It's better to leave
// a dynamic hole that can be filled during the navigation.
if (cacheSignal) {
cacheSignal.endRead()
}
......@@ -1232,6 +1254,11 @@ export function cache(
}
}
// We want to make sure we only propagate cache life & tags if the
// entry was *not* omitted from the prerender. So we only do this
// after the above early returns.
propagateCacheLifeAndTags(cacheContext, existingEntry)
const [streamA, streamB] = existingEntry.value.tee()
existingEntry.value = streamB
......@@ -1361,8 +1388,9 @@ export function cache(
// In a Dynamic I/O prerender, if the cache entry has revalidate:
// 0 or if the expire time is under 5 minutes, then we consider
// this cache entry dynamic as it's not worth generating static
// pages for such data. It's better to leave a PPR hole that can
// be filled in dynamically with a potentially cached entry.
// pages for such data. It's better to leave a dynamic hole that
// can be filled in during the resume with a potentially cached
// entry.
if (cacheSignal) {
cacheSignal.endRead()
}
......@@ -1372,12 +1400,6 @@ export function cache(
'dynamic "use cache"'
)
case 'prerender-runtime':
// In a runtime prerender, we have to make sure that APIs that would hang during a static prerender
// are resolved with a delay, in the runtime stage.
if (workUnitStore.runtimeStagePromise) {
await workUnitStore.runtimeStagePromise
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -33,6 +33,11 @@ export default function Page() {
<li>
<LinkAccordion href="/dynamic">Page with dynamic data</LinkAccordion>
</li>
<li>
<LinkAccordion href="/seconds">
Page with cached data with <code>cacheLife("seconds")</code>
</LinkAccordion>
</li>
</ul>
</>
)
......
import { Suspense } from 'react'
import { unstable_cacheLife } from 'next/cache'
export default function Page() {
return (
<main>
<p>
Caches that use the 'seconds' profile will be omitted from static
prerenders, making this essentially dynamic. If we omit it, it should
not affect the cache life of the prerender.
</p>
<Suspense fallback="Loading...">
<ShortLivedContent />
</Suspense>
<br />
<p>Longer lived caches should still affect the cache life of the page.</p>
<LongerLivedContent />
</main>
)
}
async function ShortLivedContent() {
'use cache'
unstable_cacheLife('seconds')
return <div>Short-lived cached content</div>
}
async function LongerLivedContent() {
'use cache'
unstable_cacheLife('minutes')
return <div>Longer-lived cached content</div>
}
......@@ -220,4 +220,73 @@ describe('segment cache (staleness)', () => {
'Dynamic content'
)
})
it('caches omitted from the prerender should not affect when the prefetch is expired', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
await page.clock.install()
// Reveal the link to trigger a prefetch
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/seconds"]')
.click()
await browser.elementByCss('a[href="/seconds"]')
},
{
// cacheLife("seconds") should be excluded from a static prerender
includes: 'Short-lived cached content',
block: 'reject',
}
)
// Hide the link
await browser.elementByCss('input[data-link-accordion="/seconds"]').click()
// Fast forward 30 seconds and 1 millisecond
// (matching the staleness of the "seconds" profile)
const timeStep = 30 * 1000 + 1
await page.clock.fastForward(timeStep)
// Reveal the link again to trigger new prefetch tasks.
// The cache with `cacheLife('seconds'`) should not affect the stale time of the prefetch,
// because we omit it from the prerender, so we shouldn't refetch anything yet.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/seconds"]')
.click()
await browser.elementByCss('a[href="/seconds"]')
}, 'no-requests')
// Hide the link again
await browser.elementByCss('input[data-link-accordion="/seconds"]').click()
// Fast forward to 5 minutes and 1 millisecond after the prefetch.
// (matching the staleness of the "minutes" profile)
// Note that we should exclude the timestep we've already done.
await page.clock.fastForward(5 * 60 * 1000 + 1 - timeStep)
// Reveal the link to trigger a prefetch.
// The longer-lived cache we used on the page should make the previous prefetch expire,
// so we should issue a new request.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/seconds"]')
.click()
await browser.elementByCss('a[href="/seconds"]')
},
{
includes: 'Short-lived cached content',
block: 'reject',
}
)
})
})
import { Suspense } from 'react'
import { unstable_cacheLife as cacheLife } from 'next/cache'
// The id prop is just used to assert on the logged cache key in tests.
async function DynamicCache({ id }: { id: string }) {
'use cache'
cacheLife('seconds')
return <p>{new Date().toISOString()}</p>
}
export default function Page() {
return (
<p>
This page uses a short-lived "use cache", which is omitted from the
prerender, but should still be saved in the cache handler.
<Suspense>
<DynamicCache id="dynamic-cache" />
</Suspense>
</p>
)
}
......@@ -4,7 +4,7 @@ import { retry } from 'next-test-utils'
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
describe('use-cache-custom-handler', () => {
const { next, skipped } = nextTestSetup({
const { next, skipped, isNextStart } = nextTestSetup({
files: __dirname,
// Skip deployment so we can test the custom cache handlers log output
skipDeployment: true,
......@@ -184,4 +184,12 @@ describe('use-cache-custom-handler', () => {
)
})
})
if (isNextStart) {
it('should save a short-lived cache during prerendering at buildtime', async () => {
expect(next.cliOutput).toMatch(
/ModernCustomCacheHandler::set \["[A-Za-z0-9_-]{21}","([0-9a-f]{2})+",\[{"id":"dynamic-cache"},"\$undefined"\]\]/
)
})
}
})
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
async function getCachedRandom() {
'use cache'
cacheLife('frequent')
return Math.random()
}
async function DynamicCache() {
'use cache'
cacheLife({ revalidate: 99, expire: 299, stale: 18 })
return <p id="y">{new Date().toISOString()}</p>
}
async function Dynamic() {
await connection()
return null
}
export default async function Page() {
const x = await getCachedRandom()
return (
<>
<p id="x">{x}</p>
<Suspense fallback={<p id="y">Loading...</p>}>
<DynamicCache />
</Suspense>
<Suspense>
<Dynamic />
</Suspense>
</>
)
}
import { unstable_cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
......@@ -16,18 +17,35 @@ async function innermost(id: string) {
return id
}
async function Short({ id }: { id: string }) {
'use cache'
unstable_cacheLife('seconds')
return id
}
async function Dynamic() {
await connection()
return null
}
export default async function Page() {
async function CachedStuff() {
await outermost('outer')
await innermost('inner')
return (
<Suspense>
<Dynamic />
<Short id="short" />
</Suspense>
)
}
export default function Page() {
return (
<div>
<CachedStuff />
<Suspense>
<Dynamic />
</Suspense>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { assertNoConsoleErrors, retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { format } from 'util'
import { Playwright } from 'next-webdriver'
......@@ -12,6 +12,11 @@ import { PrerenderManifest } from 'next/dist/build'
const GENERIC_RSC_ERROR =
'An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.'
const withPPR = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
const withCacheComponents =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
describe('use-cache', () => {
const { next, isNextDev, isNextDeploy, isNextStart, skipped } = nextTestSetup(
{
......@@ -444,11 +449,6 @@ describe('use-cache', () => {
await next.readFile('.next/prerender-manifest.json')
) as PrerenderManifest
const withPPR = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
const withCacheComponents =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
let prerenderedRoutes = Object.entries(prerenderManifest.routes)
if (withPPR || withCacheComponents) {
......@@ -518,6 +518,23 @@ describe('use-cache', () => {
expect(routes['/cache-life'].initialRevalidateSeconds).toBe(100)
expect(routes['/cache-life'].initialExpireSeconds).toBe(300)
if (withCacheComponents) {
expect(
routes['/cache-life-with-dynamic'].initialRevalidateSeconds
).toBe(100)
expect(routes['/cache-life-with-dynamic'].initialExpireSeconds).toBe(
300
)
} else if (withPPR) {
// We don't exclude dynamic caches for the legacy PPR prerendering.
expect(
routes['/cache-life-with-dynamic'].initialRevalidateSeconds
).toBe(99)
expect(routes['/cache-life-with-dynamic'].initialExpireSeconds).toBe(
299
)
}
// default expireTime
expect(routes['/cache-fetch'].initialExpireSeconds).toBe(31536000)
......@@ -525,7 +542,7 @@ describe('use-cache', () => {
// config for the page.
expect(routes['/cache-tag'].initialRevalidateSeconds).toBe(42)
if (process.env.__NEXT_EXPERIMENTAL_PPR === 'true') {
if (withPPR) {
// cache life profile "weeks"
expect(dynamicRoutes['/[id]'].fallbackRevalidate).toBe(604800)
expect(dynamicRoutes['/[id]'].fallbackExpire).toBe(2592000)
......@@ -533,10 +550,27 @@ describe('use-cache', () => {
})
it('should match the expected stale config in the page header', async () => {
const meta = JSON.parse(
const cacheLifeMeta = JSON.parse(
await next.readFile('.next/server/app/cache-life.meta')
)
expect(meta.headers['x-nextjs-stale-time']).toBe('19')
expect(cacheLifeMeta.headers['x-nextjs-stale-time']).toBe('19')
if (withCacheComponents) {
const cacheLifeWithDynamicMeta = JSON.parse(
await next.readFile('.next/server/app/cache-life-with-dynamic.meta')
)
expect(cacheLifeWithDynamicMeta.headers['x-nextjs-stale-time']).toBe(
'19'
)
} else if (withPPR) {
const cacheLifeWithDynamicMeta = JSON.parse(
await next.readFile('.next/server/app/cache-life-with-dynamic.meta')
)
// We don't exclude dynamic caches for the legacy PPR prerendering.
expect(cacheLifeWithDynamicMeta.headers['x-nextjs-stale-time']).toBe(
'18'
)
}
})
it('should send an SWR cache-control header based on the revalidate and expire values', async () => {
......@@ -556,6 +590,30 @@ describe('use-cache', () => {
)
})
if (withCacheComponents) {
it('should omit dynamic caches from prerendered shells', async () => {
const browser = await next.browser('/cache-life-with-dynamic', {
disableJavaScript: true,
})
expect(await browser.elementById('y').text()).toBe('Loading...')
})
}
it('should not have hydration errors when resuming a partial shell with dynamic caches', async () => {
const browser = await next.browser('/cache-life-with-dynamic', {
pushErrorAsConsoleLog: true,
})
await retry(async () => {
expect(await browser.elementById('y').text()).not.toBe('Loading...')
})
// There should be no hydration errors due to a buildtime date being
// replaced by a new runtime date.
await assertNoConsoleErrors(browser)
})
it('should propagate unstable_cache tags correctly', async () => {
const meta = JSON.parse(
await next.readFile('.next/server/app/cache-tag.meta')
......@@ -962,8 +1020,8 @@ describe('use-cache', () => {
})
}
if (isNextStart && process.env.__NEXT_EXPERIMENTAL_PPR === 'true') {
it('should exclude inner caches from the resume data cache (RDC)', async () => {
if (isNextStart && withPPR) {
it('should exclude inner caches and omitted caches from the resume data cache (RDC)', async () => {
await next.fetch('/rdc')
const resumeDataCache = extractResumeDataCacheFromPostponedState(
......@@ -974,11 +1032,21 @@ describe('use-cache', () => {
// There should be no cache entry for the "middle" cache function, because
// it's only used inside another cache scope ("outer"). Whereas "inner" is
// also used inside a prerender scope (the page). Note: We're matching on
// the "id" args that are encoded into the respective cache keys.
// also used inside a prerender scope (the page). Additionally, there
// should also be no cache entry for "short", because it has a short
// lifetime and is subsequently omitted from the prerendered shell. The
// following expectation is matching on the full list. If any additional
// keys are found, the test will fail and print the unexpected keys.
expect(cacheKeys).toMatchObject([
// Note: We're matching on the args that are encoded into the respective
// cache keys.
expect.stringContaining('["outer"]'),
expect.stringContaining('["inner"]'),
...(withCacheComponents
? []
: // With legacy PPR, the "short" cache is included in the prerendered
// shell.
[expect.stringContaining('[{"id":"short"},"$undefined"]]')]),
])
})
}
......
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