Unverified Commit d54122a7 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Emit build error for unknown cache kinds (#72832)

When a `"use cache"` directive with a custom cache kind is used, e.g.
`"use cache: custom"`, a cache handler with the same name must be
specified in the Next.js config:

```js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  experimental: {
    dynamicIO: true,
    cacheHandlers: {
      custom: require.resolve('path/to/custom/cache/handler'),
    },
  },
}

module.exports = nextConfig
```

If this is not the case, we emit a build error with an error message
that explains this requirement.

<img width="795" alt="Screenshot 2024-11-14 at 23 30 01"
src="https://github.com/user-attachments/assets/bd138c97-608f-42ce-abb2-edb3e44edc3f">

When we'll get a docs page for this experimental config, we will add the
usual "Read more: ..." hint as well.

---------
Co-authored-by: 's avatarBenjamin Woodruff <benjamin.woodruff@vercel.com>
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent ef9d0969
......@@ -4086,6 +4086,7 @@ dependencies = [
"swc_relay",
"testing",
"tracing",
"turbo-rcstr",
"turbopack-ecmascript-plugins",
"walkdir",
]
......
......@@ -47,12 +47,8 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_debug_fn_name_rule(enable_mdx_rs));
}
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false;
match context_ty {
......@@ -79,6 +75,7 @@ pub async fn get_next_client_transforms_rules(
ActionsTransform::Client,
enable_mdx_rs,
dynamic_io_enabled,
cache_kinds,
));
}
ClientContextType::Fallback | ClientContextType::Other => {}
......
use std::collections::HashSet;
use anyhow::{bail, Context, Result};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use turbo_rcstr::RcStr;
......@@ -40,6 +41,9 @@ struct CustomRoutes {
#[turbo_tasks::value(transparent)]
pub struct ModularizeImports(FxIndexMap<String, ModularizeImportPackageConfig>);
#[turbo_tasks::value(transparent)]
pub struct CacheKinds(FxHashSet<RcStr>);
#[turbo_tasks::value(serialization = "custom", eq = "manual")]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
......@@ -520,7 +524,7 @@ pub struct ExperimentalConfig {
pub sri: Option<SubResourceIntegrity>,
react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")]
pub dynamic_io: Option<bool>,
dynamic_io: Option<bool>,
// ---
// UNSUPPORTED
// ---
......@@ -529,6 +533,7 @@ pub struct ExperimentalConfig {
after: Option<bool>,
amp: Option<serde_json::Value>,
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>,
......@@ -1150,10 +1155,24 @@ impl NextConfig {
}
#[turbo_tasks::function]
pub async fn enable_react_owner_stack(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(
self.await?.experimental.react_owner_stack.unwrap_or(false),
))
pub fn enable_react_owner_stack(&self) -> Vc<bool> {
Vc::cell(self.experimental.react_owner_stack.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn enable_dynamic_io(&self) -> Vc<bool> {
Vc::cell(self.experimental.dynamic_io.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn cache_kinds(&self) -> Vc<CacheKinds> {
Vc::cell(
self.experimental
.cache_handlers
.as_ref()
.map(|handlers| handlers.keys().cloned().collect())
.unwrap_or_default(),
)
}
#[turbo_tasks::function]
......
......@@ -54,12 +54,8 @@ pub async fn get_next_server_transforms_rules(
));
}
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false;
let is_server_components = match context_ty {
......@@ -96,6 +92,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Client,
mdx_rs,
dynamic_io_enabled,
cache_kinds,
));
is_app_dir = true;
......@@ -107,6 +104,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server,
mdx_rs,
dynamic_io_enabled,
cache_kinds,
));
is_app_dir = true;
......@@ -118,6 +116,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server,
mdx_rs,
dynamic_io_enabled,
cache_kinds,
));
is_app_dir = true;
......
......@@ -34,11 +34,7 @@ pub async fn get_next_react_server_components_transform_rule(
app_dir: Option<Vc<FileSystemPath>>,
) -> Result<ModuleRule> {
let enable_mdx_rs = next_config.mdx_rs().await?.is_some();
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
Ok(get_ecma_transform_rule(
Box::new(NextJsReactServerComponents::new(
is_react_server_layer,
......
......@@ -7,6 +7,7 @@ use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
use super::module_rule_match_js_no_url;
use crate::next_config::CacheKinds;
#[derive(Debug)]
pub enum ActionsTransform {
......@@ -19,11 +20,13 @@ pub fn get_server_actions_transform_rule(
transform: ActionsTransform,
enable_mdx_rs: bool,
dynamic_io_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
) -> ModuleRule {
let transformer =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions {
transform,
dynamic_io_enabled,
cache_kinds,
}) as _));
ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs),
......@@ -38,6 +41,7 @@ pub fn get_server_actions_transform_rule(
struct NextServerActions {
transform: ActionsTransform,
dynamic_io_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
}
#[async_trait]
......@@ -50,6 +54,7 @@ impl CustomTransformer for NextServerActions {
is_react_server_layer: matches!(self.transform, ActionsTransform::Server),
dynamic_io_enabled: self.dynamic_io_enabled,
hash_salt: "".into(),
cache_kinds: self.cache_kinds.await?.clone_value(),
},
ctx.comments.clone(),
);
......
......@@ -56,6 +56,7 @@ styled_jsx = { workspace = true }
swc_emotion = { workspace = true }
swc_relay = { workspace = true }
turbopack-ecmascript-plugins = { workspace = true, optional = true }
turbo-rcstr = { workspace = true }
react_remove_properties = "0.24.25"
remove_console = "0.25.25"
......
use std::path::PathBuf;
use std::{iter::FromIterator, path::PathBuf};
use next_custom_transforms::transforms::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page,
......@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{
},
strip_page_exports::{next_transform_strip_page_exports, ExportFilter},
};
use rustc_hash::FxHashSet;
use swc_core::{
common::{FileName, Mark},
ecma::{
......@@ -187,6 +188,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
tr.comments.as_ref().clone(),
),
......@@ -226,6 +228,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
is_react_server_layer: false,
dynamic_io_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
tr.comments.as_ref().clone(),
),
......@@ -283,6 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) {
is_react_server_layer: true,
dynamic_io_enabled: false,
hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
},
tr.comments.as_ref().clone(),
),
......
'use cache: x'
export async function foo() {
return 'data'
}
/* __next_internal_action_entry_do_not_use__ {"803128060c414d59f8552e4788b846c0d2b7f74743":"$$RSC_SERVER_CACHE_0"} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
export var $$RSC_SERVER_CACHE_0 = $$cache__("x", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, async function foo() {
return 'data';
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "foo",
"writable": false
});
export var foo = registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x Unknown cache kind "x". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[input.js:1:1]
1 | 'use cache: x'
: ^^^^^^^^^^^^^^
`----
export async function foo() {
'use cache: x'
return 'data'
}
/* __next_internal_action_entry_do_not_use__ {"803128060c414d59f8552e4788b846c0d2b7f74743":"$$RSC_SERVER_CACHE_0"} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
export var $$RSC_SERVER_CACHE_0 = $$cache__("x", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, async function foo() {
return 'data';
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "foo",
"writable": false
});
export var foo = registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x Unknown cache kind "x". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[input.js:2:1]
1 | export async function foo() {
2 | 'use cache: x'
: ^^^^^^^^^^^^^^
`----
use std::{
env::current_dir,
iter::FromIterator,
path::{Path, PathBuf},
};
......@@ -21,6 +22,7 @@ use next_custom_transforms::transforms::{
strip_page_exports::{next_transform_strip_page_exports, ExportFilter},
warn_for_edge_runtime::warn_for_edge_runtime,
};
use rustc_hash::FxHashSet;
use serde::de::DeserializeOwned;
use swc_core::{
common::{comments::SingleThreadedComments, FileName, Mark, SyntaxContext},
......@@ -416,6 +418,7 @@ fn server_actions_server_fixture(input: PathBuf) {
is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
},
_tr.comments.as_ref().clone(),
),
......@@ -448,6 +451,7 @@ fn next_font_with_directive_fixture(input: PathBuf) {
is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
_tr.comments.as_ref().clone(),
),
......@@ -473,6 +477,7 @@ fn server_actions_client_fixture(input: PathBuf) {
is_react_server_layer: false,
dynamic_io_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
_tr.comments.as_ref().clone(),
),
......
......@@ -65,6 +65,7 @@ function getBaseSWCOptions({
serverReferenceHashSalt,
bundleLayer,
isDynamicIo,
cacheHandlers,
}: {
filename: string
jest?: boolean
......@@ -82,6 +83,7 @@ function getBaseSWCOptions({
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
isDynamicIo?: boolean
cacheHandlers?: ExperimentalConfig['cacheHandlers']
}) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
......@@ -211,6 +213,7 @@ function getBaseSWCOptions({
isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
hashSalt: serverReferenceHashSalt,
cacheKinds: cacheHandlers ? Object.keys(cacheHandlers) : [],
}
: undefined,
// For app router we prefer to bundle ESM,
......@@ -355,6 +358,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt,
bundleLayer,
esm,
cacheHandlers,
}: {
filename: string
development: boolean
......@@ -379,6 +383,7 @@ export function getLoaderSWCOptions({
serverComponents?: boolean
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
cacheHandlers: ExperimentalConfig['cacheHandlers']
}) {
let baseOptions: any = getBaseSWCOptions({
filename,
......@@ -396,6 +401,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt,
esm: !!esm,
isDynamicIo,
cacheHandlers,
})
baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'],
......
......@@ -142,6 +142,7 @@ async function loaderTransform(
serverReferenceHashSalt,
bundleLayer,
esm,
cacheHandlers: nextConfig.experimental?.cacheHandlers,
})
const programmaticOptions = {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use cache: custom'
export default async function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { NextConfig } from 'next'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
getRedboxSource,
retry,
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const nextConfigWithCacheHandler: NextConfig = {
experimental: {
dynamicIO: true,
cacheHandlers: {
custom: require.resolve('next/dist/server/lib/cache-handlers/default'),
},
},
}
describe('use-cache-unknown-cache-kind', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextStart) {
it('should fail the build with an error', async () => {
const { cliOutput } = await next.build()
const buildOutput = getBuildOutput(cliOutput)
if (isTurbopack) {
expect(buildOutput).toMatchInlineSnapshot(`
"Error: Turbopack build failed with 1 errors:
Page: {"type":"app","side":"server","page":"/page"}
./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache: custom'
| ^^^^^^^^^^^^^^^^^^^
2 |
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.
at <unknown> (./app/page.tsx:1:1)"
`)
} else {
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.
|
,-[1:1]
1 | 'use cache: custom'
: ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./app/page.tsx
> Build failed because of webpack errors
"
`)
}
})
} else {
it('should show a build error', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
expect(errorDescription).toBe('Failed to compile')
if (isTurbopack) {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache: custom'
| ^^^^^^^^^^^^^^^^^^^
2 |
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."
`)
} 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.
|
,-[1:1]
1 | 'use cache: custom'
: ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
}
})
it('should recover from the build error if the cache handler is defined', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify(nextConfigWithCacheHandler)}`,
() =>
retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
await assertNoRedbox(browser)
})
)
})
}
})
function getBuildOutput(cliOutput: string): string {
const lines: string[] = []
let skipLines = true
for (const line of cliOutput.split('\n')) {
if (!skipLines) {
if (line.includes('at turbopackBuild')) {
break
}
lines.push(stripAnsi(line))
} else if (
line.includes('Build error occurred') ||
line.includes('Failed to compile')
) {
skipLines = false
}
}
return lines.join('\n')
}
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