Unverified Commit 656202fe authored by Justin Ridgewell's avatar Justin Ridgewell Committed by GitHub

turbopack: Implement Server Actions from Client Components (#57391)

### What?

This completes Turbopack's Server Actions implementation!

It also cleans up several things:
- Removes `server_actions` configuration, it's enabled by default now.
- Fixes the transform that runs in the SSR layer (it actually needs to
use the client transform)
- Generates a new encryption key

### Why?

### How?

It crawls the client layer modules for additional Server Actions
imports, and adds them to our generated `actions.js` entry point.

Closes NEXT-
Fixes #


Closes WEB-1854

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 1038fd53
......@@ -9,6 +9,7 @@ use next_core::{
get_edge_resolve_options_context,
mode::NextMode,
next_app::{
app_client_references_chunks::get_app_server_reference_modules,
get_app_client_references_chunks, get_app_client_shared_chunks, get_app_page_entry,
get_app_route_entry, metadata::route::get_app_metadata_route_entry, AppEntry, AppPage,
},
......@@ -823,7 +824,8 @@ impl AppEndpoint {
evaluatable_assets.push(evaluatable);
let (loader, manifest) = create_server_actions_manifest(
app_entry.rsc_entry,
Vc::upcast(app_entry.rsc_entry),
get_app_server_reference_modules(client_reference_types),
node_root,
&app_entry.pathname,
&app_entry.original_name,
......@@ -833,9 +835,7 @@ impl AppEndpoint {
)
.await?;
server_assets.push(manifest);
if let Some(loader) = loader {
evaluatable_assets.push(loader);
}
let files = chunking_context.evaluated_chunk_group(
app_entry.rsc_entry.ident(),
......@@ -973,7 +973,8 @@ impl AppEndpoint {
this.app_project.rsc_runtime_entries().await?.clone_value();
let (loader, manifest) = create_server_actions_manifest(
app_entry.rsc_entry,
Vc::upcast(app_entry.rsc_entry),
get_app_server_reference_modules(client_reference_types),
node_root,
&app_entry.pathname,
&app_entry.original_name,
......@@ -983,9 +984,7 @@ impl AppEndpoint {
)
.await?;
server_assets.push(manifest);
if let Some(loader) = loader {
evaluatable_assets.push(loader);
}
let rsc_chunk = this
.app_project
......
use std::io::Write;
use std::{io::Write, iter::once};
use anyhow::{bail, Result};
use indexmap::IndexMap;
......@@ -16,13 +16,13 @@ use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPath},
turbopack::{
core::{
asset::AssetContent,
asset::{Asset, AssetContent},
chunk::{ChunkItemExt, ChunkableModule, EvaluatableAsset},
context::AssetContext,
module::Module,
output::OutputAsset,
reference::primary_referenced_modules,
reference_type::ReferenceType,
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
virtual_output::VirtualOutputAsset,
virtual_source::VirtualSource,
},
......@@ -42,18 +42,16 @@ use turbopack_binding::{
/// If Server Actions are not enabled, this returns an empty manifest and a None
/// loader.
pub(crate) async fn create_server_actions_manifest(
entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
rsc_entry: Vc<Box<dyn Module>>,
server_reference_modules: Vc<Vec<Vc<Box<dyn Module>>>>,
node_root: Vc<FileSystemPath>,
pathname: &str,
page_name: &str,
runtime: NextRuntime,
asset_context: Vc<Box<dyn AssetContext>>,
chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
) -> Result<(
Option<Vc<Box<dyn EvaluatableAsset>>>,
Vc<Box<dyn OutputAsset>>,
)> {
let actions = get_actions(Vc::upcast(entry));
) -> Result<(Vc<Box<dyn EvaluatableAsset>>, Vc<Box<dyn OutputAsset>>)> {
let actions = get_actions(rsc_entry, server_reference_modules, asset_context);
let loader = build_server_actions_loader(node_root, page_name, actions, asset_context).await?;
let Some(evaluable) = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(loader).await?
else {
......@@ -66,7 +64,7 @@ pub(crate) async fn create_server_actions_manifest(
.to_string();
let manifest =
build_manifest(node_root, pathname, page_name, runtime, actions, loader_id).await?;
Ok((Some(evaluable), manifest))
Ok((evaluable, manifest))
}
/// Builds the "action loader" entry point, which reexports every found action
......@@ -101,7 +99,7 @@ async fn build_server_actions_loader(
",
)?;
}
import_map.insert(module_name, *module);
import_map.insert(module_name, module.1);
}
write!(contents, "}});")?;
......@@ -147,17 +145,15 @@ async fn build_manifest(
NextRuntime::NodeJs => &mut manifest.node,
};
for value in actions_value.values() {
let value = value.await?;
for hash in value.keys() {
for ((layer, _), action_map) in actions_value {
let action_map = action_map.await?;
for hash in action_map.keys() {
let entry = mapping.entry(hash.clone()).or_default();
entry.workers.insert(
format!("app{page_name}"),
ActionManifestWorkerEntry::String(loader_id_value.clone_value()),
);
entry
.layer
.insert(format!("app{page_name}"), ActionLayer::Rsc);
entry.layer.insert(format!("app{page_name}"), *layer);
}
}
......@@ -171,10 +167,22 @@ async fn build_manifest(
/// comment which identifies server actions. Every found server action will be
/// returned along with the module which exports that action.
#[turbo_tasks::function]
async fn get_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<ModuleActionMap>> {
async fn get_actions(
rsc_entry: Vc<Box<dyn Module>>,
server_reference_modules: Vc<Vec<Vc<Box<dyn Module>>>>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<ModuleActionMap>> {
let mut all_actions = NonDeterministic::new()
.skip_duplicates()
.visit([module], get_referenced_modules)
.visit(
once((ActionLayer::Rsc, rsc_entry)).chain(
server_reference_modules
.await?
.iter()
.map(|m| (ActionLayer::ActionBrowser, *m)),
),
get_referenced_modules,
)
.await
.completed()?
.into_inner()
......@@ -183,6 +191,25 @@ async fn get_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<ModuleActionMap>>
.try_flat_join()
.await?
.into_iter()
.map(|((layer, module), actions)| {
let module = if layer == ActionLayer::Rsc {
module
} else {
// The ActionBrowser layer's module is in the Client context, and we need to
// bring it into the RSC context.
let source = VirtualSource::new(
module.ident().path().join("action.js".to_string()),
module.content(),
);
asset_context.process(
Vc::upcast(source),
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
)),
)
};
((layer, module), actions)
})
.collect::<IndexMap<_, _>>();
all_actions.sort_keys();
......@@ -192,11 +219,11 @@ async fn get_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<ModuleActionMap>>
/// Our graph traversal visitor, which finds the primary modules directly
/// referenced by [parent].
async fn get_referenced_modules(
parent: Vc<Box<dyn Module>>,
) -> Result<impl Iterator<Item = Vc<Box<dyn Module>>> + Send> {
primary_referenced_modules(parent)
(layer, module): (ActionLayer, Vc<Box<dyn Module>>),
) -> Result<impl Iterator<Item = (ActionLayer, Vc<Box<dyn Module>>)> + Send> {
primary_referenced_modules(module)
.await
.map(|modules| modules.clone_value().into_iter())
.map(|modules| modules.clone_value().into_iter().map(move |m| (layer, m)))
}
/// Inspects the comments inside [module] looking for the magic actions comment.
......@@ -231,19 +258,21 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap
/// Converts our cached [parsed_actions] call into a data type suitable for
/// collecting into a flat-mapped [IndexMap].
async fn parse_actions_filter_map(
module: Vc<Box<dyn Module>>,
) -> Result<Option<(Vc<Box<dyn Module>>, Vc<ActionMap>)>> {
(layer, module): (ActionLayer, Vc<Box<dyn Module>>),
) -> Result<Option<((ActionLayer, Vc<Box<dyn Module>>), Vc<ActionMap>)>> {
parse_actions(module).await.map(|option_action_map| {
option_action_map
.clone_value()
.map(|action_map| (module, action_map))
.map(|action_map| ((layer, module), action_map))
})
}
type LayerModuleActionMap = IndexMap<(ActionLayer, Vc<Box<dyn Module>>), Vc<ActionMap>>;
/// A mapping of every module which exports a Server Action, with the hashed id
/// and exported name of each found action.
#[turbo_tasks::value(transparent)]
struct ModuleActionMap(IndexMap<Vc<Box<dyn Module>>, Vc<ActionMap>>);
struct ModuleActionMap(LayerModuleActionMap);
#[turbo_tasks::value_impl]
impl ModuleActionMap {
......
......@@ -40,6 +40,8 @@ use turbopack_binding::{
},
};
const ECMASCRIPT_CLIENT_TRANSITION_NAME: &str = "next-ecmascript-client-reference";
#[turbo_tasks::value]
pub struct AppEntries {
/// All app entries.
......@@ -140,8 +142,6 @@ pub async fn get_app_entries(
transitions.insert("next-ssr".to_string(), Vc::upcast(ssr_transition));
const ECMASCRIPT_CLIENT_TRANSITION_NAME: &str = "next-ecmascript-client-reference";
transitions.insert(
ECMASCRIPT_CLIENT_TRANSITION_NAME.to_string(),
Vc::upcast(NextEcmascriptClientReferenceTransition::new(
......
use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, TryJoinIterExt, Vc};
use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, TryFlatJoinIterExt, TryJoinIterExt, Vc,
};
use turbopack_binding::turbopack::{
core::{chunk::ChunkingContextExt, output::OutputAssets},
core::{chunk::ChunkingContextExt, module::Module, output::OutputAssets},
ecmascript::chunk::EcmascriptChunkingContext,
};
......@@ -70,3 +72,27 @@ pub async fn get_app_client_references_chunks(
Ok(Vc::cell(app_client_references_chunks))
}
/// Crawls all modules emitted in the client transition, returning a list of all
/// client JS modules.
#[turbo_tasks::function]
pub async fn get_app_server_reference_modules(
app_client_reference_types: Vc<ClientReferenceTypes>,
) -> Result<Vc<Vec<Vc<Box<dyn Module>>>>> {
Ok(Vc::cell(
app_client_reference_types
.await?
.iter()
.map(|client_reference_ty| async move {
Ok(match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) => {
let ecmascript_client_reference_ref = ecmascript_client_reference.await?;
Some(Vc::upcast(ecmascript_client_reference_ref.client_module))
}
_ => None,
})
})
.try_flat_join()
.await?,
))
}
......@@ -298,27 +298,6 @@ pub async fn get_next_server_import_map(
ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } => {
import_map.insert_exact_alias(
"private-next-rsc-action-proxy",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-proxy",
),
);
import_map.insert_exact_alias(
"private-next-rsc-action-client-wrapper",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper",
),
);
import_map.insert_exact_alias(
"private-next-rsc-action-validate",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-validate",
),
);
import_map.insert_exact_alias(
"next/head",
request_to_import_mapping(project_path, "next/dist/client/components/noop-head"),
......@@ -579,9 +558,7 @@ async fn insert_next_server_special_aliases(
// see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531
match ty {
ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. }
| ServerContextType::AppSSR { .. } => {
ServerContextType::Pages { .. } | ServerContextType::PagesData { .. } => {
insert_exact_alias_map(
import_map,
project_path,
......@@ -596,6 +573,7 @@ async fn insert_next_server_special_aliases(
// TODO: should include `ServerContextType::PagesApi` routes, but that type doesn't exist.
ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::Middleware => {
insert_exact_alias_map(
import_map,
......@@ -828,6 +806,35 @@ async fn insert_next_shared_aliases(
request_to_import_mapping(project_path, "next/dist/compiled/setimmediate"),
);
import_map.insert_exact_alias(
"private-next-rsc-action-proxy",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-proxy",
),
);
import_map.insert_exact_alias(
"private-next-rsc-action-client-wrapper",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper",
),
);
import_map.insert_exact_alias(
"private-next-rsc-action-validate",
request_to_import_mapping(
project_path,
"next/dist/build/webpack/loaders/next-flight-loader/action-validate",
),
);
import_map.insert_exact_alias(
"private-next-rsc-action-encryption",
request_to_import_mapping(
project_path,
"next/dist/server/app-render/action-encryption",
),
);
insert_turbopack_dev_alias(import_map);
insert_package_alias(
import_map,
......
......@@ -4,7 +4,8 @@ pub(crate) mod client_reference_manifest;
use std::collections::HashMap;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput};
use crate::next_config::Rewrites;
......@@ -183,7 +184,20 @@ pub enum ActionManifestWorkerEntry {
Number(f64),
}
#[derive(Serialize, Debug)]
#[derive(
Debug,
Copy,
Clone,
Hash,
Eq,
PartialEq,
Ord,
PartialOrd,
TaskInput,
TraceRawVcs,
Serialize,
Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum ActionLayer {
Rsc,
......
......@@ -39,7 +39,8 @@ pub async fn get_next_server_transforms_rules(
(false, Some(pages_dir))
}
ServerContextType::AppSSR { .. } => {
rules.push(get_server_actions_transform_rule(ActionsTransform::Server));
// Yah, this is SSR, but this is still treated as a Client transform layer.
rules.push(get_server_actions_transform_rule(ActionsTransform::Client));
(false, None)
}
ServerContextType::AppRSC {
......
......@@ -40,7 +40,9 @@ struct NextServerActions {
impl CustomTransformer for NextServerActions {
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
let mut actions = server_actions(
&FileName::Real(ctx.file_path_str.into()),
// The same action can be imported by both server and client, and we need to give both
// types a distinct Action hash ID.
&FileName::Real(format!("{}_{:?}", ctx.file_path_str, self.transform).into()),
Config {
is_server: matches!(self.transform, ActionsTransform::Server),
enabled: true,
......
......@@ -126,6 +126,7 @@ import { clearModuleContext } from '../render-server'
import type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'
import { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'
import type { LoadableManifest } from '../../load-components'
import { generateRandomActionKeyRaw } from '../../app-render/action-encryption-utils'
const wsServer = new ws.Server({ noServer: true })
......@@ -736,12 +737,12 @@ async function startWatcher(opts: SetupOpts) {
return manifest
}
function mergeActionManifests(manifests: Iterable<ActionManifest>) {
async function mergeActionManifests(manifests: Iterable<ActionManifest>) {
type ActionEntries = ActionManifest['edge' | 'node']
const manifest: ActionManifest = {
node: {},
edge: {},
encryptionKey: '',
encryptionKey: await generateRandomActionKeyRaw(true),
}
function mergeActionIds(
......@@ -761,7 +762,6 @@ async function startWatcher(opts: SetupOpts) {
for (const m of manifests) {
mergeActionIds(manifest.node, m.node)
mergeActionIds(manifest.edge, m.edge)
manifest.encryptionKey = m.encryptionKey
}
return manifest
......@@ -909,7 +909,9 @@ async function startWatcher(opts: SetupOpts) {
}
async function writeActionManifest(): Promise<void> {
const actionManifest = mergeActionManifests(actionManifests.values())
const actionManifest = await mergeActionManifests(
actionManifests.values()
)
const actionManifestJsonPath = path.join(
distDir,
'server',
......
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