Unverified Commit 51d6e765 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Avoid server action function indirection in Turbopack (#71628)

parent e9b18d64
...@@ -3,7 +3,9 @@ use std::{collections::BTreeMap, io::Write, iter::once}; ...@@ -3,7 +3,9 @@ use std::{collections::BTreeMap, io::Write, iter::once};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::map::Entry; use indexmap::map::Entry;
use next_core::{ use next_core::{
next_manifests::{ActionLayer, ActionManifestWorkerEntry, ServerReferenceManifest}, next_manifests::{
ActionLayer, ActionManifestModuleId, ActionManifestWorkerEntry, ServerReferenceManifest,
},
util::NextRuntime, util::NextRuntime,
}; };
use swc_core::{ use swc_core::{
...@@ -22,7 +24,7 @@ use turbo_tasks::{ ...@@ -22,7 +24,7 @@ use turbo_tasks::{
use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath}; use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::AssetContent, asset::AssetContent,
chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, EvaluatableAsset}, chunk::{ChunkItem, ChunkItemExt, ChunkableModule, ChunkingContext, EvaluatableAsset},
context::AssetContext, context::AssetContext,
file_source::FileSource, file_source::FileSource,
module::{Module, Modules}, module::{Module, Modules},
...@@ -69,11 +71,8 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -69,11 +71,8 @@ pub(crate) async fn create_server_actions_manifest(
.await? .await?
.context("loader module must be evaluatable")?; .context("loader module must be evaluatable")?;
let loader_id = loader let chunk_item = loader.as_chunk_item(Vc::upcast(chunking_context));
.as_chunk_item(Vc::upcast(chunking_context)) let manifest = build_manifest(node_root, page_name, runtime, actions, chunk_item).await?;
.id()
.to_string();
let manifest = build_manifest(node_root, page_name, runtime, actions, loader_id).await?;
Ok(ServerActionsManifest { Ok(ServerActionsManifest {
loader: evaluable, loader: evaluable,
manifest, manifest,
...@@ -96,11 +95,11 @@ async fn build_server_actions_loader( ...@@ -96,11 +95,11 @@ async fn build_server_actions_loader(
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { ) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
let actions = actions.await?; let actions = actions.await?;
// Every module which exports an action (that is accessible starting from our // Every module which exports an action (that is accessible starting from
// app page entry point) will be present. We generate a single loader file // our app page entry point) will be present. We generate a single loader
// which lazily imports the respective module's chunk_item id and invokes // file which re-exports the respective module's action function using the
// the exported action function. // hashed ID as export name.
let mut contents = RopeBuilder::from("__turbopack_export_value__({\n"); let mut contents = RopeBuilder::from("");
let mut import_map = FxIndexMap::default(); let mut import_map = FxIndexMap::default();
for (hash_id, (_layer, name, module)) in actions.iter() { for (hash_id, (_layer, name, module)) in actions.iter() {
let index = import_map.len(); let index = import_map.len();
...@@ -109,11 +108,9 @@ async fn build_server_actions_loader( ...@@ -109,11 +108,9 @@ async fn build_server_actions_loader(
.or_insert_with(|| format!("ACTIONS_MODULE{index}").into()); .or_insert_with(|| format!("ACTIONS_MODULE{index}").into());
writeln!( writeln!(
contents, contents,
" '{hash_id}': (...args) => Promise.resolve(require('{module_name}')).then(mod => \ "export {{{name} as '{hash_id}'}} from '{module_name}'"
(0, mod['{name}'])(...args)),",
)?; )?;
} }
write!(contents, "}});")?;
let output_path = let output_path =
project_path.join(format!(".next-internal/server/app{page_name}/actions.js").into()); project_path.join(format!(".next-internal/server/app{page_name}/actions.js").into());
...@@ -143,7 +140,7 @@ async fn build_manifest( ...@@ -143,7 +140,7 @@ async fn build_manifest(
page_name: RcStr, page_name: RcStr,
runtime: NextRuntime, runtime: NextRuntime,
actions: Vc<AllActions>, actions: Vc<AllActions>,
loader_id: Vc<RcStr>, chunk_item: Vc<Box<dyn ChunkItem>>,
) -> Result<Vc<Box<dyn OutputAsset>>> { ) -> Result<Vc<Box<dyn OutputAsset>>> {
let manifest_path_prefix = &page_name; let manifest_path_prefix = &page_name;
let manifest_path = node_root let manifest_path = node_root
...@@ -155,7 +152,7 @@ async fn build_manifest( ...@@ -155,7 +152,7 @@ async fn build_manifest(
let key = format!("app{page_name}"); let key = format!("app{page_name}");
let actions_value = actions.await?; let actions_value = actions.await?;
let loader_id_value = loader_id.await?; let loader_id = chunk_item.id().to_string().await?;
let mapping = match runtime { let mapping = match runtime {
NextRuntime::Edge => &mut manifest.edge, NextRuntime::Edge => &mut manifest.edge,
NextRuntime::NodeJs => &mut manifest.node, NextRuntime::NodeJs => &mut manifest.node,
...@@ -165,7 +162,10 @@ async fn build_manifest( ...@@ -165,7 +162,10 @@ async fn build_manifest(
let entry = mapping.entry(hash_id.as_str()).or_default(); let entry = mapping.entry(hash_id.as_str()).or_default();
entry.workers.insert( entry.workers.insert(
&key, &key,
ActionManifestWorkerEntry::String(loader_id_value.as_str()), ActionManifestWorkerEntry {
module_id: ActionManifestModuleId::String(loader_id.as_str()),
is_async: *chunk_item.is_self_async().await?,
},
); );
entry.layer.insert(&key, *layer); entry.layer.insert(&key, *layer);
} }
......
...@@ -194,9 +194,16 @@ pub struct ActionManifestEntry<'a> { ...@@ -194,9 +194,16 @@ pub struct ActionManifestEntry<'a> {
} }
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")] pub struct ActionManifestWorkerEntry<'a> {
#[serde(rename = "moduleId")]
pub module_id: ActionManifestModuleId<'a>,
#[serde(rename = "async")]
pub is_async: bool,
}
#[derive(Serialize, Debug)]
#[serde(untagged)] #[serde(untagged)]
pub enum ActionManifestWorkerEntry<'a> { pub enum ActionManifestModuleId<'a> {
String(&'a str), String(&'a str),
Number(f64), Number(f64),
} }
......
...@@ -55,11 +55,7 @@ const PLUGIN_NAME = 'FlightClientEntryPlugin' ...@@ -55,11 +55,7 @@ const PLUGIN_NAME = 'FlightClientEntryPlugin'
type Actions = { type Actions = {
[actionId: string]: { [actionId: string]: {
workers: { workers: {
[name: string]: [name: string]: { moduleId: string | number; async: boolean }
| { moduleId: string | number; async: boolean }
// TODO: This is legacy for Turbopack, and needs to be changed to the
// object above.
| string
} }
// Record which layer the action is in (rsc or sc_action), in the specific entry. // Record which layer the action is in (rsc or sc_action), in the specific entry.
layer: { layer: {
......
...@@ -26,7 +26,6 @@ export function createServerModuleMap({ ...@@ -26,7 +26,6 @@ export function createServerModuleMap({
let workerEntry: let workerEntry:
| { moduleId: string | number; async: boolean } | { moduleId: string | number; async: boolean }
| string
| undefined | undefined
if (workStore) { if (workStore) {
...@@ -46,10 +45,6 @@ export function createServerModuleMap({ ...@@ -46,10 +45,6 @@ export function createServerModuleMap({
return undefined return undefined
} }
if (typeof workerEntry === 'string') {
return { id: workerEntry, name: id, chunks: [] }
}
const { moduleId, async } = workerEntry const { moduleId, async } = workerEntry
return { id: moduleId, name: id, chunks: [], async } return { id: moduleId, name: id, chunks: [], async }
......
...@@ -679,7 +679,7 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -679,7 +679,7 @@ export function cache(kind: string, id: string, fn: any) {
moduleMap: isEdgeRuntime moduleMap: isEdgeRuntime
? clientReferenceManifest.edgeRscModuleMapping ? clientReferenceManifest.edgeRscModuleMapping
: clientReferenceManifest.rscModuleMapping, : clientReferenceManifest.rscModuleMapping,
serverModuleMap: null, serverModuleMap: getServerModuleMap(),
} }
return createFromReadableStream(stream, { return createFromReadableStream(stream, {
......
'use client'
import { ReactNode } from 'react'
import { useActionState } from 'react'
export function Form({
action,
children,
}: {
action: () => Promise<string>
children: ReactNode
}) {
const [result, formAction] = useActionState(action, 'initial')
return (
<form action={formAction}>
<button>Submit</button>
<p>{result}</p>
{children}
</form>
)
}
import { connection } from 'next/server'
export default async function DynamicLayout({
children,
}: {
children: React.ReactNode
}) {
// TODO: This is a workaround for Turbopack. Figure out why this fails during
// prerendering with:
// TypeError: Cannot read properties of undefined (reading 'Form')
await connection()
return children
}
import { Form } from './form'
async function action() {
'use server'
return 'result'
}
export default async function Page() {
'use cache'
return (
<Form action={action}>
<p>{Date.now()}</p>
</Form>
)
}
...@@ -231,4 +231,14 @@ describe('use-cache', () => { ...@@ -231,4 +231,14 @@ describe('use-cache', () => {
expect(meta.headers['x-next-cache-tags']).toContain('a,c,b') expect(meta.headers['x-next-cache-tags']).toContain('a,c,b')
}) })
} }
it('can reference server actions in "use cache" functions', async () => {
const browser = await next.browser('/with-server-action')
expect(await browser.elementByCss('p').text()).toBe('initial')
await browser.elementByCss('button').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('result')
})
})
}) })
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