Commit 58f4b029 authored by Matt Mastracci's avatar Matt Mastracci Committed by Matt Mastracci

Add boundary_info() to Module trait for type-independent boundary detection

Replace `try_downcast_type` calls for NextServerComponentModule,
NextServerUtilityModule, and NextDynamicEntryModule with a new
`boundary_info()` method on the Module trait. This decouples boundary
detection from concrete wrapper module types, preparing for their
eventual removal.

Changes:
- Add `BoundaryInfo` struct and `OptionBoundaryInfo` to turbopack-core
- Add `boundary_info()` default method to `Module` trait (returns None)
- Add boundary type constants in next-core (server-component,
  server-utility, dynamic-entry)
- Override `boundary_info()` on the three wrapper modules
- Switch detection in client_references.rs, visit_client_reference.rs,
  dynamic_imports.rs, and module_graph.rs to use boundary_info() with
  validation downcasts
- Add ServerUtility variant to ClientManifestEntryType for sync callback
  detection in module_graph.rs
parent 797eb7fe
use anyhow::Result; use anyhow::Result;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use next_core::{ use next_core::{
boundary_types::{boundary_type_server_component, boundary_type_server_utility},
next_client_reference::{CssClientReferenceModule, EcmascriptClientReferenceModule}, next_client_reference::{CssClientReferenceModule, EcmascriptClientReferenceModule},
next_server_component::server_component_module::NextServerComponentModule, next_server_component::server_component_module::NextServerComponentModule,
next_server_utility::server_utility_module::NextServerUtilityModule,
}; };
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use turbo_tasks::{ use turbo_tasks::{
...@@ -21,6 +23,7 @@ pub enum ClientManifestEntryType { ...@@ -21,6 +23,7 @@ pub enum ClientManifestEntryType {
}, },
CssClientReference(ResolvedVc<Box<dyn CssChunkPlaceable>>), CssClientReference(ResolvedVc<Box<dyn CssChunkPlaceable>>),
ServerComponent(ResolvedVc<NextServerComponentModule>), ServerComponent(ResolvedVc<NextServerComponentModule>),
ServerUtility(ResolvedVc<NextServerUtilityModule>),
} }
/// Tracks information about all the css and js client references in the graph. /// Tracks information about all the css and js client references in the graph.
...@@ -54,13 +57,18 @@ pub async fn map_client_references( ...@@ -54,13 +57,18 @@ pub async fn map_client_references(
client_reference_module.await?.client_module, client_reference_module.await?.client_module,
), ),
))) )))
} else if let Some(server_component) = } else if let Some(boundary) = &*module.boundary_info().await? {
ResolvedVc::try_downcast_type::<NextServerComponentModule>(module) if boundary.boundary_type == boundary_type_server_component() {
{ let sc = ResolvedVc::try_downcast_type::<NextServerComponentModule>(module)
Ok(Some(( .expect("server-component boundary must be NextServerComponentModule");
module, Ok(Some((module, ClientManifestEntryType::ServerComponent(sc))))
ClientManifestEntryType::ServerComponent(server_component), } else if boundary.boundary_type == boundary_type_server_utility() {
))) let su = ResolvedVc::try_downcast_type::<NextServerUtilityModule>(module)
.expect("server-utility boundary must be NextServerUtilityModule");
Ok(Some((module, ClientManifestEntryType::ServerUtility(su))))
} else {
Ok(None)
}
} else { } else {
Ok(None) Ok(None)
} }
......
...@@ -22,8 +22,8 @@ ...@@ -22,8 +22,8 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use next_core::{ use next_core::{
next_app::ClientReferencesChunks, next_client_reference::EcmascriptClientReferenceModule, boundary_types::boundary_type_dynamic_entry, next_app::ClientReferencesChunks,
next_dynamic::NextDynamicEntryModule, next_client_reference::EcmascriptClientReferenceModule, next_dynamic::NextDynamicEntryModule,
}; };
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, NonLocalValue, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc, FxIndexMap, NonLocalValue, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc,
...@@ -130,9 +130,12 @@ pub async fn map_next_dynamic( ...@@ -130,9 +130,12 @@ pub async fn map_next_dynamic(
.layer .layer
.as_ref() .as_ref()
.is_some_and(|layer| layer.name() == "app-client" || layer.name() == "client") .is_some_and(|layer| layer.name() == "app-client" || layer.name() == "client")
&& let Some(dynamic_entry_module) = && let Some(boundary) = &*module.boundary_info().await?
ResolvedVc::try_downcast_type::<NextDynamicEntryModule>(module) && boundary.boundary_type == boundary_type_dynamic_entry()
{ {
let dynamic_entry_module =
ResolvedVc::try_downcast_type::<NextDynamicEntryModule>(module)
.expect("dynamic-entry boundary must be NextDynamicEntryModule");
return Ok(Some(( return Ok(Some((
module, module,
DynamicImportEntriesMapType::DynamicEntry(dynamic_entry_module), DynamicImportEntriesMapType::DynamicEntry(dynamic_entry_module),
......
...@@ -10,7 +10,6 @@ use next_core::{ ...@@ -10,7 +10,6 @@ use next_core::{
}, },
next_dynamic::NextDynamicEntryModule, next_dynamic::NextDynamicEntryModule,
next_manifests::ActionLayer, next_manifests::ActionLayer,
next_server_utility::server_utility_module::NextServerUtilityModule,
}; };
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use tracing::Instrument; use tracing::Instrument;
...@@ -578,18 +577,13 @@ impl ClientReferencesGraph { ...@@ -578,18 +577,13 @@ impl ClientReferencesGraph {
| ClientManifestEntryType::CssClientReference { .. } | ClientManifestEntryType::CssClientReference { .. }
| ClientManifestEntryType::ServerComponent { .. }, | ClientManifestEntryType::ServerComponent { .. },
) => GraphTraversalAction::Skip, ) => GraphTraversalAction::Skip,
None => GraphTraversalAction::Continue, // ServerUtility is NOT a traversal boundary — continue into its children
Some(ClientManifestEntryType::ServerUtility { .. }) | None => {
GraphTraversalAction::Continue
}
}) })
}, },
|node, _| { |node, _| {
if let Some(server_util_module) =
ResolvedVc::try_downcast_type::<NextServerUtilityModule>(node)
{
// Server utility used by the template, not a server component
server_utils.insert(server_util_module);
return Ok(());
}
let module_type = data.get(&node); let module_type = data.get(&node);
let ty = match module_type { let ty = match module_type {
...@@ -604,6 +598,10 @@ impl ClientReferencesGraph { ...@@ -604,6 +598,10 @@ impl ClientReferencesGraph {
server_components.insert(*sc); server_components.insert(*sc);
return Ok(()); return Ok(());
} }
Some(ClientManifestEntryType::ServerUtility(su)) => {
server_utils.insert(*su);
return Ok(());
}
None => { None => {
return Ok(()); return Ok(());
} }
...@@ -640,11 +638,6 @@ impl ClientReferencesGraph { ...@@ -640,11 +638,6 @@ impl ClientReferencesGraph {
}, },
|node, _| { |node, _| {
let module = node; let module = node;
if let Some(server_util_module) =
ResolvedVc::try_downcast_type::<NextServerUtilityModule>(module)
{
server_utils.insert(server_util_module);
}
let Some(module_type) = data.get(&module) else { let Some(module_type) = data.get(&module) else {
return Ok(()); return Ok(());
...@@ -661,6 +654,10 @@ impl ClientReferencesGraph { ...@@ -661,6 +654,10 @@ impl ClientReferencesGraph {
ClientManifestEntryType::ServerComponent(_) => { ClientManifestEntryType::ServerComponent(_) => {
return Ok(()); return Ok(());
} }
ClientManifestEntryType::ServerUtility(su) => {
server_utils.insert(*su);
return Ok(());
}
}; };
client_references.push(ClientReference { client_references.push(ClientReference {
......
use turbo_rcstr::{RcStr, rcstr};
pub fn boundary_type_server_component() -> RcStr {
rcstr!("server-component")
}
pub fn boundary_type_server_utility() -> RcStr {
rcstr!("server-utility")
}
pub fn boundary_type_dynamic_entry() -> RcStr {
rcstr!("dynamic-entry")
}
...@@ -8,6 +8,7 @@ mod app_page_loader_tree; ...@@ -8,6 +8,7 @@ mod app_page_loader_tree;
pub mod app_structure; pub mod app_structure;
mod base_loader_tree; mod base_loader_tree;
mod bootstrap; mod bootstrap;
pub mod boundary_types;
mod embed_js; mod embed_js;
mod emit; mod emit;
pub mod hmr_entry; pub mod hmr_entry;
......
...@@ -16,6 +16,7 @@ use turbopack_core::{ ...@@ -16,6 +16,7 @@ use turbopack_core::{
use turbopack_css::chunk::CssChunkPlaceable; use turbopack_css::chunk::CssChunkPlaceable;
use crate::{ use crate::{
boundary_types::{boundary_type_server_component, boundary_type_server_utility},
next_client_reference::{ next_client_reference::{
CssClientReferenceModule, CssClientReferenceModule,
ecmascript_client_reference::ecmascript_client_reference_module::EcmascriptClientReferenceModule, ecmascript_client_reference::ecmascript_client_reference_module::EcmascriptClientReferenceModule,
...@@ -202,40 +203,48 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -202,40 +203,48 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
return Ok((FindServerEntriesNode::ClientReference, ())); return Ok((FindServerEntriesNode::ClientReference, ()));
} }
if let Some(server_component_asset) = if let Some(boundary) = &*module.boundary_info().await? {
ResolvedVc::try_downcast_type::<NextServerComponentModule>(*module) if boundary.boundary_type == boundary_type_server_component() {
{ let sc =
return Ok(( ResolvedVc::try_downcast_type::<NextServerComponentModule>(*module)
FindServerEntriesNode::ServerComponentEntry( .expect(
server_component_asset, "server-component boundary must be \
if emit_spans { NextServerComponentModule",
// INVALIDATION: we don't need to invalidate when the span name );
// changes return Ok((
Some(server_component_asset.ident_string().untracked().await?) FindServerEntriesNode::ServerComponentEntry(
} else { sc,
None if emit_spans {
}, // INVALIDATION: we don't need to invalidate when the span
), // name changes
(), Some(sc.ident_string().untracked().await?)
)); } else {
} None
},
if let Some(server_util_module) = ),
ResolvedVc::try_downcast_type::<NextServerUtilityModule>(*module) (),
{ ));
return Ok(( }
FindServerEntriesNode::ServerUtilEntry( if boundary.boundary_type == boundary_type_server_utility() {
server_util_module, let su =
if emit_spans { ResolvedVc::try_downcast_type::<NextServerUtilityModule>(*module)
// INVALIDATION: we don't need to invalidate when the span name .expect(
// changes "server-utility boundary must be NextServerUtilityModule",
Some(module.ident_string().untracked().await?) );
} else { return Ok((
None FindServerEntriesNode::ServerUtilEntry(
}, su,
), if emit_spans {
(), // INVALIDATION: we don't need to invalidate when the span
)); // name changes
Some(module.ident_string().untracked().await?)
} else {
None
},
),
(),
));
}
} }
Ok(( Ok((
......
...@@ -3,6 +3,7 @@ use indoc::formatdoc; ...@@ -3,6 +3,7 @@ use indoc::formatdoc;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{ use turbopack_core::{
boundary::{BoundaryInfo, OptionBoundaryInfo},
chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt}, chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt},
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
...@@ -21,6 +22,8 @@ use turbopack_ecmascript::{ ...@@ -21,6 +22,8 @@ use turbopack_ecmascript::{
utils::StringifyJs, utils::StringifyJs,
}; };
use crate::boundary_types::boundary_type_dynamic_entry;
/// A [`NextDynamicEntryModule`] is a marker asset used to indicate which /// A [`NextDynamicEntryModule`] is a marker asset used to indicate which
/// dynamic assets should appear in the dynamic manifest. /// dynamic assets should appear in the dynamic manifest.
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -71,6 +74,11 @@ impl Module for NextDynamicEntryModule { ...@@ -71,6 +74,11 @@ impl Module for NextDynamicEntryModule {
// This just exports another import // This just exports another import
ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell() ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell()
} }
#[turbo_tasks::function]
fn boundary_info(self: Vc<Self>) -> Vc<OptionBoundaryInfo> {
Vc::cell(Some(BoundaryInfo::new(boundary_type_dynamic_entry())))
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -4,6 +4,7 @@ use turbo_rcstr::rcstr; ...@@ -4,6 +4,7 @@ use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
boundary::{BoundaryInfo, OptionBoundaryInfo},
chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt}, chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt},
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
...@@ -22,6 +23,7 @@ use turbopack_ecmascript::{ ...@@ -22,6 +23,7 @@ use turbopack_ecmascript::{
}; };
use super::server_component_reference::NextServerComponentModuleReference; use super::server_component_reference::NextServerComponentModuleReference;
use crate::boundary_types::boundary_type_server_component;
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextServerComponentModule { pub struct NextServerComponentModule {
...@@ -88,6 +90,14 @@ impl Module for NextServerComponentModule { ...@@ -88,6 +90,14 @@ impl Module for NextServerComponentModule {
// This just exports another import // This just exports another import
ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell() ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell()
} }
#[turbo_tasks::function]
fn boundary_info(&self) -> Vc<OptionBoundaryInfo> {
Vc::cell(Some(BoundaryInfo::with_source_path(
boundary_type_server_component(),
self.source_path.clone(),
)))
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -4,6 +4,7 @@ use turbo_rcstr::rcstr; ...@@ -4,6 +4,7 @@ use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
boundary::{BoundaryInfo, OptionBoundaryInfo},
chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt}, chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt},
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
...@@ -22,6 +23,7 @@ use turbopack_ecmascript::{ ...@@ -22,6 +23,7 @@ use turbopack_ecmascript::{
}; };
use super::server_utility_reference::NextServerUtilityModuleReference; use super::server_utility_reference::NextServerUtilityModuleReference;
use crate::boundary_types::boundary_type_server_utility;
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextServerUtilityModule { pub struct NextServerUtilityModule {
...@@ -69,6 +71,11 @@ impl Module for NextServerUtilityModule { ...@@ -69,6 +71,11 @@ impl Module for NextServerUtilityModule {
// This just exports another import // This just exports another import
ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell() ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell()
} }
#[turbo_tasks::function]
fn boundary_info(self: Vc<Self>) -> Vc<OptionBoundaryInfo> {
Vc::cell(Some(BoundaryInfo::new(boundary_type_server_utility())))
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
use turbo_rcstr::RcStr;
use turbo_tasks_fs::FileSystemPath;
/// Metadata describing a module boundary (e.g., server component, server utility, dynamic entry).
///
/// This allows detection of boundary types without downcasting to concrete module types,
/// decoupling the detection mechanism from the wrapper module implementation.
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug)]
pub struct BoundaryInfo {
/// The type of boundary (e.g., "server-component", "server-utility", "dynamic-entry").
pub boundary_type: RcStr,
/// Optional original source path before transformations (e.g., page.mdx before page.mdx.tsx).
pub source_path: Option<FileSystemPath>,
}
impl BoundaryInfo {
pub fn new(boundary_type: RcStr) -> Self {
BoundaryInfo {
boundary_type,
source_path: None,
}
}
pub fn with_source_path(boundary_type: RcStr, source_path: FileSystemPath) -> Self {
BoundaryInfo {
boundary_type,
source_path: Some(source_path),
}
}
}
#[turbo_tasks::value(transparent)]
pub struct OptionBoundaryInfo(Option<BoundaryInfo>);
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
#![feature(hash_set_entry)] #![feature(hash_set_entry)]
pub mod asset; pub mod asset;
pub mod boundary;
pub mod changed; pub mod changed;
pub mod chunk; pub mod chunk;
pub mod code_builder; pub mod code_builder;
......
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, TaskInput, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, TaskInput, ValueToString, Vc};
use crate::{ident::AssetIdent, reference::ModuleReferences, source::OptionSource}; use crate::{
boundary::OptionBoundaryInfo, ident::AssetIdent, reference::ModuleReferences,
source::OptionSource,
};
#[derive(Clone, Copy, Debug, TaskInput, Hash)] #[derive(Clone, Copy, Debug, TaskInput, Hash)]
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -67,6 +70,13 @@ pub trait Module { ...@@ -67,6 +70,13 @@ pub trait Module {
/// Returns true if the module is marked as side effect free in package.json or by other means. /// Returns true if the module is marked as side effect free in package.json or by other means.
#[turbo_tasks::function] #[turbo_tasks::function]
fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects>; fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects>;
/// Returns boundary metadata if this module represents a module boundary
/// (e.g., server component, server utility, dynamic entry). Returns `None` by default.
#[turbo_tasks::function]
fn boundary_info(self: Vc<Self>) -> Vc<OptionBoundaryInfo> {
Vc::cell(None)
}
} }
#[turbo_tasks::value_trait] #[turbo_tasks::value_trait]
......
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