Unverified Commit 5eec1d9d authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: preload _app's next/dynamic chunks with _app's own availability (#100091)

## Summary

Fixes a Turbopack dev regression from #98823 in the Pages Router. When
`pages/_app` renders a `next/dynamic` component, a page's SSR HTML can
preload a chunk that 404s. This was reported in #99789, with a repro at
[dcheng1290/next-loadable-404](https://github.com/dcheng1290/next-loadable-404).
The component still renders, but the browser logs a failed request. This
PR also makes Turbopack production preload `_app`'s `next/dynamic`
chunks on every page, matching dev and webpack.

**Why:** #98823 chains the `/_app` and page client module graphs in
development. `next/dynamic` imports are collected from every layer of
that graph, so each page's `react-loadable-manifest` now also lists
`/_app`'s dynamic imports, but chunked with the **page's** availability.
At runtime those imports are loaded by `/_app`'s own async loader, which
is chunked with `/_app`'s graph and availability. The preloaded chunk
names therefore don't match the chunks that are emitted and requested.

In production, `/_app`'s dynamic imports were only listed in
`server/pages/_app/react-loadable-manifest.json`, which page renders
don't read, so they were never preloaded.

**How:** a Pages-only helper in `crates/next-api/src/pages.rs`
(`page_next_dynamic_chunks`), used for every page except `/_app`:
- it chunks `/_app`'s dynamic imports with the `/_app` endpoint's client
module graph and client availability, which is exactly what `/_app`
itself lists;
- it chunks the page's own imports as before, with `/_app`'s filtered
out (in per-page/dev mode they are reachable from the page's chained
graph);
- it merges both into the page's manifest.

The generic collector in `module_graph.rs` is untouched, and so is App
Router.

This should be backported to `releases/lts/active` together with #98823
(backport PR #100008).

## Verification

- New e2e suite `test/e2e/pages-app-next-dynamic-preload`, based on the
repro. It checks that:
- every `/_next/static` asset in the SSR HTML of `/` and `/other`
returns 200;
  - the `_app` dynamic component renders;
  - both pages preload the same non-empty set of `_app` dynamic chunks.
- The suite fails without the fix in Turbopack dev (a 404 asset). With
the fix it passes in Turbopack dev and start and in webpack dev and
start, using a locally built native binary.
- Existing suites pass in Turbopack dev and start: `next-dynamic`,
`next-dynamic-css`, `next-dynamic-lazy-compilation`,
`pages-app-availability-boundary`, `app-document-import-order` (#99910),
`app-dir/dynamic` and `app-dir/dynamic-import`.
- Manual check, using the repro with a headless browser in dev and in
production:
  - there are no failed requests or console errors on either page;
- production manifests list `_app`'s entry with the chunk `_app` itself
uses.
- `cargo clippy -p next-api` and `cargo fmt --check` pass.

<!-- NEXT_JS_LLM -->


<!-- fleet 652922cb-dc34-493d-9be5-c241a5164cad -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent d735dbab
...@@ -29,10 +29,13 @@ use next_core::{ ...@@ -29,10 +29,13 @@ use next_core::{
segment_config::ParseSegmentMode, segment_config::ParseSegmentMode,
util::{NextRuntime, get_asset_prefix_from_pathname, pages_function_name}, util::{NextRuntime, get_asset_prefix_from_pathname, pages_function_name},
}; };
use rustc_hash::FxHashSet;
use smallvec::smallvec; use smallvec::smallvec;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, FxIndexMap, ResolvedVc, ValueToString, Vc, fxindexmap, fxindexset}; use turbo_tasks::{
Completion, FxIndexMap, ReadRef, ResolvedVc, ValueToString, Vc, fxindexmap, fxindexset,
};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem, self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
}; };
...@@ -72,7 +75,9 @@ use crate::{ ...@@ -72,7 +75,9 @@ use crate::{
}, },
font::FontManifest, font::FontManifest,
loadable_manifest::create_react_loadable_manifest, loadable_manifest::create_react_loadable_manifest,
module_graph::{NextDynamicGraphs, validate_pages_css_imports}, module_graph::{
DynamicImportEntriesWithImporter, NextDynamicGraphs, validate_pages_css_imports,
},
nft::{EndpointTraceResult, trace_endpoint}, nft::{EndpointTraceResult, trace_endpoint},
nft_json::NftJsonAsset, nft_json::NftJsonAsset,
paths::{ paths::{
...@@ -653,6 +658,76 @@ async fn client_entry_modules( ...@@ -653,6 +658,76 @@ async fn client_entry_modules(
.collect()) .collect())
} }
/// The chunks to preload for the `next/dynamic` imports of a page's client graph, including the
/// ones of `/_app` (which is rendered as part of every page).
async fn page_next_dynamic_chunks(
endpoint: Vc<PageEndpoint>,
next_dynamic_imports: ReadRef<DynamicImportEntriesWithImporter>,
client_availability_info: AvailabilityInfo,
) -> Result<ResolvedVc<DynamicImportedChunks>> {
let this = endpoint.await?;
let project = this.pages_project.project();
let client_chunking_context = project.client_chunking_context();
if this.pathname == "/_app" {
return collect_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await;
}
// `/_app`'s `next/dynamic` imports are loaded by `/_app`'s async loaders, which are chunked
// with `/_app`'s graph and availability, so preload them with the chunks `/_app` itself
// lists. Chunked with the page's availability, they would name chunks that don't match what
// those loaders request (and that may not be emitted at all).
// With a per-page module graph, a page's client graph is chained after `/_app`'s (see
// `client_module_graph`), so `next_dynamic_imports` also contains `/_app`'s imports: chunk
// only the page's own imports with the page's graph and availability. With a whole-app graph
// they aren't reachable from the page, so `/_app`'s imports are only added here.
let per_page_module_graph = *project.per_page_module_graph().await?;
let app_endpoint = this.pages_project.app_page_endpoint();
let app_module_graph = app_endpoint.client_module_graph();
let app_next_dynamic_imports = NextDynamicGraphs::new(app_module_graph, per_page_module_graph)
.get_next_dynamic_imports_for_endpoint(app_endpoint.client_module())
.await?;
let app_dynamic_entries = app_next_dynamic_imports
.iter()
.map(|(dynamic_entry, _)| *dynamic_entry)
.collect::<FxHashSet<_>>();
let page_next_dynamic_imports = Vc::<DynamicImportEntriesWithImporter>::cell(
next_dynamic_imports
.iter()
.filter(|(dynamic_entry, _)| !app_dynamic_entries.contains(dynamic_entry))
.cloned()
.collect(),
)
.await?;
let page_chunks = collect_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
page_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await?;
let app_chunks = collect_next_dynamic_chunks(
app_module_graph,
client_chunking_context,
app_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(
app_endpoint.client_chunk_group().await?.availability_info,
),
)
.await?;
let mut chunks = (*app_chunks.await?).clone();
chunks.extend(page_chunks.await?.iter().map(|(k, v)| (*k, *v)));
Ok(ResolvedVc::cell(chunks))
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl PageEndpoint { impl PageEndpoint {
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -1056,13 +1131,8 @@ impl PageEndpoint { ...@@ -1056,13 +1131,8 @@ impl PageEndpoint {
client_availability_info, client_availability_info,
)) = next_dynamic_imports )) = next_dynamic_imports
{ {
collect_next_dynamic_chunks( page_next_dynamic_chunks(self, next_dynamic_imports, client_availability_info)
self.client_module_graph(), .await?
project.client_chunking_context(),
next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await?
} else { } else {
DynamicImportedChunks::default().resolved_cell() DynamicImportedChunks::default().resolved_cell()
}; };
......
export const appShared = (s: string) => `app-shared:${s}`
export const lazyOnly = (s: string) => `lazy-only-marker:${s}`
import { appShared } from './app-shared'
import { lazyOnly } from './lazy-only'
import { pageShared } from './page-shared'
export function Lazy() {
return (
<p id="lazy">
{[appShared('lazy'), pageShared('lazy'), lazyOnly('lazy')].join(',')}
</p>
)
}
export const pageShared = (s: string) => `page-shared:${s}`
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// `_app` renders a `next/dynamic` component that shares a module with `/` (but not with `/other`).
// The component is loaded by `_app`'s own async loader on every page, so every page has to preload
// the same chunks, the ones that loader requests, regardless of what the page already loaded.
describe('pages-app-next-dynamic-preload', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const pages = ['/', '/other']
// The `/_next/static` scripts and stylesheets (including preloads) in the SSR HTML, with their
// query strings (e.g. the deployment id).
async function getReferencedAssets(pathname: string) {
const $ = await next.render$(pathname)
const urls = $('script[src], link[href]')
.toArray()
.map((el) => $(el).attr('src') ?? $(el).attr('href') ?? '')
.filter((url) => /^\/_next\/static\/.+\.(?:js|css)(?:\?|$)/.test(url))
return [...new Set(urls)]
}
it.each(pages)(
'serves every asset referenced in the HTML of %s',
async (pathname) => {
const assets = await getReferencedAssets(pathname)
expect(assets.length).toBeGreaterThan(0)
const failed: string[] = []
for (const asset of assets) {
const res = await next.fetch(asset)
if (res.status !== 200) failed.push(`${res.status} ${asset}`)
}
expect(failed).toEqual([])
}
)
it.each(pages)(
'renders the _app next/dynamic component on %s',
async (pathname) => {
const browser = await next.browser(pathname)
await retry(async () => {
expect(await browser.elementByCss('#lazy').text()).toBe(
'app-shared:lazy,page-shared:lazy,lazy-only-marker:lazy'
)
})
expect(await browser.elementByCss('#app').text()).toBe('app-shared:app')
}
)
it('preloads the same _app next/dynamic chunks on every page', async () => {
const preloadedChunks: Record<string, string[]> = {}
for (const pathname of pages) {
const chunks: string[] = []
for (const asset of await getReferencedAssets(pathname)) {
if (!/\.js(?:\?|$)/.test(asset)) continue
const res = await next.fetch(asset)
expect({ asset, status: res.status }).toEqual({ asset, status: 200 })
if ((await res.text()).includes('lazy-only-marker')) {
chunks.push(asset.split('?')[0])
}
}
preloadedChunks[pathname] = chunks.sort()
}
expect(preloadedChunks['/']).not.toEqual([])
expect(preloadedChunks['/other']).toEqual(preloadedChunks['/'])
})
})
import type { AppProps } from 'next/app'
import dynamic from 'next/dynamic'
import { appShared } from '../components/app-shared'
const Lazy = dynamic(() => import('../components/lazy').then((m) => m.Lazy))
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<p id="app">{appShared('app')}</p>
<Lazy />
<Component {...pageProps} />
</>
)
}
// Shared with `components/lazy`, which `_app` loads with `next/dynamic`: this page has already
// loaded it when `_app`'s dynamic import runs, `/other` hasn't.
import { pageShared } from '../components/page-shared'
export default function Page() {
return <p id="page">{pageShared('index')}</p>
}
export default function Page() {
return <p id="page">other</p>
}
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