Unverified Commit 4162a56b authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: refactor ServerActionManifestAsset to be lazy (#94377)

Previously, `AppEndpoint::output` computed the manifest content eagerly.
This change moves it to the emit phase.
parent d8426d0d
use std::{collections::BTreeMap, io::Write}; use std::{borrow::Cow, collections::BTreeMap, io::Write};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
...@@ -21,11 +21,12 @@ use swc_core::{ ...@@ -21,11 +21,12 @@ use swc_core::{
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, NonLocalValue, OperationVc, ResolvedVc, TryFlatJoinIterExt, Vc, trace::TraceRawVcs, FxIndexMap, NonLocalValue, OperationVc, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc,
trace::TraceRawVcs,
}; };
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath, rope::RopeBuilder}; use turbo_tasks_fs::{self, File, FileContent, FileSystemPath, rope::RopeBuilder};
use turbopack_core::{ use turbopack_core::{
asset::AssetContent, asset::{Asset, AssetContent},
chunk::{ chunk::{
ChunkItem, ChunkItemExt, ChunkableModule, ChunkingContext, EvaluatableAsset, ModuleId, ChunkItem, ChunkItemExt, ChunkableModule, ChunkingContext, EvaluatableAsset, ModuleId,
}, },
...@@ -34,10 +35,9 @@ use turbopack_core::{ ...@@ -34,10 +35,9 @@ use turbopack_core::{
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
module_graph::{ModuleGraph, ModuleGraphLayer, async_module_info::AsyncModulesInfo}, module_graph::{ModuleGraph, ModuleGraphLayer, async_module_info::AsyncModulesInfo},
output::OutputAsset, output::{OutputAsset, OutputAssetsReference},
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType}, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::ModulePart, resolve::ModulePart,
virtual_output::VirtualOutputAsset,
virtual_source::VirtualSource, virtual_source::VirtualSource,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
...@@ -45,9 +45,6 @@ use turbopack_ecmascript::{ ...@@ -45,9 +45,6 @@ use turbopack_ecmascript::{
tree_shake::part::module::EcmascriptModulePartAsset, tree_shake::part::module::EcmascriptModulePartAsset,
}; };
/// Metadata for a server action: (layer, exported_name, filename)
type ActionMetadata = (ActionLayer, String, String);
#[turbo_tasks::value] #[turbo_tasks::value]
pub(crate) struct ServerActionsManifest { pub(crate) struct ServerActionsManifest {
pub loader: ResolvedVc<Box<dyn EvaluatableAsset>>, pub loader: ResolvedVc<Box<dyn EvaluatableAsset>>,
...@@ -79,7 +76,8 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -79,7 +76,8 @@ pub(crate) async fn create_server_actions_manifest(
.context("loader module must be evaluatable")?; .context("loader module must be evaluatable")?;
let chunk_item = loader.as_chunk_item(module_graph, chunking_context); let chunk_item = loader.as_chunk_item(module_graph, chunking_context);
let manifest = build_manifest( let manifest = ResolvedVc::upcast(
ServerActionManifestAsset::new(
node_root, node_root,
page_name, page_name,
runtime, runtime,
...@@ -87,7 +85,9 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -87,7 +85,9 @@ pub(crate) async fn create_server_actions_manifest(
chunk_item, chunk_item,
module_graph.async_module_info(), module_graph.async_module_info(),
) )
.await?; .to_resolved()
.await?,
);
Ok(ServerActionsManifest { Ok(ServerActionsManifest {
loader: evaluable, loader: evaluable,
manifest, manifest,
...@@ -155,79 +155,133 @@ pub(crate) async fn build_server_actions_loader( ...@@ -155,79 +155,133 @@ pub(crate) async fn build_server_actions_loader(
/// Builds a manifest containing every action's hashed id, with an internal /// Builds a manifest containing every action's hashed id, with an internal
/// module id which exports a function using that hashed name. /// module id which exports a function using that hashed name.
async fn build_manifest( #[turbo_tasks::value]
struct ServerActionManifestAsset {
node_root: FileSystemPath, node_root: FileSystemPath,
page_name: RcStr, page_name: RcStr,
runtime: NextRuntime, runtime: NextRuntime,
actions: Vc<AllActions>, actions: ResolvedVc<AllActions>,
chunk_item: Vc<Box<dyn ChunkItem>>, chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
async_module_info: Vc<AsyncModulesInfo>, async_module_info: ResolvedVc<AsyncModulesInfo>,
) -> Result<ResolvedVc<Box<dyn OutputAsset>>> { }
let manifest_path_prefix = &page_name;
let manifest_path = node_root.join(&format!( #[turbo_tasks::value_impl]
impl ServerActionManifestAsset {
#[turbo_tasks::function]
pub fn new(
node_root: FileSystemPath,
page_name: RcStr,
runtime: NextRuntime,
actions: ResolvedVc<AllActions>,
chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
async_module_info: ResolvedVc<AsyncModulesInfo>,
) -> Vc<Self> {
Self {
node_root,
page_name,
runtime,
actions,
chunk_item,
async_module_info,
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl OutputAsset for ServerActionManifestAsset {
#[turbo_tasks::function]
fn path(&self) -> Result<Vc<FileSystemPath>> {
let manifest_path_prefix = &self.page_name;
let manifest_path = self.node_root.join(&format!(
"server/app{manifest_path_prefix}/server-reference-manifest.json", "server/app{manifest_path_prefix}/server-reference-manifest.json",
))?; ))?;
let mut manifest = ServerReferenceManifest { Ok(manifest_path.cell())
..Default::default() }
}; }
#[turbo_tasks::value_impl]
impl OutputAssetsReference for ServerActionManifestAsset {}
#[turbo_tasks::value_impl]
impl Asset for ServerActionManifestAsset {
#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<AssetContent>> {
let mut manifest: ServerReferenceManifest = Default::default();
let key = format!("app{page_name}"); let key = format!("app{}", self.page_name);
let actions_value = actions.await?; let actions_value = self.actions.await?;
let loader_id = chunk_item.id().await?; let loader_id = self.chunk_item.id().await?;
let loader_id = match &loader_id { let loader_id = match &loader_id {
ModuleId::Number(id) => ActionManifestModuleId::Number(*id), ModuleId::Number(id) => ActionManifestModuleId::Number(*id),
ModuleId::String(id) => ActionManifestModuleId::String(id), ModuleId::String(id) => ActionManifestModuleId::String(id),
}; };
let mapping = match runtime { let mapping = match self.runtime {
NextRuntime::Edge => &mut manifest.edge, NextRuntime::Edge => &mut manifest.edge,
NextRuntime::NodeJs => &mut manifest.node, NextRuntime::NodeJs => &mut manifest.node,
}; };
// Collect all the action metadata including filenames and location struct ActionMetadata<'a> {
let mut action_metadata: Vec<(String, ActionMetadata)> = Vec::new(); exported_name: &'a str,
for (hash_id, (layer, meta, module)) in actions_value.iter() { filename: Cow<'a, str>,
// Use source_path from the action comment if available (contains original .ts/.tsx path), }
// otherwise fall back to module.ident().path() (may be compiled .js path)
let action_metadata: Vec<(&str, ActionMetadata<'_>)> = actions_value
.iter()
.map(async |(hash_id, (_layer, meta, module))| {
// Use source_path from the action comment if available (contains original .ts/.tsx
// path), otherwise fall back to module.ident().path() (may be compiled .js
// path)
let filename = if !meta.source_path.is_empty() { let filename = if !meta.source_path.is_empty() {
meta.source_path.clone() Cow::Borrowed(&*meta.source_path)
} else { } else {
module.ident().await?.path.to_string() Cow::Owned(module.ident().await?.path.to_string())
}; };
action_metadata.push((hash_id.clone(), (*layer, meta.name.clone(), filename))); Ok((
} &**hash_id,
ActionMetadata {
exported_name: &meta.name,
filename,
},
))
})
.try_join()
.await?;
// Now create the manifest entries // Now create the manifest entries
for (hash_id, (_layer, name, filename)) in &action_metadata { for (
let entry = mapping.entry(hash_id.as_str()).or_default(); hash_id,
ActionMetadata {
exported_name,
filename,
},
) in &action_metadata
{
let entry = mapping.entry(hash_id).or_default();
entry.workers.insert( entry.workers.insert(
&key, &key,
ActionManifestWorkerEntry { ActionManifestWorkerEntry {
module_id: loader_id.clone(), module_id: loader_id.clone(),
is_async: async_module_info is_async: self
.is_async(chunk_item.module().to_resolved().await?) .async_module_info
.is_async(self.chunk_item.module().to_resolved().await?)
.await?, .await?,
exported_name: name.as_str(), exported_name,
filename: filename.as_str(), filename: filename.as_ref(),
}, },
); );
// Hoist the filename and exported_name to the entry level // Hoist the filename and exported_name to the entry level
entry.exported_name = name.as_str(); entry.exported_name = exported_name;
entry.filename = filename.as_str(); entry.filename = filename.as_ref();
} }
Ok(ResolvedVc::upcast( Ok(AssetContent::file(
VirtualOutputAsset::new(
manifest_path,
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(&manifest)?)).cell(), FileContent::Content(File::from(serde_json::to_string_pretty(&manifest)?)).cell(),
),
)
.to_resolved()
.await?,
)) ))
}
} }
/// The ActionBrowser layer's module is in the Client context, and we need to /// The ActionBrowser layer's module is in the Client context, and we need to
......
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