Commit 6fa8395f authored by Jimmy Lai's avatar Jimmy Lai

Allow unstable_staleTime with cacheComponents and add coverage

parent a21f4028
......@@ -11,19 +11,19 @@ use regex::Regex;
use rustc_hash::FxHashMap;
use serde::Deserialize;
use swc_core::{
atoms::{atom, Atom, Wtf8Atom},
atoms::{Atom, Wtf8Atom, atom},
common::{
DUMMY_SP, FileName, Span, Spanned,
comments::{Comment, CommentKind, Comments},
errors::HANDLER,
util::take::Take,
FileName, Span, Spanned, DUMMY_SP,
},
ecma::{
ast::*,
utils::{prepend_stmts, quote_ident, quote_str, ExprFactory},
utils::{ExprFactory, prepend_stmts, quote_ident, quote_str},
visit::{
noop_visit_mut_type, noop_visit_type, visit_mut_pass, Visit, VisitMut, VisitMutWith,
VisitWith,
Visit, VisitMut, VisitMutWith, VisitWith, noop_visit_mut_type, noop_visit_type,
visit_mut_pass,
},
},
};
......@@ -370,7 +370,7 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
vec![span],
),
RSCErrorKind::NextRscErrStaleTimeInLayout(span) => (
"`unstable_staleTime` is only supported in pages, but you're using it in a layout. Please remove it."
"`unstable_staleTime` is only supported in page files (`page.js`, `page.jsx`, `page.ts`, `page.tsx`). You are using it in a layout file. Move this export to the corresponding page file or remove it from the layout."
.to_string(),
vec![span],
),
......@@ -952,17 +952,7 @@ impl ReactServerComponentValidator {
}
}
"unstable_staleTime" => {
if self.cache_components_enabled {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::CacheComponents,
),
*span,
),
);
} else if is_layout {
if is_layout {
possibly_invalid_exports.insert(
export_name.clone(),
(InvalidExportKind::StaleTimeInLayout, *span),
......
......@@ -1046,6 +1046,5 @@
"1045": "LRUCache: calculateSize returned %s%s, but size must be > 0. Items with size 0 would never be evicted, causing unbounded cache growth.",
"1046": "`draftMode` must not be used within a Client Component. Next.js should be preventing `draftMode` from being included in Client Components statically, but did not in this case.",
"1047": "Extra keys returned from getStaticPaths in %s (%s) Expected: { paths: [], fallback: boolean }\\nSee here for more info: https://nextjs.org/docs/messages/invalid-getstaticpaths-value",
"1048": "\\`unstable_staleTime\\` is only supported in pages, but you're using it in a layout. Please remove it.",
"1049": "Page \"%s\" cannot use \\`export const unstable_staleTime = ...\\` when \\`cacheComponents\\` is enabled."
"1048": "\\`unstable_staleTime\\` is only supported in page files (\\`page.js\\`, \\`page.jsx\\`, \\`page.ts\\`, \\`page.tsx\\`). You are using it in a layout file. Move this export to the corresponding page file or remove it from the layout."
}
......@@ -690,16 +690,10 @@ export async function getAppPageStaticInfo({
)
}
if ('unstable_staleTime' in config && nextConfig.cacheComponents) {
throw new Error(
`Page "${page}" cannot use \`export const unstable_staleTime = ...\` when \`cacheComponents\` is enabled.`
)
}
// unstable_staleTime is only supported on page segments, not layouts
if ('unstable_staleTime' in config && /\/layout\.[^/]+$/.test(pageFilePath)) {
throw new Error(
`\`unstable_staleTime\` is only supported in pages, but you're using it in a layout. Please remove it.`
`\`unstable_staleTime\` is only supported in page files (\`page.js\`, \`page.jsx\`, \`page.ts\`, \`page.tsx\`). You are using it in a layout file. Move this export to the corresponding page file or remove it from the layout.`
)
}
......
......@@ -232,7 +232,6 @@ import {
anySegmentNeedsInstantValidation,
} from './instant-validation/instant-config'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import { extractStaleTimeFromLoaderTree } from './extract-stale-time-from-loader-tree'
import {
createDebugChannel,
type DebugChannelPair,
......@@ -707,18 +706,6 @@ async function generateDynamicFlightRenderResult(
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
}
// Extract staleTime for dynamic pages if not already set by createComponentTree.
// This handles cases where walkTreeWithFlightRouterState short-circuits for
// prefetch requests without a loading component.
if (requestStore.stale === undefined) {
const extractedStaleTime = await extractStaleTimeFromLoaderTree(
ctx.componentMod.routeModule.userland.loaderTree
)
if (typeof extractedStaleTime === 'number') {
requestStore.stale = extractedStaleTime
}
}
const { clientModules } = getClientReferenceManifest()
// For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
......
import type { LoaderTree } from '../lib/app-dir-module'
import { getLayoutOrPageModule } from '../lib/app-dir-module'
/**
* Extracts the unstable_staleTime export from a loader tree.
* Walks the tree to find the page segment and extracts unstable_staleTime.
* Only page modules are checked - layouts do not support unstable_staleTime.
*/
export async function extractStaleTimeFromLoaderTree(
tree: LoaderTree
): Promise<number | undefined> {
const [, parallelRoutes] = tree
// Get the layout or page module for this segment
const { mod, modType } = await getLayoutOrPageModule(tree)
// Get unstable_staleTime only from page modules (not layouts)
let staleTime: number | undefined =
modType === 'page' && typeof mod?.unstable_staleTime === 'number'
? mod.unstable_staleTime
: undefined
// Walk through parallel routes (typically just 'children')
const parallelRouteKeys = Object.keys(parallelRoutes)
for (const key of parallelRouteKeys) {
const childTree = parallelRoutes[key]
const childStaleTime = await extractStaleTimeFromLoaderTree(childTree)
if (typeof childStaleTime === 'number') {
staleTime = childStaleTime
}
}
return staleTime
}
This diff is collapsed.
......@@ -5,8 +5,7 @@ export default function Page() {
<>
<p>
Tests for export const unstable_staleTime segment config. This test
suite does NOT use cacheComponents, as unstable_staleTime segment config
is not supported with cacheComponents.
suite verifies stale-time behavior with and without cacheComponents.
</p>
<ul>
<li>
......
......@@ -2,7 +2,7 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
// NO cacheComponents - export const unstable_staleTime doesn't work with cacheComponents
// Baseline config used for stale-time assertions.
experimental: {
staleTimes: {
dynamic: 30,
......
......@@ -3,6 +3,12 @@ import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
import { outdent } from 'outdent'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STALE_TIME_HEADER,
RSC_HEADER,
} from 'next/dist/client/components/app-router-headers'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
......@@ -75,6 +81,24 @@ describe('segment cache - export const unstable_staleTime', () => {
)
})
it('does not apply unstable_staleTime when route-tree prefetch short-circuits', async () => {
const response = await next.fetch('/stale-5-minutes', {
headers: {
[RSC_HEADER]: '1',
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/_tree',
},
})
expect(response.status).toBe(200)
expect(response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER)).toBeNull()
const prefetchResponse = await response.text()
expect(prefetchResponse).not.toContain(
'Page with unstable_staleTime = 300 (5 minutes)'
)
})
// TODO: Test for caching unstable_staleTime on navigation without prefetch
//
// Currently, navigation responses (without prefetch) cache the route tree
......@@ -129,7 +153,7 @@ describe('unstable_staleTime - layout build error', () => {
await retry(async () => {
expect(next.cliOutput).toContain(
"`unstable_staleTime` is only supported in pages, but you're using it in a layout. Please remove it."
'`unstable_staleTime` is only supported in page files (`page.js`, `page.jsx`, `page.ts`, `page.tsx`). You are using it in a layout file. Move this export to the corresponding page file or remove it from the layout.'
)
})
}
......@@ -137,8 +161,8 @@ describe('unstable_staleTime - layout build error', () => {
})
})
describe('unstable_staleTime - cacheComponents build error', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
describe('unstable_staleTime - cacheComponents', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
......@@ -148,7 +172,7 @@ describe('unstable_staleTime - cacheComponents build error', () => {
return
}
it('should error when unstable_staleTime is used with cacheComponents', async () => {
it('should allow unstable_staleTime when cacheComponents is enabled', async () => {
await next.patchFile(
'next.config.js',
outdent`
......@@ -157,29 +181,26 @@ describe('unstable_staleTime - cacheComponents build error', () => {
}
`,
async () => {
try {
await next.start()
} catch {
// we expect the build/start to fail
}
await next.start()
if (isNextDev) {
// In dev mode, we need to trigger the compilation by visiting a page
// with unstable_staleTime
// In dev mode, trigger compilation and ensure the route is served.
await next.fetch('/stale-5-minutes')
expect(next.cliOutput).not.toContain(
'cannot use `export const unstable_staleTime = ...` when `cacheComponents` is enabled.'
)
expect(next.cliOutput).not.toContain(
'"unstable_staleTime" is not compatible with `nextConfig.cacheComponents`. Please remove it.'
)
} else {
const pageMeta = JSON.parse(
await next.readFile('.next/server/app/stale-5-minutes.meta')
)
expect(pageMeta.headers['x-nextjs-stale-time']).toBe('300')
}
await retry(async () => {
if (isTurbopack) {
expect(next.cliOutput).toContain(
'"unstable_staleTime" is not compatible with `nextConfig.cacheComponents`. Please remove it.'
)
} else {
expect(next.cliOutput).toContain(
'cannot use `export const unstable_staleTime = ...` when `cacheComponents` is enabled.'
)
}
})
const response = await next.fetch('/stale-5-minutes')
expect(response.status).toBe(200)
}
)
})
......
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