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

Prepare `'use cache'` for static root-param tracking (#99239)

Static root-param tracking for `'use cache'` needs to distinguish which
getters a cached module imports. The existing generated module contains
every getter, so module-level dependency collection includes unrelated
root params.

`next/root-params` now re-exports each getter from a separate virtual
module. The generated `next/root-params` module declares that it has no
side effects, so Turbopack resolves named imports without including
unrelated getter modules. Runtime root-param tracking remains unchanged.

The split also keeps code hashes stable when unrelated root params are
added. The regression test checks this dependency isolation through the
existing code-hash manifest.
parent 79647071
use std::iter; use std::iter;
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow, ensure};
use either::Either; use either::Either;
use indoc::formatdoc; use indoc::formatdoc;
use itertools::Itertools; use itertools::Itertools;
...@@ -28,17 +28,19 @@ use crate::{ ...@@ -28,17 +28,19 @@ use crate::{
next_shared::resolve::InvalidImportModuleIssue, next_shared::resolve::InvalidImportModuleIssue,
}; };
// The resolver extracts queries from module subpaths.
const ROOT_PARAM_GETTER_MODULE: &str = "private-next-root-params/getter";
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>,
collected_root_params: Option<Vc<CollectedRootParams>>, collected_root_params: Option<Vc<CollectedRootParams>>,
) -> Result<()> { ) -> Result<()> {
import_map.insert_exact_alias( let mapping = get_next_root_params_mapping(EitherTaskInput(ty), collected_root_params)
"next/root-params", .to_resolved()
get_next_root_params_mapping(EitherTaskInput(ty), collected_root_params) .await?;
.to_resolved() import_map.insert_exact_alias("next/root-params", mapping);
.await?, import_map.insert_exact_alias(ROOT_PARAM_GETTER_MODULE, mapping);
);
Ok(()) Ok(())
} }
...@@ -84,7 +86,10 @@ impl NextRootParamsMapper { ...@@ -84,7 +86,10 @@ impl NextRootParamsMapper {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn import_map_result(self: Vc<Self>) -> Result<Vc<ImportMapResult>> { async fn import_map_result(
self: Vc<Self>,
param_name: Option<RcStr>,
) -> Result<Vc<ImportMapResult>> {
let this = self.await?; let this = self.await?;
Ok(match &this.context_type { Ok(match &this.context_type {
Either::Left(server_ty) => match &server_ty { Either::Left(server_ty) => match &server_ty {
...@@ -96,7 +101,7 @@ impl NextRootParamsMapper { ...@@ -96,7 +101,7 @@ impl NextRootParamsMapper {
server_ty.clone() server_ty.clone()
) )
})?; })?;
Self::valid_import_map_result(collected_root_params) Self::valid_import_map_result(collected_root_params, param_name)
} }
ServerContextType::PagesApi { .. } ServerContextType::PagesApi { .. }
| ServerContextType::Instrumentation { .. } | ServerContextType::Instrumentation { .. }
...@@ -134,35 +139,44 @@ impl NextRootParamsMapper { ...@@ -134,35 +139,44 @@ impl NextRootParamsMapper {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn valid_import_map_result( async fn valid_import_map_result(
collected_root_params: ResolvedVc<CollectedRootParams>, collected_root_params: ResolvedVc<CollectedRootParams>,
param_name: Option<RcStr>,
) -> Result<Vc<ImportMapResult>> { ) -> Result<Vc<ImportMapResult>> {
let collected_root_params = collected_root_params.await?; let collected_root_params = collected_root_params.await?;
// Generate a virtual 'next/root-params' module based on the root params we collected. let (filename, module_content) = if let Some(param_name) = param_name {
let module_content = ensure!(
// If there's no root params, export nothing. collected_root_params.contains(&param_name),
if collected_root_params.is_empty() { "Unknown root parameter in generated getter request: {param_name}"
"export {}".to_string() );
} else { (
iter::once(formatdoc!( format!("root-params/{param_name}.js").into(),
formatdoc!(
r#" r#"
import {{ getRootParam }} from 'next/dist/server/request/root-params'; import {{ getRootParam }} from 'next/dist/server/request/root-params';
export function {param_name}() {{
return getRootParam('{param_name}');
}}
"#, "#,
)) ),
.chain(collected_root_params.iter().map(|param_name| { )
formatdoc!( } else {
r#" // The generated `next/root-params` module only re-exports getters.
export function {PARAM_NAME}() {{ // The side-effect-free directive lets Turbopack resolve named
return getRootParam('{PARAM_NAME}'); // imports without including unrelated getter modules.
}} let module_content =
"#, iter::once("'use turbopack: no side effects';\nexport {};".to_string())
PARAM_NAME = param_name, .chain(collected_root_params.iter().map(|param_name| {
) format!(
})) "export {{ {param_name} }} from \
.join("\n") '{ROOT_PARAM_GETTER_MODULE}?{param_name}';"
}; )
}))
.join("\n");
("root-params.js".into(), module_content)
};
let virtual_source = VirtualSource::new( let virtual_source = VirtualSource::new(
next_js_file_path("root-params.js".into()).owned().await?, next_js_file_path(filename).owned().await?,
AssetContent::file(FileContent::Content(module_content.into()).cell()), AssetContent::file(FileContent::Content(module_content.into()).cell()),
) )
.to_resolved() .to_resolved()
...@@ -218,10 +232,25 @@ impl ImportMappingReplacement for NextRootParamsMapper { ...@@ -218,10 +232,25 @@ impl ImportMappingReplacement for NextRootParamsMapper {
async fn result( async fn result(
self: Vc<Self>, self: Vc<Self>,
_lookup_path: FileSystemPath, _lookup_path: FileSystemPath,
_request: Vc<Request>, request: Vc<Request>,
) -> Vc<ImportMapResult> { ) -> Result<Vc<ImportMapResult>> {
// Delegate to an inner function that only depends on `self` -- let request = request.await?;
// we want to return the same cell regardless of the arguments we received here. let param_name = match &*request {
self.import_map_result() Request::Module { query, .. }
if request.request().as_deref() == Some(ROOT_PARAM_GETTER_MODULE) =>
{
Some(
query
.strip_prefix('?')
.ok_or_else(|| {
anyhow!("Missing root parameter in generated getter request")
})?
.into(),
)
}
_ => None,
};
// Share generated sources across importers with the same root name.
Ok(self.import_map_result(param_name))
} }
} }
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
import { readLanguage } from './read-language'
export default async function Page() {
return <p>{await readLanguage()}</p>
}
import { lang } from 'next/root-params'
export async function readLanguage() {
'use cache'
return lang()
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
supportsImmutableAssets: true,
experimental: {
durableUseCacheEntries: true,
runtimeServerDeploymentId: true,
},
}
module.exports = nextConfig
import { nextTestSetup, type NextInstance } from 'e2e-utils' import { nextTestSetup, type NextInstance } from 'e2e-utils'
import { join } from 'path'
async function getCodeHashes( async function getCodeHashes(
next: NextInstance, next: NextInstance,
...@@ -141,6 +142,69 @@ async function getCodeHashes( ...@@ -141,6 +142,69 @@ async function getCodeHashes(
}) })
}) })
describe('root params', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures/root-params'),
skipStart: true,
})
async function expectStableRootParamHash(args: string[] = []) {
expect((await next.build({ args })).exitCode).toBe(0)
const before = await getCodeHashes(next, ['app/[lang]/page'])
expect(before).toHaveLength(1)
expect(before[0].codeHash).toEqual(expect.any(String))
await next.patchFile(
'app/extra/[region]/layout.jsx',
`export default function Layout({ children }) {
return <html><body>{children}</body></html>
}
export function generateStaticParams() {
return [{ region: 'eu' }]
}
`,
async () => {
await next.patchFile(
'app/extra/[region]/page.jsx',
`export default function Page() {
return <p>extra root</p>
}
`,
async () => {
expect((await next.build({ args })).exitCode).toBe(0)
const after = await getCodeHashes(next, ['app/[lang]/page'])
expect(after).toHaveLength(1)
expect(after[0].codeHash).toBe(before[0].codeHash)
}
)
}
)
}
it('keeps codeHash stable when an unrelated root param is added', async () => {
await expectStableRootParamHash()
})
it('keeps root-param codeHash stable in debug-prerender builds', async () => {
await expectStableRootParamHash(['--debug-prerender'])
})
it('keeps root-param codeHash stable without import/export pruning', async () => {
await next.patchFile(
'next.config.js',
(config) =>
config.replace(
'experimental: {',
'experimental: { turbopackRemoveUnusedImports: false, turbopackRemoveUnusedExports: false,'
),
async () => {
await expectStableRootParamHash()
}
)
})
})
describe('invalidation', () => { describe('invalidation', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
......
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