Unverified Commit 7aa61377 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Emit build error when `useCache` is enabled and Edge runtime is used (#75279)

The `"use cache"` directive is not compatible with the Edge runtime.

When the `experimental.useCache` flag is enabled, we now emit a build
error for pages with `export const runtime = 'edge'`. This is analogous
to using the `experimental.dynamicIO` flag.

The other route segment configs that are forbidden when `dynamicIO` is
enabled, are currently still allowed for `useCache`:

- `dynamicParams`
- `dynamic`
- `fetchCache`
- `revalidate`
parent e431f9e6
......@@ -35,10 +35,12 @@ pub async fn get_next_react_server_components_transform_rule(
) -> Result<ModuleRule> {
let enable_mdx_rs = next_config.mdx_rs().await?.is_some();
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
let use_cache_enabled = *next_config.enable_use_cache().await?;
Ok(get_ecma_transform_rule(
Box::new(NextJsReactServerComponents::new(
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
app_dir,
)),
enable_mdx_rs,
......@@ -50,6 +52,7 @@ pub async fn get_next_react_server_components_transform_rule(
struct NextJsReactServerComponents {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
app_dir: Option<Vc<FileSystemPath>>,
}
......@@ -57,11 +60,13 @@ impl NextJsReactServerComponents {
fn new(
is_react_server_layer: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
app_dir: Option<Vc<FileSystemPath>>,
) -> Self {
Self {
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
app_dir,
}
}
......@@ -82,6 +87,7 @@ impl CustomTransformer for NextJsReactServerComponents {
Config::WithOptions(Options {
is_react_server_layer: self.is_react_server_layer,
dynamic_io_enabled: self.dynamic_io_enabled,
use_cache_enabled: self.use_cache_enabled,
}),
match self.app_dir {
None => None,
......
use std::{collections::HashMap, path::PathBuf, rc::Rc, sync::Arc};
use std::{
collections::HashMap,
fmt::{self, Display},
path::PathBuf,
rc::Rc,
sync::Arc,
};
use indexmap::IndexMap;
use once_cell::sync::Lazy;
......@@ -45,6 +51,7 @@ impl Config {
pub struct Options {
pub is_react_server_layer: bool,
pub dynamic_io_enabled: bool,
pub use_cache_enabled: bool,
}
/// A visitor that transforms given module to use module proxy if it's a React
......@@ -54,6 +61,7 @@ pub struct Options {
struct ReactServerComponents<C: Comments> {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
comments: C,
......@@ -80,13 +88,28 @@ enum RSCErrorKind {
NextRscErrInvalidApi((String, Span)),
NextRscErrDeprecatedApi((String, String, Span)),
NextSsrDynamicFalseNotAllowed(Span),
NextRscErrIncompatibleDynamicIoSegment(Span, String),
NextRscErrIncompatibleRouteSegmentConfig(Span, String, NextConfigProperty),
}
#[derive(Clone, Debug, Copy)]
enum NextConfigProperty {
DynamicIo,
UseCache,
}
impl Display for NextConfigProperty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NextConfigProperty::DynamicIo => write!(f, "experimental.dynamicIO"),
NextConfigProperty::UseCache => write!(f, "experimental.useCache"),
}
}
}
enum InvalidExportKind {
General,
Metadata,
DynamicIoSegment,
RouteSegmentConfig(NextConfigProperty),
}
impl<C: Comments> VisitMut for ReactServerComponents<C> {
......@@ -97,6 +120,7 @@ impl<C: Comments> VisitMut for ReactServerComponents<C> {
let mut validator = ReactServerComponentValidator::new(
self.is_react_server_layer,
self.dynamic_io_enabled,
self.use_cache_enabled,
self.filepath.clone(),
self.app_dir.clone(),
);
......@@ -318,8 +342,8 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
.to_string(),
vec![span],
),
RSCErrorKind::NextRscErrIncompatibleDynamicIoSegment(span, segment) => (
format!("Route segment config \"{}\" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.", segment),
RSCErrorKind::NextRscErrIncompatibleRouteSegmentConfig(span, segment, property) => (
format!("Route segment config \"{}\" is not compatible with `nextConfig.{}`. Please remove it.", segment, property),
vec![span],
),
};
......@@ -516,6 +540,7 @@ fn collect_top_level_directives_and_imports(
struct ReactServerComponentValidator {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
invalid_server_imports: Vec<JsWord>,
......@@ -534,12 +559,14 @@ impl ReactServerComponentValidator {
pub fn new(
is_react_server_layer: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
filename: String,
app_dir: Option<PathBuf>,
) -> Self {
Self {
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
filepath: filename,
app_dir,
directive_import_collection: None,
......@@ -769,11 +796,39 @@ impl ReactServerComponentValidator {
(InvalidExportKind::Metadata, *span),
);
}
"dynamicParams" | "dynamic" | "fetchCache" | "runtime" | "revalidate" => {
"runtime" => {
if self.dynamic_io_enabled {
possibly_invalid_exports.insert(
export_name.to_string(),
(InvalidExportKind::DynamicIoSegment, *span),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::DynamicIo,
),
*span,
),
);
} else if self.use_cache_enabled {
possibly_invalid_exports.insert(
export_name.to_string(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::UseCache,
),
*span,
),
);
}
}
"dynamicParams" | "dynamic" | "fetchCache" | "revalidate" => {
if self.dynamic_io_enabled {
possibly_invalid_exports.insert(
export_name.to_string(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::DynamicIo,
),
*span,
),
);
}
}
......@@ -815,13 +870,14 @@ impl ReactServerComponentValidator {
for (export_name, (kind, span)) in &possibly_invalid_exports {
match kind {
InvalidExportKind::DynamicIoSegment => {
InvalidExportKind::RouteSegmentConfig(property) => {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrIncompatibleDynamicIoSegment(
RSCErrorKind::NextRscErrIncompatibleRouteSegmentConfig(
*span,
export_name.clone(),
*property,
),
);
}
......@@ -985,11 +1041,21 @@ pub fn server_components_assert(
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
let use_cache_enabled: bool = match &config {
Config::WithOptions(x) => x.use_cache_enabled,
_ => false,
};
let filename = match filename {
FileName::Custom(path) => format!("<{path}>"),
_ => filename.to_string(),
};
ReactServerComponentValidator::new(is_react_server_layer, dynamic_io_enabled, filename, app_dir)
ReactServerComponentValidator::new(
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
filename,
app_dir,
)
}
/// Runs react server component transform for the module proxy, as well as
......@@ -1008,9 +1074,14 @@ pub fn server_components<C: Comments>(
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
let use_cache_enabled: bool = match &config {
Config::WithOptions(x) => x.use_cache_enabled,
_ => false,
};
visit_mut_pass(ReactServerComponents {
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
comments,
filepath: match &*filename {
FileName::Custom(path) => format!("<{path}>"),
......
......@@ -94,6 +94,7 @@ fn react_server_components_errors(input: PathBuf) {
use next_custom_transforms::transforms::react_server_components::{Config, Options};
let is_react_server_layer = input.iter().any(|s| s.to_str() == Some("server-graph"));
let dynamic_io_enabled = input.iter().any(|s| s.to_str() == Some("dynamic-io"));
let use_cache_enabled = input.iter().any(|s| s.to_str() == Some("use-cache"));
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
......@@ -103,6 +104,7 @@ fn react_server_components_errors(input: PathBuf) {
Config::WithOptions(Options {
is_react_server_layer,
dynamic_io_enabled,
use_cache_enabled,
}),
tr.comments.as_ref().clone(),
None,
......@@ -154,6 +156,7 @@ fn react_server_actions_errors(input: PathBuf) {
Config::WithOptions(Options {
is_react_server_layer,
dynamic_io_enabled: true,
use_cache_enabled: true,
}),
tr.comments.as_ref().clone(),
None,
......@@ -213,6 +216,7 @@ fn use_cache_not_allowed(input: PathBuf) {
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
use_cache_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......
export const runtime = 'edge'
// The following route segment configs are currently allowed:
export const dynamic = 'force-dynamic'
export const dynamicParams = false
export const fetchCache = 'force-no-store'
export const revalidate = 1
export const runtime = 'edge';
// The following route segment configs are currently allowed:
export const dynamic = 'force-dynamic';
export const dynamicParams = false;
export const fetchCache = 'force-no-store';
export const revalidate = 1;
x Route segment config "runtime" is not compatible with `nextConfig.experimental.useCache`. Please remove it.
,-[input.js:1:1]
1 | export const runtime = 'edge'
: ^^^^^^^
2 | // The following route segment configs are currently allowed:
`----
......@@ -475,6 +475,7 @@ fn react_server_components_typescript(input: PathBuf) {
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
use_cache_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......@@ -502,6 +503,7 @@ fn react_server_components_fixture(input: PathBuf) {
Config::WithOptions(Options {
is_react_server_layer,
dynamic_io_enabled: false,
use_cache_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......
......@@ -212,6 +212,7 @@ function getBaseSWCOptions({
? {
isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
useCacheEnabled,
}
: undefined,
serverActions:
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
export const runtime = 'edge'
export default function Page() {
return <div>This page uses `export const runtime`.</div>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useCache: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
getRedboxSource,
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('use-cache-segment-configs', () => {
const { next, skipped, isNextDev, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
skipDeployment: true,
})
if (skipped) {
return
}
it("it should error when using segment configs that aren't supported by useCache", async () => {
if (isNextDev) {
const browser = await next.browser('/runtime')
if (isTurbopack) {
await assertHasRedbox(browser)
const description = await getRedboxDescription(browser)
const source = await getRedboxSource(browser)
expect(description).toBe('Failed to compile')
expect(source).toMatchInlineSnapshot(`
"./app/runtime/page.tsx:1:14
Ecmascript file had an error
> 1 | export const runtime = 'edge'
| ^^^^^^^
2 |
3 | export default function Page() {
4 | return <div>This page uses \`export const runtime\`.</div>
Route segment config "runtime" is not compatible with \`nextConfig.experimental.useCache\`. Please remove it."
`)
} else {
// TODO(veil): Figure out why dev overlay is not shown with Webpack when
// the runtime is 'edge'. It's possibly related to the import trace
// being wrong (pointing at the Webpack loader resource).
await assertNoRedbox(browser)
}
} else {
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":"/runtime/page"}
./app/runtime/page.tsx:1:14
Ecmascript file had an error
> 1 | export const runtime = 'edge'
| ^^^^^^^
2 |
3 | export default function Page() {
4 | return <div>This page uses \`export const runtime\`.</div>
Route segment config "runtime" is not compatible with \`nextConfig.experimental.useCache\`. Please remove it.
at <unknown> (./app/runtime/page.tsx:1:14)
"
`)
} else {
expect(buildOutput).toMatchInlineSnapshot(`
"
// TODO(veil): Fix broken import trace for Webpack loader resource.
Error: x Route segment config "runtime" is not compatible with \`nextConfig.experimental.useCache\`. Please remove it.
,-[1:1]
1 | export const runtime = 'edge'
: ^^^^^^^
2 |
3 | export default function Page() {
4 | return <div>This page uses \`export const runtime\`.</div>
\`----
Import trace for requested module:
// TODO(veil): Fix broken import trace for Webpack loader resource.
> Build failed because of webpack errors
"
`)
}
}
})
})
function getBuildOutput(cliOutput: string): string {
const lines: string[] = []
let skipLines = true
for (const line of cliOutput.split('\n')) {
if (!skipLines) {
if (line.includes('__next_edge_ssr_entry__')) {
lines.push(
'// TODO(veil): Fix broken import trace for Webpack loader resource.'
)
} else {
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