Unverified Commit 1fffea65 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Collect root param dependencies for `'use cache'` at build time (#99274)

parent c4608008
...@@ -11,6 +11,7 @@ use next_core::{ ...@@ -11,6 +11,7 @@ use next_core::{
ActionLayer, ActionManifestModuleId, ActionManifestWorkerEntry, ActionLayer, ActionManifestModuleId, ActionManifestWorkerEntry,
ActionManifestWorkerEntryDurability, ServerReferenceManifest, ActionManifestWorkerEntryDurability, ServerReferenceManifest,
}, },
root_param_getters_path,
util::NextRuntime, util::NextRuntime,
}; };
use swc_core::{ use swc_core::{
...@@ -239,6 +240,9 @@ impl Asset for ServerActionManifestAsset { ...@@ -239,6 +240,9 @@ impl Asset for ServerActionManifestAsset {
let durable_use_cache_entries = *next_config let durable_use_cache_entries = *next_config
.enable_durable_use_cache_entries(self.project.next_mode()) .enable_durable_use_cache_entries(self.project.next_mode())
.await?; .await?;
let static_root_param_tracking_enabled = *next_config
.enable_use_cache_static_root_param_tracking(self.project.next_mode())
.await?;
let hash_salt = next_config.output_hash_salt(); let hash_salt = next_config.output_hash_salt();
let loader_id = self.chunk_item.id().await?; let loader_id = self.chunk_item.id().await?;
...@@ -267,30 +271,14 @@ impl Asset for ServerActionManifestAsset { ...@@ -267,30 +271,14 @@ impl Asset for ServerActionManifestAsset {
// - next/dist/shared/lib/image-config-context.shared-runtime // - next/dist/shared/lib/image-config-context.shared-runtime
// - next/dist/shared/lib/router-context.shared-runtime // - next/dist/shared/lib/router-context.shared-runtime
// - next/dist/shared/lib/server-inserted-html.shared-runtime // - next/dist/shared/lib/server-inserted-html.shared-runtime
let app_project = self.project.app_project().await?.unwrap(); let modules_to_ignore = (durable_use_cache_entries || static_root_param_tracking_enabled)
let next_dir = get_next_package(self.project.project_path().owned().await?).await?; .then(|| get_use_cache_modules_to_ignore(*self.project));
let source_to_ignore = FileSource::new(
next_dir.join("dist/server/route-modules/app-page/module.compiled.js")?,
);
let modules_to_ignore = Vc::cell(
[
app_project.rsc_module_context(),
app_project.route_module_context(),
]
.iter()
.map(|c| {
c.process(Vc::upcast(source_to_ignore), ReferenceType::Undefined)
.module()
.to_resolved()
})
.try_join()
.await?,
);
struct ActionMetadata<'a> { struct ActionMetadata<'a> {
exported_name: &'a str, exported_name: &'a str,
filename: Cow<'a, str>, filename: Cow<'a, str>,
data: Option<ReadRef<ModulesInformation>>, data: Option<ReadRef<ModulesInformation>>,
root_param_dependencies: Option<ReadRef<Vec<RcStr>>>,
} }
let action_metadata: Vec<(&str, ActionMetadata<'_>)> = actions_value let action_metadata: Vec<(&str, ActionMetadata<'_>)> = actions_value
...@@ -315,7 +303,24 @@ impl Asset for ServerActionManifestAsset { ...@@ -315,7 +303,24 @@ impl Asset for ServerActionManifestAsset {
**module, **module,
*self.chunking_context, *self.chunking_context,
hash_salt, hash_salt,
modules_to_ignore, modules_to_ignore
.expect("cache metadata collection requires module exclusions"),
)
.await?,
)
} else {
None
};
let root_param_dependencies = if static_root_param_tracking_enabled
&& extract_type_from_server_reference_id(hash_id)
== ServerReferenceType::UseCache
{
Some(
collect_root_param_dependencies_from_graph(
*self.module_graph,
**module,
modules_to_ignore
.expect("cache metadata collection requires module exclusions"),
) )
.await?, .await?,
) )
...@@ -329,6 +334,7 @@ impl Asset for ServerActionManifestAsset { ...@@ -329,6 +334,7 @@ impl Asset for ServerActionManifestAsset {
exported_name: &meta.name, exported_name: &meta.name,
filename, filename,
data, data,
root_param_dependencies,
}, },
)) ))
}) })
...@@ -342,6 +348,7 @@ impl Asset for ServerActionManifestAsset { ...@@ -342,6 +348,7 @@ impl Asset for ServerActionManifestAsset {
exported_name, exported_name,
filename, filename,
data, data,
root_param_dependencies,
}, },
) in &action_metadata ) in &action_metadata
{ {
...@@ -358,6 +365,9 @@ impl Asset for ServerActionManifestAsset { ...@@ -358,6 +365,9 @@ impl Asset for ServerActionManifestAsset {
runtime_env_vars_read: d.runtime_env_vars_read.as_slice(), runtime_env_vars_read: d.runtime_env_vars_read.as_slice(),
runtime_env_vars_existence: d.runtime_env_vars_existence.as_slice(), runtime_env_vars_existence: d.runtime_env_vars_existence.as_slice(),
}), }),
root_param_dependencies: root_param_dependencies
.as_ref()
.map(|names| names.as_slice()),
}, },
); );
...@@ -417,6 +427,102 @@ struct ModulesInformation { ...@@ -417,6 +427,102 @@ struct ModulesInformation {
pub runtime_env_vars_existence: Vec<RcStr>, pub runtime_env_vars_existence: Vec<RcStr>,
} }
#[turbo_tasks::function]
async fn get_use_cache_modules_to_ignore(project: ResolvedVc<Project>) -> Result<Vc<Modules>> {
let app_project = project.app_project().await?.unwrap();
let next_dir = get_next_package(project.project_path().owned().await?).await?;
let source_to_ignore =
FileSource::new(next_dir.join("dist/server/route-modules/app-page/module.compiled.js")?);
Ok(Vc::cell(
[
app_project.rsc_module_context(),
app_project.route_module_context(),
]
.iter()
.map(|c| {
c.process(Vc::upcast(source_to_ignore), ReferenceType::Undefined)
.module()
.to_resolved()
})
.try_join()
.await?,
))
}
fn collect_cache_modules(
graph: &ModuleGraph,
entry: ResolvedVc<Box<dyn Module>>,
ignored: &[ResolvedVc<Box<dyn Module>>],
) -> Result<FxIndexSet<ResolvedVc<Box<dyn Module>>>> {
let mut modules = FxIndexSet::default();
graph.traverse_edges_dfs(
std::iter::once(entry),
&mut (),
|_, target, _| {
if ignored.contains(&target) {
return Ok(GraphTraversalAction::Exclude);
}
if ResolvedVc::try_downcast_type::<CssClientReferenceModule>(target).is_some() {
// CSS client references do not execute code on the server.
return Ok(GraphTraversalAction::Exclude);
}
if ResolvedVc::try_downcast_type::<EcmascriptClientReferenceModule>(target).is_some() {
// Include the proxy, but do not traverse client
// implementations.
modules.insert(target);
return Ok(GraphTraversalAction::Exclude);
}
modules.insert(target);
Ok(GraphTraversalAction::Continue)
},
|_, _, _| Ok(()),
true,
)?;
Ok(modules)
}
// Returns the sorted root param dependencies from this cache module's graph. A
// callable received at runtime can read other root params. The runtime must
// check reads against this list when it uses the list for upfront cache keys.
#[turbo_tasks::function]
async fn collect_root_param_dependencies_from_graph(
module_graph: ResolvedVc<ModuleGraph>,
entry: ResolvedVc<Box<dyn Module>>,
modules_to_ignore: Vc<Modules>,
) -> Result<Vc<Vec<RcStr>>> {
let span = tracing::info_span!(
"collect use-cache root param dependencies",
entry = display(entry.ident_string().await?)
);
async {
let graph = module_graph.await?;
let ignored = modules_to_ignore.await?;
let modules = collect_cache_modules(&graph, entry, &ignored)?;
let getters_path = root_param_getters_path().await?;
let mut names = modules
.iter()
.map(async |module| {
let ident = module.ident().await?;
if let Some(filename) = getters_path.get_path_to(&ident.path)
&& let Some(name) = filename.strip_suffix(".js")
&& !name.is_empty()
&& !name.contains('/')
{
Ok(Some(RcStr::from(name)))
} else {
Ok(None)
}
})
.try_flat_join()
.await?;
names.sort_unstable();
names.dedup();
anyhow::Ok(Vc::cell(names))
}
.instrument(span)
.await
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn compute_subtree_content_hash( async fn compute_subtree_content_hash(
module_graph: ResolvedVc<ModuleGraph>, module_graph: ResolvedVc<ModuleGraph>,
...@@ -434,34 +540,7 @@ async fn compute_subtree_content_hash( ...@@ -434,34 +540,7 @@ async fn compute_subtree_content_hash(
let async_module_info = module_graph.async_module_info(); let async_module_info = module_graph.async_module_info();
let modules_to_ignore = modules_to_ignore.await?; let modules_to_ignore = modules_to_ignore.await?;
let mut modules = FxIndexSet::default(); let modules = collect_cache_modules(&module_graph_value, entry, &modules_to_ignore)?;
module_graph_value.traverse_edges_dfs(
std::iter::once(entry),
/* state */ &mut (),
/* visit_preorder */
|_, target, _| {
if modules_to_ignore.contains(&target) {
Ok(GraphTraversalAction::Exclude)
} else if ResolvedVc::try_downcast_type::<CssClientReferenceModule>(target)
.is_some()
{
// Don't include the module at all. There is nothing that executes on the server
Ok(GraphTraversalAction::Exclude)
} else if ResolvedVc::try_downcast_type::<EcmascriptClientReferenceModule>(target)
.is_some()
{
// Include the client reference proxy module, but not the referenced client
// modules themselves.
modules.insert(target);
Ok(GraphTraversalAction::Exclude)
} else {
modules.insert(target);
Ok(GraphTraversalAction::Continue)
}
},
/* visit_postorder */ |_, _, _| Ok(()),
/* include_traced */ true,
)?;
let data = modules let data = modules
.into_iter() .into_iter()
......
...@@ -46,6 +46,7 @@ pub use next_edge::context::{ ...@@ -46,6 +46,7 @@ pub use next_edge::context::{
get_edge_compile_time_info, get_edge_resolve_options_context, get_edge_compile_time_info, get_edge_resolve_options_context,
}; };
pub use next_import_map::get_next_package; pub use next_import_map::get_next_package;
pub use next_root_params::root_param_getters_path;
pub use page_loader::{PageLoaderAsset, create_page_loader_entry_module}; pub use page_loader::{PageLoaderAsset, create_page_loader_entry_module};
pub use segment_config::{parse_segment_config_from_loader_tree, parse_segment_config_from_source}; pub use segment_config::{parse_segment_config_from_loader_tree, parse_segment_config_from_source};
pub use util::{PathType, get_asset_path_from_pathname, pathname_for_path}; pub use util::{PathType, get_asset_path_from_pathname, pathname_for_path};
...@@ -1107,6 +1107,7 @@ pub struct ExperimentalConfig { ...@@ -1107,6 +1107,7 @@ pub struct ExperimentalConfig {
cache_components: Option<bool>, cache_components: Option<bool>,
use_cache: Option<bool>, use_cache: Option<bool>,
durable_use_cache_entries: Option<bool>, durable_use_cache_entries: Option<bool>,
use_cache_static_root_param_tracking: Option<bool>,
runtime_server_deployment_id: Option<bool>, runtime_server_deployment_id: Option<bool>,
expose_testing_api_in_production_build: Option<bool>, expose_testing_api_in_production_build: Option<bool>,
...@@ -2230,6 +2231,24 @@ impl NextConfig { ...@@ -2230,6 +2231,24 @@ impl NextConfig {
}) })
} }
#[turbo_tasks::function]
pub async fn enable_use_cache_static_root_param_tracking(
self: Vc<Self>,
mode: Vc<NextMode>,
) -> Result<Vc<bool>> {
Ok(match *mode.await? {
NextMode::Development => Vc::cell(false),
NextMode::Build => Vc::cell(
*self.enable_use_cache().await?
&& self
.await?
.experimental
.use_cache_static_root_param_tracking
.unwrap_or(false),
),
})
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn use_react_experimental(&self) -> Vc<bool> { pub fn use_react_experimental(&self) -> Vc<bool> {
// Keep in sync with file:///./../../../packages/next/src/lib/needs-experimental-react.ts // Keep in sync with file:///./../../../packages/next/src/lib/needs-experimental-react.ts
......
...@@ -453,6 +453,12 @@ pub struct ActionManifestWorkerEntry<'a> { ...@@ -453,6 +453,12 @@ pub struct ActionManifestWorkerEntry<'a> {
pub is_async: bool, pub is_async: bool,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub durability: Option<ActionManifestWorkerEntryDurability<'a>>, pub durability: Option<ActionManifestWorkerEntryDurability<'a>>,
/// The sorted root param dependencies collected from the cache module's
/// graph. An empty list means that collection found no root params. The
/// build omits this field when it does not collect dependencies for the
/// module.
#[serde(skip_serializing_if = "Option::is_none")]
pub root_param_dependencies: Option<&'a [RcStr]>,
} }
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
......
...@@ -31,6 +31,12 @@ use crate::{ ...@@ -31,6 +31,12 @@ use crate::{
// The resolver extracts queries from module subpaths. // The resolver extracts queries from module subpaths.
const ROOT_PARAM_GETTER_MODULE: &str = "private-next-root-params/getter"; const ROOT_PARAM_GETTER_MODULE: &str = "private-next-root-params/getter";
/// The generated getters live in Next's internal filesystem. The collector uses
/// this directory to distinguish them from user files with the same names.
pub fn root_param_getters_path() -> Vc<FileSystemPath> {
next_js_file_path("root-params".into())
}
pub async fn insert_next_root_params_mapping( pub async fn insert_next_root_params_mapping(
import_map: &mut ImportMap, import_map: &mut ImportMap,
ty: Either<ServerContextType, ClientContextType>, ty: Either<ServerContextType, ClientContextType>,
...@@ -143,13 +149,15 @@ impl NextRootParamsMapper { ...@@ -143,13 +149,15 @@ impl NextRootParamsMapper {
) -> Result<Vc<ImportMapResult>> { ) -> Result<Vc<ImportMapResult>> {
let collected_root_params = collected_root_params.await?; let collected_root_params = collected_root_params.await?;
let (filename, module_content) = if let Some(param_name) = param_name { let (path, module_content) = if let Some(param_name) = &param_name {
ensure!( ensure!(
collected_root_params.contains(&param_name), collected_root_params.contains(param_name),
"Unknown root parameter in generated getter request: {param_name}" "Unknown root parameter in generated getter request: {param_name}"
); );
( (
format!("root-params/{param_name}.js").into(), root_param_getters_path()
.await?
.join(&format!("{param_name}.js"))?,
formatdoc!( formatdoc!(
r#" r#"
import {{ getRootParam }} from 'next/dist/server/request/root-params'; import {{ getRootParam }} from 'next/dist/server/request/root-params';
...@@ -172,11 +180,14 @@ impl NextRootParamsMapper { ...@@ -172,11 +180,14 @@ impl NextRootParamsMapper {
) )
})) }))
.join("\n"); .join("\n");
("root-params.js".into(), module_content) (
next_js_file_path("root-params.js".into()).owned().await?,
module_content,
)
}; };
let virtual_source = VirtualSource::new( let virtual_source = VirtualSource::new(
next_js_file_path(filename).owned().await?, path,
AssetContent::file(FileContent::Content(module_content.into()).cell()), AssetContent::file(FileContent::Content(module_content.into()).cell()),
) )
.to_resolved() .to_resolved()
......
...@@ -72,6 +72,10 @@ type Actions = { ...@@ -72,6 +72,10 @@ type Actions = {
[name: string]: { [name: string]: {
moduleId: string | number moduleId: string | number
async: boolean async: boolean
// Root param dependencies collected from the cache module's graph. An
// empty list means none were found; absence means collection did not
// run.
rootParamDependencies?: readonly string[]
durability?: { durability?: {
codeHash: string codeHash: string
runtimeEnvVarsRead: string[] runtimeEnvVarsRead: string[]
......
...@@ -504,6 +504,7 @@ export const experimentalSchema = { ...@@ -504,6 +504,7 @@ export const experimentalSchema = {
authInterrupts: z.boolean().optional(), authInterrupts: z.boolean().optional(),
useCache: z.boolean().optional(), useCache: z.boolean().optional(),
durableUseCacheEntries: z.boolean().optional(), durableUseCacheEntries: z.boolean().optional(),
useCacheStaticRootParamTracking: z.boolean().optional(),
useCacheTimeout: z.number().positive().optional(), useCacheTimeout: z.number().positive().optional(),
slowModuleDetection: z slowModuleDetection: z
.object({ .object({
......
...@@ -1487,6 +1487,13 @@ export interface ExperimentalConfig { ...@@ -1487,6 +1487,13 @@ export interface ExperimentalConfig {
*/ */
durableUseCacheEntries?: boolean durableUseCacheEntries?: boolean
/**
* Collects root param dependencies for `'use cache'` in Turbopack production
* builds. Defaults to `false`. When disabled, the server-reference manifest
* omits `rootParamDependencies`.
*/
useCacheStaticRootParamTracking?: boolean
/** /**
* Enables detection and reporting of slow modules during development builds. * Enables detection and reporting of slow modules during development builds.
* Enabling this may impact build performance to ensure accurate measurements. * Enabling this may impact build performance to ensure accurate measurements.
...@@ -2472,6 +2479,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2472,6 +2479,7 @@ export const defaultConfig = Object.freeze({
gestureTransition: false, gestureTransition: false,
inlineCss: false, inlineCss: false,
useCache: undefined, useCache: undefined,
useCacheStaticRootParamTracking: false,
slowModuleDetection: undefined, slowModuleDetection: undefined,
globalNotFound: false, globalNotFound: false,
explicitParallelRouteChildren: true, explicitParallelRouteChildren: true,
......
...@@ -573,10 +573,9 @@ function assignDefaultsAndValidate( ...@@ -573,10 +573,9 @@ function assignDefaultsAndValidate(
) )
} }
// Validate experimental.cssChunking compatibility with the active bundler. Graph mode is // Build and development phases validate bundler-specific options. Server,
// Turbopack-only; strict mode and `false` (single-chunk-per-module) are webpack-only. // info, and test phases do not select a bundler. They must accept
// Only validate during build/dev — `next start` doesn't pick a bundler and would otherwise // configuration from either bundler.
// see `process.env.TURBOPACK` unset and reject a valid `cssChunking: "graph"` config.
if ( if (
phase !== PHASE_PRODUCTION_SERVER && phase !== PHASE_PRODUCTION_SERVER &&
phase !== PHASE_INFO && phase !== PHASE_INFO &&
...@@ -589,6 +588,16 @@ function assignDefaultsAndValidate( ...@@ -589,6 +588,16 @@ function assignDefaultsAndValidate(
) )
} }
if (
result.experimental.useCacheStaticRootParamTracking &&
!process.env.TURBOPACK
) {
throw new Error(
`\`experimental.useCacheStaticRootParamTracking: true\` is only supported with Turbopack. ` +
`Please remove the option or run Next.js with Turbopack in ${configFileName}.`
)
}
const cssChunkingValue = result.experimental.cssChunking const cssChunkingValue = result.experimental.cssChunking
const cssChunkingMode = resolveCssChunkingMode(cssChunkingValue) const cssChunkingMode = resolveCssChunkingMode(cssChunkingValue)
if (cssChunkingMode === 'graph' && !process.env.TURBOPACK) { if (cssChunkingMode === 'graph' && !process.env.TURBOPACK) {
......
import { lang } from 'next/root-params'
export async function CachedView() {
return <span>{await lang()}</span>
}
'use client'
import { readRootLanguage } from './root-reader'
export function ClientView() {
return <button onClick={() => readRootLanguage()}>client</button>
}
import { lang } from 'next/root-params'
import { continueCycle } from './cycle-b'
export async function readCycleLanguage(remaining: number): Promise<string> {
return remaining === 0 ? lang() : continueCycle(remaining - 1)
}
import { readCycleLanguage } from './cycle-a'
export async function continueCycle(remaining: number): Promise<string> {
return readCycleLanguage(remaining)
}
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [
{ lang: 'en', countryCode: 'us' },
{ lang: 'fr', countryCode: 'ca' },
]
}
import { readDirect } from '../read-direct'
export default async function Page() {
return <p>{await readDirect()}</p>
}
import { readDirect } from './read-direct'
import { readTransitive } from './read-transitive'
import { readConditional } from './read-conditional'
import { readNested } from './read-nested'
import { readNamespace } from './read-namespace'
import { readIndependent } from './read-independent'
import { readAlias } from './read-alias'
import { readComponent } from './read-component'
import { readDynamicImport } from './read-dynamic-import'
import { readRequire } from './read-require'
import { readArguments } from './read-arguments'
import { foo, bar } from './read-module'
import { readCycle } from './read-cycle'
import { readLookalike } from './read-lookalike'
import { readClient } from './read-client'
export default async function Page() {
const values = await Promise.all([
readDirect(),
readTransitive(),
readConditional(),
readNested(),
readNamespace('lang'),
readIndependent(),
readAlias(),
readDynamicImport(),
readRequire(),
readArguments(true),
foo(),
bar(),
readCycle().then((value) => `cycle:${value}`),
readLookalike(),
])
const component = await readComponent()
const client = await readClient()
return (
<p>
{values.join(' ')} {component} {client}
</p>
)
}
import { language } from './root-reexport'
export async function readAlias() {
'use cache'
return language()
}
export async function readArguments(enabled: boolean) {
'use cache'
const value = enabled ? 'enabled' : 'disabled'
return value
}
import { ClientView } from './client-view'
export async function readClient() {
'use cache'
return <ClientView />
}
import { CachedView } from './cached-view'
export async function readComponent() {
'use cache'
return <CachedView />
}
import { lang } from 'next/root-params'
export async function readConditional() {
'use cache'
if (process.env.__ROOT_PARAM_METADATA_TEST_BRANCH__) {
return lang()
}
return 'constant'
}
import { readCycleLanguage } from './cycle-a'
export async function readCycle() {
'use cache'
return readCycleLanguage(2)
}
import { lang } from 'next/root-params'
export async function readDirect() {
'use cache'
return lang()
}
export async function readDynamicImport() {
'use cache'
await import('./root-helper')
return 'constant'
}
export async function readIndependent() {
'use cache'
return 'constant'
}
// The imported user file has the same relative path as a generated getter. The
// collector must distinguish them by filesystem identity.
import { lang } from '../../../root-params/lang'
export async function readLookalike() {
'use cache'
return lang()
}
'use cache'
import { lang } from 'next/root-params'
export async function foo() {
return 'foo'
}
export async function bar() {
return lang()
}
import * as root from 'next/root-params'
export async function readNamespace(name: 'lang' | 'countryCode') {
'use cache'
return root[name]()
}
import { readDirect } from './read-direct'
export async function readNested() {
'use cache'
return readDirect()
}
export async function readRequire() {
'use cache'
require('./root-helper')
return 'constant'
}
import { getCountryCode } from './root-helper'
export async function readTransitive() {
'use cache'
return getCountryCode()
}
import { countryCode } from 'next/root-params'
export const getCountryCode = async () => countryCode()
'use server'
import { lang } from 'next/root-params'
export async function readRootLanguage() {
return lang()
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
useCacheStaticRootParamTracking: Boolean(process.env.TURBOPACK),
},
}
export default nextConfig
export function lang() {
return 'local-language'
}
import { nextTestSetup } from 'e2e-utils'
type RootParamDependencies = readonly string[] | undefined
describe('use-cache-root-param-metadata', () => {
const { next, isNextDev, isTurbopack } = nextTestSetup({ files: __dirname })
// Manifest inspection requires access to local build output.
// @force-gate !deploy
it('emits root param dependencies only in Turbopack production', async () => {
if (isNextDev) {
await next.render('/en/us')
}
const manifest = await next.readJSON(
`${next.distDir}/server/server-reference-manifest.json`
)
const entries = Object.values<any>(manifest.node)
expect(entries.length).toBeGreaterThan(0)
if (isNextDev || !isTurbopack) {
for (const entry of entries) {
for (const worker of Object.values<any>(entry.workers)) {
expect(worker.rootParamDependencies).toBeUndefined()
}
}
return
}
const matchingEntries = (name: string) => {
const matching = entries.filter((entry) =>
['.ts', '.tsx'].some((extension) =>
entry.filename.endsWith(`/${name}${extension}`)
)
)
expect(matching.length).toBeGreaterThan(0)
return matching
}
const expectDependencies = (
name: string,
expected: RootParamDependencies
) => {
for (const entry of matchingEntries(name)) {
const workers = Object.values<any>(entry.workers)
expect(workers.length).toBeGreaterThan(0)
for (const worker of workers) {
expect(worker.durability).toBeUndefined()
expect({ name, dependencies: worker.rootParamDependencies }).toEqual({
name,
dependencies: expected,
})
}
}
}
const languageCases = [
'read-direct',
'read-conditional',
'read-nested',
'read-alias',
'read-component',
'read-cycle',
'read-module',
]
for (const name of languageCases) {
expectDependencies(name, ['lang'])
}
for (const name of [
'read-transitive',
'read-dynamic-import',
'read-require',
]) {
expectDependencies(name, ['countryCode'])
}
expectDependencies('read-namespace', ['countryCode', 'lang'])
expect(matchingEntries('read-module')).toHaveLength(2)
expect(Object.keys(matchingEntries('read-direct')[0].workers)).toEqual(
expect.arrayContaining([
'app/[lang]/[countryCode]/page',
'app/[lang]/[countryCode]/other/page',
])
)
const emptyCases = [
'read-independent',
'read-arguments',
'read-lookalike',
'read-client',
]
for (const name of emptyCases) {
expectDependencies(name, [])
}
expectDependencies('root-reader', undefined)
})
it('renders the graph fixtures', async () => {
const $ = await next.render$('/en/us')
expect($('body').text()).toContain('enabled')
expect($('body').text()).toContain('cycle:en')
expect($('body').text()).toContain('foo')
expect($('span').text()).toBe('en')
expect($('button').text()).toBe('client')
})
})
...@@ -5,6 +5,7 @@ const nextConfig = { ...@@ -5,6 +5,7 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
supportsImmutableAssets: true, supportsImmutableAssets: true,
experimental: { experimental: {
useCacheStaticRootParamTracking: true,
durableUseCacheEntries: true, durableUseCacheEntries: true,
runtimeServerDeploymentId: true, runtimeServerDeploymentId: true,
}, },
......
...@@ -5,6 +5,7 @@ const nextConfig = { ...@@ -5,6 +5,7 @@ const nextConfig = {
cacheComponents: true, cacheComponents: true,
supportsImmutableAssets: true, supportsImmutableAssets: true,
experimental: { experimental: {
useCacheStaticRootParamTracking: true,
durableUseCacheEntries: true, durableUseCacheEntries: true,
runtimeServerDeploymentId: true, runtimeServerDeploymentId: true,
}, },
......
...@@ -9,6 +9,7 @@ async function getCodeHashes( ...@@ -9,6 +9,7 @@ async function getCodeHashes(
id: string id: string
page: string page: string
codeHash?: string codeHash?: string
rootParamDependencies?: readonly string[]
runtimeEnvVarsRead?: string[] runtimeEnvVarsRead?: string[]
runtimeEnvVarsExistence?: string[] runtimeEnvVarsExistence?: string[]
}[] }[]
...@@ -21,6 +22,7 @@ async function getCodeHashes( ...@@ -21,6 +22,7 @@ async function getCodeHashes(
id: string id: string
page: string page: string
codeHash?: string codeHash?: string
rootParamDependencies?: readonly string[]
runtimeEnvVarsRead?: string[] runtimeEnvVarsRead?: string[]
runtimeEnvVarsExistence?: string[] runtimeEnvVarsExistence?: string[]
}[] = [] }[] = []
...@@ -31,6 +33,7 @@ async function getCodeHashes( ...@@ -31,6 +33,7 @@ async function getCodeHashes(
id: actionId, id: actionId,
page: workerKey, page: workerKey,
codeHash: worker?.durability?.codeHash, codeHash: worker?.durability?.codeHash,
rootParamDependencies: worker.rootParamDependencies,
runtimeEnvVarsRead: worker?.durability?.runtimeEnvVarsRead, runtimeEnvVarsRead: worker?.durability?.runtimeEnvVarsRead,
runtimeEnvVarsExistence: worker?.durability?.runtimeEnvVarsExistence, runtimeEnvVarsExistence: worker?.durability?.runtimeEnvVarsExistence,
}) })
...@@ -62,6 +65,24 @@ async function getCodeHashes( ...@@ -62,6 +65,24 @@ async function getCodeHashes(
`) `)
}) })
it('emits root dependencies alongside durability', async () => {
const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json'
)
let cacheWorkers = 0
for (const entry of Object.values<any>(manifest.node)) {
for (const worker of Object.values<any>(entry.workers)) {
if (worker.durability) {
cacheWorkers++
expect(worker.rootParamDependencies).toBeDefined()
} else {
expect(worker.rootParamDependencies).toBeUndefined()
}
}
}
expect(cacheWorkers).toBeGreaterThan(0)
})
it('lists non-inlined runtime env vars', async () => { it('lists non-inlined runtime env vars', async () => {
const data = await getCodeHashes(next) const data = await getCodeHashes(next)
expect( expect(
...@@ -153,6 +174,7 @@ async function getCodeHashes( ...@@ -153,6 +174,7 @@ async function getCodeHashes(
const before = await getCodeHashes(next, ['app/[lang]/page']) const before = await getCodeHashes(next, ['app/[lang]/page'])
expect(before).toHaveLength(1) expect(before).toHaveLength(1)
expect(before[0].codeHash).toEqual(expect.any(String)) expect(before[0].codeHash).toEqual(expect.any(String))
expect(before[0].rootParamDependencies).toEqual(['lang'])
await next.patchFile( await next.patchFile(
'app/extra/[region]/layout.jsx', 'app/extra/[region]/layout.jsx',
...@@ -176,6 +198,7 @@ export function generateStaticParams() { ...@@ -176,6 +198,7 @@ export function generateStaticParams() {
const after = await getCodeHashes(next, ['app/[lang]/page']) const after = await getCodeHashes(next, ['app/[lang]/page'])
expect(after).toHaveLength(1) expect(after).toHaveLength(1)
expect(after[0].codeHash).toBe(before[0].codeHash) expect(after[0].codeHash).toBe(before[0].codeHash)
expect(after[0].rootParamDependencies).toEqual(['lang'])
} }
) )
} }
......
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [
{ lang: 'en', countryCode: 'us' },
{ lang: 'fr', countryCode: 'ca' },
]
}
import { readValue } from './read-value'
export default async function Page() {
return <p>{await readValue()}</p>
}
import { getValue } from './helper'
export async function readValue() {
'use cache'
return getValue()
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
useCacheStaticRootParamTracking: true,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
// @force-gate turbopack
describe('use-cache-root-param-metadata-rebuild', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
async function getWorker() {
const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json'
)
const entry = Object.values<any>(manifest.node).find((entry) =>
entry.filename.endsWith('read-value.ts')
)
expect(entry).toBeDefined()
const workers = Object.values<any>(entry.workers)
expect(workers).toHaveLength(1)
return workers[0]
}
async function getDependencies() {
return (await getWorker()).rootParamDependencies as
| readonly string[]
| undefined
}
it('omits root param dependencies by default', async () => {
await next.patchFile(
'next.config.ts',
`export default { cacheComponents: true }`,
async () => {
expect((await next.build()).exitCode).toBe(0)
expect(await getDependencies()).toBeUndefined()
}
)
})
it('updates transitive root param dependencies after a rebuild', async () => {
expect((await next.build()).exitCode).toBe(0)
expect(await getDependencies()).toEqual([])
await next.patchFile(
'app/[lang]/[countryCode]/helper.ts',
`import { lang } from 'next/root-params'
export async function getValue() {
return lang()
}
`,
async () => {
expect((await next.build()).exitCode).toBe(0)
expect(await getDependencies()).toEqual(['lang'])
await next.patchFile(
'app/[lang]/[countryCode]/helper.ts',
`import { countryCode } from 'next/root-params'
export async function getValue() {
return countryCode()
}
`
)
expect((await next.build()).exitCode).toBe(0)
expect(await getDependencies()).toEqual(['countryCode'])
}
)
})
it('collects root param dependencies in debug-prerender builds', async () => {
await next.patchFile(
'app/[lang]/[countryCode]/helper.ts',
`import { lang } from 'next/root-params'
export async function getValue() {
return lang()
}
`,
async () => {
expect(
(await next.build({ args: ['--debug-prerender'] })).exitCode
).toBe(0)
expect(await getDependencies()).toEqual(['lang'])
}
)
})
it('can disable root param collection independently of durability', async () => {
await next.patchFile(
'app/[lang]/[countryCode]/helper.ts',
`import { lang } from 'next/root-params'
export async function getValue() {
return (await lang()) + ':' + process.env.ROOT_PARAM_METADATA_TEST_VALUE
}
`,
async () => {
await next.patchFile(
'next.config.ts',
`export default {
cacheComponents: true,
experimental: {
useCacheStaticRootParamTracking: false,
durableUseCacheEntries: true,
},
}
`,
async () => {
expect((await next.build()).exitCode).toBe(0)
const worker = await getWorker()
expect(worker.rootParamDependencies).toBeUndefined()
expect(worker.durability.codeHash).toEqual(expect.any(String))
expect(worker.durability.runtimeEnvVarsRead).toContain(
'ROOT_PARAM_METADATA_TEST_VALUE'
)
}
)
}
)
})
})
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