Unverified Commit da024c19 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

[cache components] move experimental.cacheHandlers out of experimental (#85157)

Moves this flag out of experimental so that custom `use cache` handlers
can be configured alongside the cache components release.
parent 7a801959
......@@ -187,7 +187,7 @@ impl ServerNftJsonAsset {
let cache_handlers = self
.project
.next_config()
.experimental_cache_handlers(project_path.clone())
.cache_handlers(project_path.clone())
.await?;
// These are used by packages/next/src/server/require-hook.ts
......
......@@ -86,7 +86,7 @@ pub struct NextConfig {
cache_max_memory_size: Option<f64>,
/// custom path to a cache handler to use
cache_handler: Option<RcStr>,
cache_handlers: Option<FxIndexMap<RcStr, RcStr>>,
env: FxIndexMap<String, JsonValue>,
experimental: ExperimentalConfig,
images: ImageConfig,
......@@ -823,7 +823,6 @@ pub struct ExperimentalConfig {
adjust_font_fallbacks_with_size_adjust: Option<bool>,
after: Option<bool>,
app_document_preloading: Option<bool>,
cache_handlers: Option<FxIndexMap<RcStr, RcStr>>,
cache_life: Option<FxIndexMap<String, CacheLifeProfile>>,
case_sensitive_routes: Option<bool>,
cpus: Option<f64>,
......@@ -1601,11 +1600,8 @@ impl NextConfig {
}
#[turbo_tasks::function]
pub fn experimental_cache_handlers(
&self,
project_path: FileSystemPath,
) -> Result<Vc<FileSystemPathVec>> {
if let Some(handlers) = &self.experimental.cache_handlers {
pub fn cache_handlers(&self, project_path: FileSystemPath) -> Result<Vc<FileSystemPathVec>> {
if let Some(handlers) = &self.cache_handlers {
Ok(Vc::cell(
handlers
.values()
......@@ -1763,7 +1759,7 @@ impl NextConfig {
pub fn cache_kinds(&self) -> Vc<CacheKinds> {
let mut cache_kinds = CacheKinds::default();
if let Some(handlers) = self.experimental.cache_handlers.as_ref() {
if let Some(handlers) = self.cache_handlers.as_ref() {
cache_kinds.extend(handlers.keys().cloned());
}
......
......@@ -3191,7 +3191,7 @@ fn emit_error(error_kind: ServerActionsErrorKind) {
span,
formatdoc! {
r#"
Unknown cache kind "{cache_kind}". Please configure a cache handler for this kind in the `experimental.cacheHandlers` object in your Next.js config.
Unknown cache kind "{cache_kind}". Please configure a cache handler for this kind in the `cacheHandlers` object in your Next.js config.
"#
},
),
......
x Unknown cache kind "x". Please configure a cache handler for this kind in the `experimental.cacheHandlers` object in your Next.js config.
x Unknown cache kind "x". Please configure a cache handler for this kind in the `cacheHandlers` object in your Next.js config.
|
,-[input.js:1:1]
1 | 'use cache: x'
......
x Unknown cache kind "x". Please configure a cache handler for this kind in the `experimental.cacheHandlers` object in your Next.js config.
x Unknown cache kind "x". Please configure a cache handler for this kind in the `cacheHandlers` object in your Next.js config.
|
,-[input.js:2:1]
1 | export async function foo() {
......
......@@ -898,5 +898,7 @@
"897": "Expected HTML document to start with doctype prefix",
"898": "When using Cache Components, all `generateStaticParams` functions must return at least one result. This is to ensure that we can perform build-time validation that there is no other dynamic accesses that would cause a runtime error.\n\nLearn more: https://nextjs.org/docs/messages/empty-generate-static-params",
"899": "Both \"%s\" and \"%s\" files are detected. Please use \"%s\" instead. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy"
"900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"901": "Invalid \"cacheHandlers\" provided, expected an object e.g. { default: '/my-handler.js' }, received %s",
"902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s"
}
......@@ -140,8 +140,7 @@ export async function collectBuildTraces({
})
)
const { cacheHandler } = config
const { cacheHandlers } = config.experimental
const { cacheHandler, cacheHandlers } = config
// ensure we trace any dependencies needed for custom
// incremental cache handler
......
......@@ -616,9 +616,7 @@ export function getEdgeServerEntry(opts: {
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
cacheHandlers: JSON.stringify(
opts.config.experimental.cacheHandlers || {}
),
cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}),
}
return {
......@@ -685,7 +683,7 @@ export function getEdgeServerEntry(opts: {
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
serverActions: opts.config.experimental.serverActions,
cacheHandlers: JSON.stringify(opts.config.experimental.cacheHandlers || {}),
cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}),
}
return {
......
......@@ -2228,7 +2228,7 @@ export default async function build(
cacheComponents: isAppCacheComponentsEnabled,
authInterrupts: isAuthInterruptsEnabled,
cacheHandler: config.cacheHandler,
cacheHandlers: config.experimental.cacheHandlers,
cacheHandlers: config.cacheHandlers,
isrFlushToDisk: ciEnvironment.hasNextSupport
? false
: config.experimental.isrFlushToDisk,
......@@ -2523,7 +2523,7 @@ export default async function build(
const normalizedCacheHandlers: Record<string, string> = {}
for (const [key, value] of Object.entries(
config.experimental.cacheHandlers || {}
config.cacheHandlers || {}
)) {
if (key && value) {
normalizedCacheHandlers[key] = path.relative(distDir, value)
......@@ -2543,9 +2543,9 @@ export default async function build(
cacheHandler: cacheHandler
? path.relative(distDir, cacheHandler)
: config.cacheHandler,
cacheHandlers: normalizedCacheHandlers,
experimental: {
...config.experimental,
cacheHandlers: normalizedCacheHandlers,
trustHostHeader: ciEnvironment.hasNextSupport,
isExperimentalCompile: isCompileMode,
},
......
......@@ -747,7 +747,7 @@ export async function buildAppStaticPaths({
isrFlushToDisk?: boolean
fetchCacheKeyPrefix?: string
cacheHandler?: string
cacheHandlers?: NextConfigComplete['experimental']['cacheHandlers']
cacheHandlers?: NextConfigComplete['cacheHandlers']
cacheLifeProfiles?: {
[profile: string]: import('../../server/use-cache/cache-life').CacheLife
}
......
......@@ -859,26 +859,20 @@ function bindingToApi(
? path.relative(projectPath, nextConfigSerializable.cacheHandler)
: nextConfigSerializable.cacheHandler)
}
if (nextConfigSerializable.experimental?.cacheHandlers) {
nextConfigSerializable.experimental = {
...nextConfigSerializable.experimental,
cacheHandlers: Object.fromEntries(
Object.entries(
nextConfigSerializable.experimental.cacheHandlers as Record<
string,
string
>
)
.filter(([_, value]) => value != null)
.map(([key, value]) => [
key,
'./' +
(path.isAbsolute(value)
? path.relative(projectPath, value)
: value),
])
),
}
if (nextConfigSerializable.cacheHandlers) {
nextConfigSerializable.cacheHandlers = Object.fromEntries(
Object.entries(
nextConfigSerializable.cacheHandlers as Record<string, string>
)
.filter(([_, value]) => value != null)
.map(([key, value]) => [
key,
'./' +
(path.isAbsolute(value)
? path.relative(projectPath, value)
: value),
])
)
}
if (nextConfigSerializable.turbopack != null) {
......
......@@ -92,7 +92,7 @@ function getBaseSWCOptions({
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
isCacheComponents?: boolean
cacheHandlers?: ExperimentalConfig['cacheHandlers']
cacheHandlers?: NextConfig['cacheHandlers']
useCacheEnabled?: boolean
trackDynamicImports?: boolean
}) {
......@@ -412,7 +412,7 @@ export function getLoaderSWCOptions({
serverComponents?: boolean
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
cacheHandlers: ExperimentalConfig['cacheHandlers']
cacheHandlers: NextConfig['cacheHandlers']
useCacheEnabled?: boolean
trackDynamicImports?: boolean
}) {
......
......@@ -164,7 +164,7 @@ async function loaderTransform(
serverReferenceHashSalt,
bundleLayer,
esm,
cacheHandlers: nextConfig.experimental?.cacheHandlers,
cacheHandlers: nextConfig.cacheHandlers,
useCacheEnabled: nextConfig.experimental?.useCache,
trackDynamicImports,
})
......
......@@ -360,7 +360,7 @@ export async function exportPages(
// skip writing to disk in minimal mode for now, pending some
// changes to better support it
flushToDisk: !hasNextSupport,
cacheHandlers: nextConfig.experimental.cacheHandlers,
cacheHandlers: nextConfig.cacheHandlers,
})
renderOpts.incrementalCache = incrementalCache
......
......@@ -355,6 +355,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
bundlePagesRouterDependencies: z.boolean().optional(),
cacheComponents: z.boolean().optional(),
cacheHandler: z.string().min(1).optional(),
cacheHandlers: z.record(z.string(), z.string().optional()).optional(),
cacheLife: z
.record(
z.object({
......
......@@ -272,12 +272,8 @@ export interface LoggingConfig {
export interface ExperimentalConfig {
adapterPath?: string
useSkewCookie?: boolean
cacheHandlers?: {
default?: string
remote?: string
static?: string
[handlerName: string]: string | undefined
}
/** @deprecated use top-level `cacheHandlers` instead */
cacheHandlers?: NextConfig['cacheHandlers']
multiZoneDraftMode?: boolean
appNavFailHandling?: boolean
prerenderEarlyExit?: boolean
......@@ -308,19 +304,7 @@ export interface ExperimentalConfig {
/**
* @deprecated use top-level `cacheLife` instead
*/
cacheLife?: {
[profile: string]: {
// How long the client can cache a value without checking with the server.
stale?: number
// How frequently you want the cache to refresh on the server.
// Stale values may be served while revalidating.
revalidate?: number
// In the worst case scenario, where you haven't had traffic in a while,
// how stale can a value be until you prefer deopting to dynamic.
// Must be longer than revalidate.
expire?: number
}
}
cacheLife?: NextConfig['cacheLife']
// decimal for percent for possible false positives
// e.g. 0.01 for 10% potential false matches lower
// percent increases size of the filter
......@@ -1012,6 +996,13 @@ export interface NextConfig {
*/
cacheHandler?: string | undefined
cacheHandlers?: {
default?: string
remote?: string
static?: string
[handlerName: string]: string | undefined
}
/**
* Configure the in-memory cache size in bytes. Defaults to 50 MB.
* If `cacheMaxMemorySize: 0`, this disables in-memory caching entirely.
......@@ -1447,14 +1438,14 @@ export const defaultConfig = Object.freeze({
expire: 60 * 60 * 24 * 365, // 1 year
},
},
cacheHandlers: {
default: process.env.NEXT_DEFAULT_CACHE_HANDLER_PATH,
remote: process.env.NEXT_REMOTE_CACHE_HANDLER_PATH,
static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH,
},
experimental: {
adapterPath: process.env.NEXT_ADAPTER_PATH || undefined,
useSkewCookie: false,
cacheHandlers: {
default: process.env.NEXT_DEFAULT_CACHE_HANDLER_PATH,
remote: process.env.NEXT_REMOTE_CACHE_HANDLER_PATH,
static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH,
},
cssChunking: true,
multiZoneDraftMode: false,
appNavFailHandling: false,
......
......@@ -744,6 +744,13 @@ function assignDefaultsAndValidate(
configFileName,
silent
)
warnOptionHasBeenMovedOutOfExperimental(
result,
'cacheHandlers',
'cacheHandlers',
configFileName,
silent
)
if ((result.experimental as any).outputStandalone) {
if (!silent) {
......@@ -1146,16 +1153,16 @@ function assignDefaultsAndValidate(
}
}
if (result.experimental?.cacheHandlers) {
if (result.cacheHandlers) {
const allowedHandlerNameRegex = /[a-z-]/
if (typeof result.experimental.cacheHandlers !== 'object') {
if (typeof result.cacheHandlers !== 'object') {
throw new Error(
`Invalid "experimental.cacheHandlers" provided, expected an object e.g. { default: '/my-handler.js' }, received ${JSON.stringify(result.experimental.cacheHandlers)}`
`Invalid "cacheHandlers" provided, expected an object e.g. { default: '/my-handler.js' }, received ${JSON.stringify(result.cacheHandlers)}`
)
}
const handlerKeys = Object.keys(result.experimental.cacheHandlers)
const handlerKeys = Object.keys(result.cacheHandlers)
const invalidHandlerItems: Array<{ key: string; reason: string }> = []
for (const key of handlerKeys) {
......@@ -1172,7 +1179,7 @@ function assignDefaultsAndValidate(
})
} else {
const handlerPath = (
result.experimental.cacheHandlers as {
result.cacheHandlers as {
[handlerName: string]: string | undefined
}
)[key]
......@@ -1186,7 +1193,7 @@ function assignDefaultsAndValidate(
}
if (invalidHandlerItems.length) {
throw new Error(
`Invalid handler fields configured for "experimental.cacheHandler":\n${invalidHandlerItems.map((item) => `${key}: ${item.reason}`).join('\n')}`
`Invalid handler fields configured for "cacheHandlers":\n${invalidHandlerItems.map((item) => `${key}: ${item.reason}`).join('\n')}`
)
}
}
......
......@@ -761,7 +761,7 @@ export default class DevServer extends Server {
isAppPath,
requestHeaders,
cacheHandler: this.nextConfig.cacheHandler,
cacheHandlers: this.nextConfig.experimental.cacheHandlers,
cacheHandlers: this.nextConfig.cacheHandlers,
cacheLifeProfiles: this.nextConfig.cacheLife,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
......
......@@ -66,7 +66,7 @@ export async function loadStaticPaths({
cacheMaxMemorySize: number
requestHeaders: IncrementalCache['requestHeaders']
cacheHandler?: string
cacheHandlers?: NextConfigComplete['experimental']['cacheHandlers']
cacheHandlers?: NextConfigComplete['cacheHandlers']
cacheLifeProfiles?: {
[profile: string]: import('../../server/use-cache/cache-life').CacheLife
}
......
......@@ -459,10 +459,7 @@ export default class NextNodeServer extends BaseServer<
}
private async loadCustomCacheHandlers() {
const {
cacheMaxMemorySize,
experimental: { cacheHandlers },
} = this.nextConfig
const { cacheMaxMemorySize, cacheHandlers } = this.nextConfig
if (!cacheHandlers) return
// If we've already initialized the cache handlers interface, don't do it
......
......@@ -381,10 +381,7 @@ export abstract class RouteModule<
nextConfig: NextConfigComplete
) {
if (process.env.NEXT_RUNTIME !== 'edge') {
const {
cacheMaxMemorySize,
experimental: { cacheHandlers },
} = nextConfig
const { cacheMaxMemorySize, cacheHandlers } = nextConfig
if (!cacheHandlers) return
// If we've already initialized the cache handlers interface, don't do it
......
......@@ -3,10 +3,8 @@
*/
const nextConfig = {
cacheComponents: true,
experimental: {
cacheHandlers: {
default: require.resolve('./handler.js'),
},
cacheHandlers: {
default: require.resolve('./handler.js'),
},
}
......
......@@ -3,8 +3,8 @@
*/
const nextConfig = {
cacheComponents: true,
cacheHandlers: {}, // overwrite the default config
experimental: {
cacheHandlers: {}, // overwrite the default config
prerenderEarlyExit: false,
},
}
......
......@@ -41,7 +41,7 @@ describe('use-cache-unknown-cache-kind', () => {
3 | export default async function Page() {
4 | return <p>hello world</p>
Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config.
Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config.
......@@ -53,7 +53,7 @@ describe('use-cache-unknown-cache-kind', () => {
"
./app/page.tsx
× Module build failed:
╰─▶ × Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config.
╰─▶ × Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config.
│
│ ,-[1:1]
│ 1 | 'use cache: custom'
......@@ -75,7 +75,7 @@ describe('use-cache-unknown-cache-kind', () => {
expect(buildOutput).toMatchInlineSnapshot(`
"
./app/page.tsx
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config.
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config.
,-[1:1]
1 | 'use cache: custom'
......@@ -124,7 +124,7 @@ describe('use-cache-unknown-cache-kind', () => {
)
} else {
expect(errorDescription).toMatchInlineSnapshot(
`" x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config."`
`" x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config."`
)
}
......@@ -138,13 +138,13 @@ describe('use-cache-unknown-cache-kind', () => {
3 | export default async function Page() {
4 | return <p>hello world</p>
Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config."
Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config."
`)
} else if (isRspack) {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
× Module build failed:
╰─▶ × Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config.
╰─▶ × Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config.
│ |
│ ,-[1:1]
│ 1 | 'use cache: custom'
......@@ -158,7 +158,7 @@ describe('use-cache-unknown-cache-kind', () => {
} else {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`experimental.cacheHandlers\` object in your Next.js config.
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the \`cacheHandlers\` object in your Next.js config.
,-[1:1]
1 | 'use cache: custom'
......@@ -180,13 +180,11 @@ describe('use-cache-unknown-cache-kind', () => {
await session.patch(
'next.config.js',
`module.exports = {
experimental: {
cacheComponents: true,
cacheHandlers: {
custom: require.resolve(
'next/dist/server/lib/cache-handlers/default.external'
),
},
cacheComponents: true,
cacheHandlers: {
custom: require.resolve(
'next/dist/server/lib/cache-handlers/default.external'
),
},
}`
)
......
......@@ -2,13 +2,13 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheHandlers: {
custom: require.resolve(
'next/dist/server/lib/cache-handlers/default.external'
),
},
experimental: {
useCache: true,
cacheHandlers: {
custom: require.resolve(
'next/dist/server/lib/cache-handlers/default.external'
),
},
},
cacheLife: {
frequent: {
......
module.exports = {
experimental: {
cacheComponents: true,
cacheHandlers: {
custom: require.resolve('next/dist/server/lib/cache-handlers/default.external'),
},
cacheComponents: true,
cacheHandlers: {
custom: require.resolve('next/dist/server/lib/cache-handlers/default.external'),
},
}
......@@ -4,9 +4,9 @@
const nextConfig = {
experimental: {
useCache: true,
cacheHandlers: {
default: require.resolve('./cache-handler.js'),
},
},
cacheHandlers: {
default: require.resolve('./cache-handler.js'),
},
}
......
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